<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Coding | Hey, ruX is here.</title>
	<atom:link href="https://rux.vc/topics/coding/feed/" rel="self" type="application/rss+xml" />
	<link>https://rux.vc</link>
	<description>Delivering things - from code to product</description>
	<lastBuildDate>Mon, 12 Jun 2023 14:14:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.8</generator>
<site xmlns="com-wordpress:feed-additions:1">162978439</site>	<item>
		<title>Solidity is NOT JavaScript</title>
		<link>https://rux.vc/2023.06/solidity-is-not-javascript/</link>
					<comments>https://rux.vc/2023.06/solidity-is-not-javascript/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Mon, 12 Jun 2023 13:34:47 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[blockchain]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[solidity]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3934</guid>

					<description><![CDATA[<p>As blockchains are expanding their influence, it's quite evident for an ordinary developer that Solidity has almost nothing to do with JavaScript. I'm very particular about compile-time checks and runtime safety when it comes to writing software, and it becomes apparent if you read my other posts. In 2018, when I first came across Ethereum, ... <a title="Solidity is NOT JavaScript" class="read-more" href="https://rux.vc/2023.06/solidity-is-not-javascript/" aria-label="More on Solidity is NOT JavaScript">Read more</a></p>
The post <a href="https://rux.vc/2023.06/solidity-is-not-javascript/">Solidity is NOT JavaScript</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>As blockchains are expanding their influence, it's quite evident for an ordinary developer that Solidity has almost nothing to do with JavaScript.</p>
<p>I'm very particular about compile-time checks and runtime safety when it comes to writing software, and it becomes apparent if you read my other posts. In 2018, when I first came across Ethereum, also known as the 'world computer,' I knew nothing about the technologies behind it except that I'd need to use Solidity for this computer. The <a href="https://docs.soliditylang.org/en/v0.2.2/solidity-by-example.html">Solidity language website v2.2.0</a> stated, <em>&quot;Solidity is a high-level language whose <strong>syntax</strong> is similar to that of <strong>JavaScript</strong>, and it is designed to compile to code for the Ethereum Virtual Machine.&quot;</em></p>
<p>The reference to JavaScript alarmed me. How come someone use a potentially risky language like JavaScript to manage money? I know it mentioned only the syntax, but the reference was strong enough to discourage further exploration in that area, given at that time it didn't look something worth attention.</p>
<p><span id="more-3934"></span></p>
<p>However, it turned out to be the complete opposite: <strong>Solidity is a type-safe, runtime-safe language</strong> that only shares a C-like syntax with JavaScript. Sadly, I discovered this three years later.</p>
<p>I was going to provide some examples here, but I quickly realized that it makes no sense due to the massive differences at the conceptual level. Things like number overflow, limited or no string operations, explicit number casting, manual data location specification, limited local memory, and fixed-sized arrays—none of these are applicable to JavaScript.</p>
<p>Seriously, these things only make sense in Solidity (though not always a good idea):</p>
<ul>
<li>Thoughtfully design the memory layout when inheriting a class for your delegate implementation.</li>
<li>Change the order of variables to align them in words and reduce the cost of reading and writing operations to storage.</li>
<li>Pack array indexes into u256 using binary operations to save on gas.</li>
<li>Check variable values to avoid overflow and underflow.</li>
</ul>
<p>If anything, to me, Solidity is very close to <a href="https://en.wikipedia.org/wiki/C--">C-- with the memory management</a> in terms of syntax and proximity to the &quot;hardware&quot; but couldn't be further from JavaScript.</p>The post <a href="https://rux.vc/2023.06/solidity-is-not-javascript/">Solidity is NOT JavaScript</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2023.06/solidity-is-not-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3934</post-id>	</item>
		<item>
		<title>Project Update: PronounceMe &#8211; implementation details</title>
		<link>https://rux.vc/2019.11/update-pronounceme-implementation-details/</link>
					<comments>https://rux.vc/2019.11/update-pronounceme-implementation-details/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sat, 02 Nov 2019 23:20:57 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[computer vision]]></category>
		<category><![CDATA[moviepy]]></category>
		<category><![CDATA[pixabay]]></category>
		<category><![CDATA[polly]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[pronounceMe]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[rekognition]]></category>
		<category><![CDATA[TTS]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3494</guid>

					<description><![CDATA[<p>I have several post about the PronounceMe project experiments - automatic video and voice generator for English learners. If you missed previous posts please review #pronounceMe for more information about the project, ideas behind and some statistics. In this post I'd focus on the technical implementation with some diagrams and noticeable code snippets. Service diagram ... <a title="Project Update: PronounceMe &#8211; implementation details" class="read-more" href="https://rux.vc/2019.11/update-pronounceme-implementation-details/" aria-label="More on Project Update: PronounceMe &#8211; implementation details">Read more</a></p>
The post <a href="https://rux.vc/2019.11/update-pronounceme-implementation-details/">Project Update: PronounceMe – implementation details</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>I have several post about the PronounceMe project experiments - automatic video and voice generator for English learners. If you missed previous posts please review <a href="/tags/pronounceme/">#pronounceMe</a> for more information about the project, ideas behind and some statistics. In this post I'd focus on the technical implementation with some diagrams and noticeable code snippets.</p>
<p><span id="more-3494"></span></p>
<h2>Service diagram</h2>
<p>Essentially, the service consist number of the components:</p>
<ul>
<li>Terms Database - dataset of the words</li>
<li>Voice generator - engine which generates human-alike voices</li>
<li>Picture lookup service - huge part which is responsible for finding relevant background picture</li>
<li>Video generator - renderer of the video which composes the clips and voices</li>
<li>Youtube Uploader - implementation of the client Youtube API</li>
<li>Management panel - very basic web-based admin panel allowing to observe current status, database and statictics</li>
<li>Statistics extractor - a regular fetching some statistics data</li>
</ul>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/11/services-diagram.png" alt="services diagram" /></p>
<p>The central focus of the service is a Term - one or few words which need to be pronounced. Service is built around the pipeline which takes the term and transforms it into the uploaded Youtube video.</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/11/interaction-diagram.png" alt="pipeline diagram" /></p>
<p>Bear in mind this project is at the MVP stage. That means there are several compromises I have chosen to reduce Time To Market. It's never late to improve code if the project is useful.</p>
<h2>Technologies used</h2>
<p>I could say it uses most-of-the-buzzwords such as Computer Vision, Mesh API, Cloud Services, Docker, Microservices and it won't be a lie. But we always want to see more specifics:</p>
<h3>Generator service:</h3>
<ul>
<li><strong>Kotlin</strong> - of course, there are no other candidates. Most of the engine is built on it</li>
<li><strong>http4k</strong> - webserver written in kotlin, for kotlin</li>
<li><strong>kotlinx-html</strong> - dsl for html. There is <strong>no javascript</strong> in the project as such</li>
<li><strong>kmongo</strong> - as a DAO layer for the db</li>
<li><strong>java-pixabay</strong> - for Pixabay API access, the original project has been abandoned, I had to <a href="https://github.com/ruXlab/pixabay-java-api">fork it</a></li>
</ul>
<h3>Video generator and render</h3>
<p>It's a microservice working in the separate container, communicating with the engine via HTTP</p>
<ul>
<li><strong>python3</strong> - because of moviepy</li>
<li><strong>moviepy</strong> - the best programmatic video generator; I found anything similar for JVM.</li>
<li><strong>imageio</strong> - for image manipulation</li>
<li><strong>cherrypy</strong> - apparently the easiest way to expose python function via http REST service</li>
</ul>
<h3>Infrastructure:</h3>
<ul>
<li><strong>jib</strong> - jvm docker image generator</li>
<li><strong>mongo</strong> - default database for experiments/MVP</li>
<li><strong>docker</strong> - as a runtime</li>
<li><strong>docker-compose</strong> - for container orchestration</li>
<li><strong>docker-machine</strong> - for provisioning</li>
<li><strong>make</strong> - as a frontend for the deployment commands</li>
</ul>
<h3>Cloud API and services:</h3>
<ul>
<li><strong>AWS Rekognition</strong> - cloud computer vision API. It allows to filterout pictures with faces(often they create a lot of noise) and image image labeling for choosing the best picture</li>
<li><strong>AWS Polly</strong> - TTS engine provided by Amazon. Previously I tried one from MS Azure but quality wasn't satisfying. Polly generates nearly perfect voice with different accents</li>
<li><strong>YouTube API</strong> - for video uploads and statistics collection</li>
<li><strong>AWS EC2</strong> - for hosting</li>
<li><strong>PaperTrail</strong> - for logs from the docker containers</li>
</ul>
<h2>Challanges</h2>
<p>Well, there were a lot of issues, mostly related to the external services</p>
<p>1) YouTube API has limitations - each call counts towards <a href="https://developers.google.com/youtube/v3/getting-started">daily quota</a>(which is 1M units). From my experience, it's only possible to upload about <strong>50 videos a day</strong>. Although I'd like to upload way more than limit set that didn't bother me much since the process is automated<br />
2) moviepy heavily leaks memory. From my experiments that after 10 rendered videos python process held about 2Gb of RAM. Since it's MVP I have chosen the simplest solution - just restart microservice. More precisely, to configure docker-swarm <em>to kill it</em> once it consumed too much memory. I believe it's a very practical decision for the given project stage.<br />
3) To make the video stand out from others it has to have a relevant background picture for the term. If the user looks for the &quot;how to pronounce tomato&quot; it's more likely that video with <em>tomato</em> on the background would be chosen rather than one with grey colour. To find images I used <strong>Pixabay API</strong>(if you like service don't forget to donate them too!). For the obvious reasons often some irrelevant pictures are returned, so I had to filter irrelevant pictures using Amazon computer vision.<br />
4) <strong>Imagemagik</strong> policies hurt. It's a great library but I found it tricky to configure since it has a configuration file where defaults are very tight. For example it's impossible to generate video into the <code>/tmp</code> folder by default. Thanks to docker it's very easy to build up the image with embedded configuration.<br />
5) Apparently, <strong>docker-compose</strong>  has changed the behaviour for the container limits so I had to downgrade configuration file from version 3.3 to 2.3<br />
6) I wanted to keep MongoDB outside of the container on the host machine for my personal reasons. If you ever tried to do so you know it's not easy. The container ecosystem is pushing a user to use containers only. I ended up binding <code>/var/lib/mongodb/mongod.sock</code> from host to container and use <code>jnr-unixsocket</code> to make mongo to use unix socket instead of TCP<br />
7) Youtube API documentation seems to be very convoluted, I had a hard time to understand how to go from the simple youtube upload to something like &quot;create a playlist if need and then specify description along with tags and location of the video in different languages&quot;</p>
<h2>Enjoyable parts</h2>
<p>This project is actually quite interesting to work on. It uses many external APIs, works with computer vision(a lot of fun with debugging!), etc</p>
<ul>
<li><strong>kotlin</strong> is soo nice, as usual. Can't imagine myself using python which can expode after every single type or java where I would write a few books and still it's not that clean</li>
<li>Writing web pages in kotlin with <strong>kotlinx-html</strong> is really fun. Just think - statically typed html templates!</li>
<li>Amazon Rekognition works like a <strong>magic</strong>, I'd say in 90% it sees what I'd say about the picture. Prices are very competitive for my use case</li>
<li>Sealed classes work really well for the statistics collection and voices description</li>
<li><strong>kmongo</strong> allows to express db queries via staticly typed DSL. As most ORM it fails on the complex constructions but perfomance of the DB communication is never consern for this project</li>
<li><strong>java-pixabay</strong> library has been outdated, I made a few PRs but author had not got back to me. For that reason I continued to work on my fork - <a href="https://github.com/ruXlab/pixabay-java-api">ruXlab/pixabay-java-api</a></li>
</ul>
<h2>Code snippets</h2>
<p>I'd like to highlight some code used in PronounceMe service</p>
<h3>kotlinx-html templates</h3>
<pre><code class="language-kotlin">
private inline fun &lt;reified T : Any&gt; BODY.dumpListAsTable(
    list: List&lt;T&gt;, fields: Collection&lt;KProperty1&lt;T, *&gt;&gt; = T::class.memberProperties
) = table(&quot;table table-striped table-hover&quot;) {
    thead {
        tr {
            for (field in fields)
                th { +field.name }
        }
    }
    tbody {
        for (row in list) {
            tr {
                for (field in fields)
                    td { +field.get(row).toString() }
            }
        }
    }
}
private fun youtubePlaylists(req: Request): Response = pageTemplate(&quot;Youtube playlists&quot;, autoreload = false) {
    dumpListAsTable(
        youtubeClient.getPlaylists(),
        listOf(YoutubePlaylist::id, YoutubePlaylist::title, YoutubePlaylist::itemsCount, YoutubePlaylist::description)
    )
        . . . .
}

</code></pre>
<p>Outputs:</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/11/pronounceme-frontpage.png" alt="" /></p>
<h3>Navbar and html body</h3>
<pre><code class="language-kotlin">body {
    nav(&quot;navbar navbar-expand-md navbar-dark bg-dark fixed-top&quot;) {
        div(&quot;collapse navbar-collapse&quot;) {
            ul(&quot;navbar-nav mr-auto&quot;) {
                WebApp.webRoutes.filter { it.verb == Method.GET }.forEach {
                    li(&quot;nav-item&quot;) {
                        a(it.url, classes = &quot;nav-link&quot;) {
                            +it.description
                        }
                    }
                }
            }
            ul(&quot;navbar-nav mr-auto&quot;) {
                li(&quot;nav-item&quot;) {
                    if (PronounceApp.isRunning.get()) {
                        h2 {
                            span(&quot;badge badge-danger badge-secondary&quot;) { +&quot;Generator is running&quot; }
                        }
                    } else {
                        form(action = &quot;/forcestart&quot;, method = FormMethod.post, classes = &quot;form-inline&quot;) {
                            button(classes = &quot;btn btn-success&quot;, type = ButtonType.submit) { +&quot;Force start&quot; }
                        }
                    }
                }
                li(&quot;nav-item&quot;) {
                    a(&quot;https://papertrailapp.com/groups/XXXXXXX/events&quot;, &quot;_blank&quot;, &quot;nav-link button&quot;) {
                        +&quot;logs&quot;
                    }
                }
            }
        }
    }
    main {
        h1 { +title }
        builder(this@body)
    }
}

</code></pre>
<p>Result looks like:</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/11/pronounceme-channel-stats.png" alt="" /></p>
<p>Decent design for the private admin panel to be used every once in a few months by a single person, isn't it? :)</p>
<h3>Server and routes</h3>
<p>Handlers are defined as a list of routes with URL and handler function as expected in http4k</p>
<pre><code class="language-kotlin">val webRoutes = listOf(
    Route(GET, &quot;/ping&quot;, &quot;Ping it&quot;) { req -&gt; Response(OK).body(&quot;pong&quot;) },
    Route(GET, &quot;/stat&quot;, &quot;Some stats&quot;, this::stat),
    Route(GET, &quot;/events&quot;, &quot;Recent events&quot;, this::recentEvents),
    Route(GET, &quot;/&quot;, &quot;All urls available&quot;, this::root),
    Route(GET, &quot;/config&quot;, &quot;Runtime config&quot;, this::config),
    Route(GET, &quot;/stat_channel&quot;, &quot;Channel statistics&quot;, this::channelStat),
    Route(GET, &quot;/youtube_playlist&quot;, &quot;YT playlists&quot;, this::youtubePlaylists),

    Route(POST, &quot;/forcestart&quot;, &quot;Force start&quot;, this::forceStart),
    Route(POST, &quot;/createplaylist&quot;, &quot;Create playlist&quot;, this::youtubePlaylistCreate)
)
</code></pre>
<p>The webserver itself is literally 3 lines of code</p>
<pre><code class="language-kotlin">routes(*webRoutes.map { it.url bind it.verb to it.handler }.toTypedArray())
    .asServer(SunHttp(port))
    .start()
</code></pre>
<h3>The heart of the image lookup component:</h3>
<pre><code class="language-kotln">fun findImageForWordWithCandidates(
    word: String,
    category: Category?,
    stopList: List&lt;String&gt;,
    mandatoryList: List&lt;String&gt;? = null,
    allowFaces: Boolean = false,
    pixabyPage: Int = 1
): ImagesWithCandidates? {
    val stopList = stopList.mapTo(HashSet(), String::toLowerCase)
    val mandatoryList = mandatoryList?.mapTo(HashSet(), String::toLowerCase)
    val allImages = imageLookup.searchPixabay(word, category, pixabyPage)
        ?.shuffled()
        ?.also { log.info(&quot;findImageForWord: got {} images for {}&quot;, it.size, word) }
        ?.mapNotNull {
            // fetch pictures locally
            runCatching {
                ImageRuntimeInfo(it.largeImageURL, URL(it.largeImageURL).asCachedFile(&quot;pixaby-${it.id}-large&quot;), pixaby = it)
            }
            .onFailure { log.warn(&quot;findImageForWord: during image saving&quot;, it) }
            .getOrNull()
        }
    val images = allImages
        // filter pics with faces if necessary
        ?.let { if (allowFaces) it else withoutFaces(word, it) }
        ?.also { log.info(&quot;findImageForWord: got ${it.size} pics after face filtering&quot;) }
        // image labelling
        ?.let { findLabels(word, it) }
        // exclude stop list words
        ?.filterNot { it.normalizedLabels.any { it in stopList } }
        // exclude images without mandatory words
        ?.filter {
            if (mandatoryList == null) true
            else it.normalizedLabels.any { it in mandatoryList }
        }
        ?.also { log.info(&quot;findImageForWord: got ${it.size} pics after filtering by label&quot;) }
        ?: return null

    if (images.isEmpty()) {
        log.warn(&quot;findImageForWord: No eligible images were found for {}&quot;, word)
        return null
    }

    val sortedImagesByConfidence = images
        .map {
            // find the best matches by original word
            val labelWithWord = it.labels
                .sortedByDescending { it.confidence }
                .firstOrNull { it.name.contains(word, ignoreCase = true) }
            it to (labelWithWord?.confidence ?: -1.0F)
        }

    log.debug(&quot;findImageForWord: ${sortedImagesByConfidence.size} candidates for $word: \n{}&quot;,
        sortedImagesByConfidence.joinToString(&quot;\n&quot;) { &quot;   - ${it.first} with ${it.second} confidence&quot; })

    val firstBestMatch = sortedImagesByConfidence
        .firstOrNull { it.second &gt; 0.0F } // return first by confidence
        ?.first

    log.info(&quot;findImageForWord: best match for {} by label in word - {}&quot;,
        word, firstBestMatch)

    if (firstBestMatch != null)
        return ImagesWithCandidates(firstBestMatch, allImages)

    // we don&#039;t have best extact match by word in labels
    val firstMatchByConfidence = sortedImagesByConfidence.firstOrNull()
    log.info(&quot;findImageForWord: good match by confidence for {} - {}&quot;,
        word, firstMatchByConfidence)

    return ImagesWithCandidates(firstMatchByConfidence?.first, allImages)
}

</code></pre>
<h3>Clips compose</h3>
<p><em>Pardon me for my python</em></p>
<pre><code class="language-python">for idx, _ in enumerate(voice_title_clips):
    prevoice_clip = CompositeVideoClip([static, voice_title_clips[idx]], size=screensize)
    prevoice_clip.duration = pre_voice_pause
    postvoice_clip = prevoice_clip.set_duration(post_voice_pause)
    voice_title_clips[idx] = CompositeVideoClip([static, voice_title_clips[idx]], size=screensize)
    voice_title_clips[idx].duration = voice_clips[idx].duration * voice_repeats + voice_repeats_pause_times * voice_clips[idx].duration
    silence_clip = silence.set_duration(voice_clips[idx].duration * voice_repeats_pause_times)
    voice_title_clips[idx].audio = concatenate_audioclips(intersperse([voice_clips[idx]] * voice_repeats, silence_clip))
    clips = [prevoice_clip, voice_title_clips[idx], postvoice_clip, static.set_duration(pause_between)]
    voice_title_clips[idx] = concatenate_videoclips(clips, padding=-1, method=&quot;compose&quot;)
</code></pre>
<h3>What is next</h3>
<p>Subscribe for the blog to see where this project goes. Breaking news is awaiting!</p>
<p>Checkout more project updates from posts grouped by <a href="/tags/pronounceme">#pronounceMe</a> hashtag</p>The post <a href="https://rux.vc/2019.11/update-pronounceme-implementation-details/">Project Update: PronounceMe – implementation details</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.11/update-pronounceme-implementation-details/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3494</post-id>	</item>
		<item>
		<title>Functional Kotlin part 4: collections manipulation</title>
		<link>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/</link>
					<comments>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sat, 02 Nov 2019 13:07:48 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<category><![CDATA[stdlib]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3451</guid>

					<description><![CDATA[<p>This is a part 4 of the #kotlin-showoff series and it's going to be about the standard functions over the collections(mostly iterables to be precise) allowing developer to express data modification in the clean and functional way. General convention Although one might think that kotlin has inherited all the base collection types from the Java ... <a title="Functional Kotlin part 4: collections manipulation" class="read-more" href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/" aria-label="More on Functional Kotlin part 4: collections manipulation">Read more</a></p>
The post <a href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/">Functional Kotlin part 4: collections manipulation</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>This is a part 4 of the <a href="/tags/kotlin-showoff">#kotlin-showoff</a> series and it's going to be about the standard functions over the collections(mostly iterables to be precise) allowing developer to express data modification in the clean and functional way.</p>

<h2>General convention</h2>
<p>Although one might think that kotlin has inherited all the base collection types from the Java it's not quite true. Kotlin transparently maps existing Java collections into the Kotlin by using some tricks such as typealiasing. Collections hierarchy in Kotlin make code even more safer by imposing separation between mutable and immutable data structures. Take a look on the interfaces diagram:</p>
<span id="more-3451"></span>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/collections-diagram.png" alt="diagram originally posted on the kotlinlang.org" /></p>
<p>Having dedicated interfaces for immutable collections makes expressions are purely functional - no need to worry if api consumer modifies list on the way or even worse, attempt to insert into the immutable collection(goodbye <code>UnsupportedOperationException</code>!). Indeed, immutability is enforced in <strong>compile time</strong> by contract.</p>
<h3>A note about Iterable vs Sequence</h3>
<p>Those are very similar types of the base entities even with the same signatures, let's take a look</p>
<pre><code class="language-kotln">public interface Sequence&lt;out T&gt; {
    public operator fun iterator(): Iterator&lt;T&gt;
}

public interface Iterable&lt;out T&gt; {
    public operator fun iterator(): Iterator&lt;T&gt;
}</code></pre>
<p>Those two base classes define the way data will be processed in the chain of the calls:</p>
<ul>
<li>Operations on <code>Iterable</code> produce result immideatelly, so the <em>full</em> intermideate result will be passed between calls in the chain. The result is evaluated <strong>eagerly</strong> after each step.</li>
<li>Operations on the <code>Sequence</code> treat data items comming thorough as it would be an infinite stream, the closest analogy would be java8 <code>Stream</code> or <code>RxObservable</code>.  Items passed via the chain of the calls one by one. Result is evaluated <strong>lazily</strong>.</li>
</ul>
<p>As for now we focus on the <code>Iterable</code> and it's descendants(<code>Collection</code>, <code>List</code>, <code>Map</code>,  etc..) . Luckily, <em>many</em> operations exist for both interfaces with exactly the same  signatures</p>
<h3>Simple list transformations <code>filter</code>, <code>map</code>, <code>forEach</code></h3>
<p>Those are the probably the most widely used operators and they do exactly after their name. The provided function is applied to the each element of the operation</p>
<pre><code class="language-kotlin">val adminNames = users
  .filter { it.isAdmin }
  .map { it.name }

pupils.forEach { 
  println(&quot;${it.name}: ${it.score}&quot;)
}</code></pre>
<h3><code>filter*</code> and <code>map*</code> families</h3>
<p>There are <a href="https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt">way more </a> similar operations provided in the Kotlin stdlib giving extra flexibility when it need:</p>
<pre><code class="language-kotlin">val userList = users
  .filterNotNul()
  .filterNot { it.isBanned }
  .mapTo(mutableHashSet()) { it.userId }
  .mapIndexed { (idx, userId) -&gt; &quot;#${idx}: {it.userId}&quot; }</code></pre>
<p>In many occasions you'll find the same pattern - <code>verb [not] [indexed] [to]</code>. No need to memorise - the names come out intuitively:
<img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-29-22-42-56.png" alt="" />
<img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-29-22-47-14.png" alt="" /></p>
<h3>Operations returning single element: <code>first</code>, <code>last</code>, <code>single</code>, <code>elementAt</code>, <code>get</code></h3>
<p><code>first</code> and <code>last</code> return first and last elements (obviously). </p>
<pre><code class="language-kotlin">val firstUser = users.first()
val firstAdminUser = users.first { it.isAdmin }
val lastBannedUser = users.last { it.isBanned }</code></pre>
<p><code>single</code> returns one element and throws exception if more than 1 element in collection matches the predicate</p>
<pre><code class="language-kotlin">val oneLove = listOf(&quot;java&quot;, &quot;kotlin&quot;,  &quot;javascript&quot;).singleOrNull { it == &quot;kotlin&quot; } </code></pre>
<p>Also those operations can have return alternative value - provided by closure or null:</p>
<pre><code class="language-kotlin">val oneLove = languages.singleOrNull { it == &quot;kotlin&quot; }
val tenthWinnerName = user.getOrElse(10) { &quot;NO WINNER&quot; }
val secondPerson = user.getOrNull(2)</code></pre>
<h3>Aggregation operations <code>count</code>, <code>average</code>, <code>min</code>, <code>max</code></h3>
<p>Again, intuitively those operations perform aggregations:</p>
<pre><code class="language-koltlin">val avgScore = pupils.average { it.score }
val topStudent = pupils.max { it.score }
val channagingStudent = pupils.min { it.score }</code></pre>
<h3>Conditional oprations <code>all</code>, <code>none</code>, <code>count</code>, <code>any</code></h3>
<pre><code class="language-kotlin">val numberOfTopStudents = pupils.count { it.score &gt; 4.5 }
val allPassed = pupils.all { it.score &gt; 2.0 }
val hasNeedleInHaystack = heap.any { it.object == NEEDLE }
val allGood = results.none { it.error != null }</code></pre>
<h3>List to Map transformation <code>associate*</code>,  <code>groupBy</code></h3>
<p>Both operations produce a <code>Map</code> and they are different on how keys are collided. While <code>assciate*</code> simply overwrites existing value with associated key, <code>groupBy</code> adds value to the list of values:</p>
<pre><code class="language-kotlin">val usersById = users.associate { it.id to it } // result type: Map&lt;UserId, User&gt;
val usersById = users.associateBy { it.id } // same output
val pupilsByScore = pupils.groupBy { it.score } // result type Map&lt;Int, List&lt;Pupil&gt;&gt;
</code></pre>
<h3>Many more</h3>
<p>There a way more functional operations over collections are available in Kotlin stdlib such as <code>fold</code>, <code>reduce</code>, <code>minus(-)</code>, <code>plus(+)</code>, <code>contains(in)</code> etc:</p>
<pre><code class="language-kotlin">// result - list of the both users
val allUsers = fbUsers + twitterUsers 

// result - elements of allUserIds which are not in bannedUsersIds
val activeUserIds = allUserIds - bannedUsersIds 

// result - the longest length of the name
val longestName = names.reduce { longest, item -&gt; if (longest.length &lt; item.length) item else longest }

// result - same as above, the longest length of the name
val longestLength = names.map(String::length).fold(0, ::max))

// result - if Wally was there
val isWallyLovesKotlin = &quot;Wally&quot; in kotlinLovers</code></pre>
<p>Those extension functions are very intuitive and widely used, essentially can cover most of the everyday tasks. </p>
<h2>Conclusion</h2>
<p>Kotlin collection functions provide a lot of flexibility to express your ideas and business logic in very concise, clear and functional way</p>
<p>Hopefully you found this article useful for you, please check out other posts by <a href="/tags/kotlin-showoff">#kotlin-showoff</a>  hashtag</p>The post <a href="https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/">Functional Kotlin part 4: collections manipulation</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.11/functional-kotlin-part-4-collections-manipulation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3451</post-id>	</item>
		<item>
		<title>Project update: Alexa London Bus Stop</title>
		<link>https://rux.vc/2019.10/alexa-london-bus-stop-project-update/</link>
					<comments>https://rux.vc/2019.10/alexa-london-bus-stop-project-update/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 09 Oct 2019 18:20:41 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Notes about life in London]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Reality]]></category>
		<category><![CDATA[alexa]]></category>
		<category><![CDATA[alexa-london-bus-stop]]></category>
		<category><![CDATA[London]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[skill]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3454</guid>

					<description><![CDATA[<p>A while ago I have published post about the first skill for Alexa I developed. Personally I use it since then practically every day and I found it very useful. I didn't even bother to check analytics since, well, it does work for me and I expected people to use it as well if it's ... <a title="Project update: Alexa London Bus Stop" class="read-more" href="https://rux.vc/2019.10/alexa-london-bus-stop-project-update/" aria-label="More on Project update: Alexa London Bus Stop">Read more</a></p>
The post <a href="https://rux.vc/2019.10/alexa-london-bus-stop-project-update/">Project update: Alexa London Bus Stop</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>A while ago I have <a href="https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/">published post</a> about the first skill for Alexa I developed. Personally I use it since then practically every day and I found it very useful. I didn't even bother to check analytics since, well, it does work for me and I expected people to use it as well if it's useful.</p>


<p>Thanks to my wife, I recently learnt <a href="https://www.amazon.co.uk/dp/B01N4DKTNY">London Bus Stop</a> skill:</p>


<ul><li>still in the top 30 skills in the area because I'm receiving $100 credit for AWS every month; </li><li>it's not <strong>listed anymore</strong>! That fact slipped through the cracks!</li></ul>


<span id="more-3454"></span>


<h3 class="wp-block-heading">Statistics</h3>


<p>I've noticed that only <strong>20 unique</strong> users are using this skill every month but didn't take attention for that. I wrongly assumed it's related to the low popularity and/or presence of the competitive skills. I was clearly <strong>wrong</strong>. Number of Londoners who have Alexa is only growing, so audience of the skill should.</p>


<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="905" height="715" src="https://rux.vc/wp-content/uploads/2019/10/alexa-skill-no-installs.png" alt="" class="wp-image-3455" srcset="https://rux.vc/wp-content/uploads/2019/10/alexa-skill-no-installs.png 905w, https://rux.vc/wp-content/uploads/2019/10/alexa-skill-no-installs-150x119.png 150w, https://rux.vc/wp-content/uploads/2019/10/alexa-skill-no-installs-300x237.png 300w, https://rux.vc/wp-content/uploads/2019/10/alexa-skill-no-installs-768x607.png 768w" sizes="(max-width: 905px) 100vw, 905px" /></figure>


<p>Clearly no one has enabled skill, even by mistake. It never made me doubt.</p>


<h3 class="wp-block-heading">The issue</h3>


<p>Apparently, Amazon imposed new requirements for the skills and performed some sort of automated testing. It seems that problem was with <strong>session finishing</strong> - skill should be reacting on the default "Quit" intent but it didn't, at least in all required cases. </p>


<p>I didn't receive any notifications or simply ignored them - Amazon sends bunch of the promo emails almost every week regarding new features in Alexa API and toolkit around it. <strong>Disappointing</strong>.</p>


<p>So skill was active for people who already has activated it but new audience can't enabled it anymore. 10 mins fix and Voilá - fixed. Automated review passed in one minute + 4 days for the review by human and skill went back to the listing.</p>


<h3 class="wp-block-heading">5 days statistics since it back</h3>


<figure class="wp-block-image"><img decoding="async" width="906" height="679" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-06-09.png" alt="" class="wp-image-3458" srcset="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-06-09.png 906w, https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-06-09-150x112.png 150w, https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-06-09-300x225.png 300w, https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-06-09-768x576.png 768w" sizes="(max-width: 906px) 100vw, 906px" /></figure>


<p>Skill started to get new audience! </p>


<h3 class="wp-block-heading">Conclusion</h3>


<p>Well, monitor emails? To be honest I can't think of the generic automated system which will check presence in the store listing. This monitoring has to be thought and implemented through parses I suppose? Alternatively, data can be collected from the dashboard and analysed for the down trend.</p>


<p>Will see how it goes, I'll post update some time in the future. Stay tuned.</p>


<p>In meanwhile, if you're in London please checkout the skill and rate should you like it.</p>


<div class="wp-block-image"><figure class="aligncenter is-resized">
<a href="https://www.amazon.co.uk/dp/B01N4DKTNY" target="_blank" rel="noopener noreferrer">
<img decoding="async" src="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-11-18.png" alt="" class="wp-image-3459" width="182" height="197" srcset="https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-11-18.png 279w, https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-11-18-139x150.png 139w, https://rux.vc/wp-content/uploads/2019/10/Screenshot-from-2019-10-09-19-11-18-277x300.png 277w" sizes="(max-width: 182px) 100vw, 182px" /><figcaption>Get the Alex Bus Stops skill</figcaption></a> </figure></div>


<blockquote class="wp-block-quote"><p>Alexa, <strong>open bus stop</strong></p></blockquote>


<p> </p>The post <a href="https://rux.vc/2019.10/alexa-london-bus-stop-project-update/">Project update: Alexa London Bus Stop</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.10/alexa-london-bus-stop-project-update/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3454</post-id>	</item>
		<item>
		<title>Functional kotlin part 3: scoping functions</title>
		<link>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/</link>
					<comments>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 20:57:35 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[productivity]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3427</guid>

					<description><![CDATA[<p>In the part 3 of the series of the posts about kotlin we going to look into the one of the intensively used kotlin extension functions from the standard library - they allow to write very expressive and safe, functionally-looking code. For folks who got lost on the word "extension functions" - it's a way ... <a title="Functional kotlin part 3: scoping functions" class="read-more" href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/" aria-label="More on Functional kotlin part 3: scoping functions">Read more</a></p>
The post <a href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/">Functional kotlin part 3: scoping functions</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>In <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="5" data-gr-id="5">the part</g> 3 of <a href="/tags/kotlin-showoff">the series of the</a> posts about kotlin we going to look into <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="6" data-gr-id="6">the one</g> of the intensively used kotlin <strong>extension</strong> functions from the standard library - they allow to write very expressive and safe, functionally-looking code.</p>



<p>For folks who got lost on the word "extension functions" - it's a way to <strong>attach</strong> a <em>function</em> or <em>property</em> to the instances of the existing classes. For example, <code>val d = 10.twice()</code>It's very much like <g class="gr_ gr_8 gr-alert gr_gramm gr_hide gr_inline_cards gr_run_anim Grammar multiReplace replaceWithoutSep" id="8" data-gr-id="8">a classic <g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="12" data-gr-id="12">Java  <code>Util</code></g></g><g class="gr_ gr_8 gr-alert gr_gramm gr_hide gr_inline_cards gr_disable_anim_appear Grammar multiReplace replaceWithoutSep" id="8" data-gr-id="8"><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12"><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12">  classes</g></g> with method <code>twice(int)</code> but done in a very clean way. Visually it looks like you're calling a member of the class, but in reality, the compiler calls your function passing receiver as an argument.</g> </p>



<span id="more-3427"></span>



<h2 class="wp-block-heading">T.<code>let</code></h2>



<p><code>let</code> allows passing given reciever into the parameter of the lambda, returns result from it. Essentially it's an <code>map</code> operator on the single value</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val imageData = db.getUserById(userId)
    ?.let { it.getProfilePicture().url }
    ?.let { fetchData(it) }</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>It's very useful when it comes to the conditional on nullable object, think of functional replacement for <code>if (user != null) user.ban()</code>:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">user?.let { it.ban() }
// or even
user?.let(::ban)</code></pre>



<p>Often we use expressions in the string interpolation, <code>.let</code> can be very handy:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">println(&quot;Hello ${db.getUser(id)?.let { it.name } ?: &quot;NONAME&quot;}&quot;)</code></pre>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T.<code>apply</code></h2>



<p><code>apply</code> calls given lambda in <strong>the context</strong> of receiver, similar to the <code>with</code> found in JavaScript and Groovy.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">User().apply {
    name = &quot;user name&quot;
    password = &quot;qwerty&quot;
}</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>I found it's a way to <s>patch</s> <strong>encapsulate configuration</strong>/finish object initialisation. It helps to perform number of operations within lambda block which are logically related to the operation such as factory initialisation or object creation. <code>apply</code> returns the receiver object(object it was called on)</p>



<p>So instead of</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client()
val credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;)
credentials.setForceHttps(true)
awsS3Client.credentials = credentials
awsS3Client.bucket = &quot;my_bucket&quot;</code></pre>



<p>We can have nicely organized initialization block:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client().apply {
    credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;).apply {
        setForceHttps(true)
    }
    bucket = &quot;my_bucket&quot;
}
</code></pre>



<p>Nice and clean, without messy noise and scope pollution!</p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T<code>.also</code> </h2>



<p>It behaves exactly as <code>.let</code> with one exception - with return result. <code>.also</code> takes receiver and passes it as an argument for the given lambda, returning the same receiver</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val bannedUser = db.getUserById(userId)
   .also { println(&quot;Got user $it&quot;) }
   .ban()</code></pre>



<h3 class="wp-block-heading">How to use?</h3>



<p>From my experience it can be used for debugging - as demonstrated above. Also, it can be used a replacement for <g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="8" data-gr-id="8">the </g><code>.apply</code><g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="8" data-gr-id="8">,</g> one can say it's more clear - based on the example for <code>.apply</code>:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val awsS3Client = AwsS3Client().also {
    it.credentials = AwsCredentialsFactory(&quot;key&quot;, &quot;secret&quot;).apply {
        it.setForceHttps(true)
    }
    it.bucket = &quot;my_bucket&quot;
}</code></pre>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">T<code>.run</code> / <code>with()</code></h2>



<p>These have very similar <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace gr-progress sel" id="5" data-gr-id="5">b</g>ehaviour - they both change the context of the function but <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="7" data-gr-id="7">unlike .</g><code>apply</code> the result of the function would be something lambda returned</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userId = User().run {
    name = &quot;username&quot;
    password = &quot;foobar&quot;
    db.save(this).id
}

val userId = with(User()) {
    name = &quot;username&quot;
    password = &quot;foobar&quot;
    db.save(this).id
}</code></pre>



<p>These two have identical behaviour - in both cases object is initialised, saved and generated id is returned - the result of the last line expression</p>



<h3 class="wp-block-heading">How to use?</h3>



<p>Well, I didn't find it used often in my code, but the example above may give you some idea</p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">Combo</h2>



<p>Some examples from the real projects</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">// filter out images with faces, print debug info, annotate 
// image with labels and filter images by stop words
val images = allImages
    // filter pics with faces if necessary
    ?.let { if (allowFaces) it else withoutFaces(word, it) }
    ?.also { log.info(&quot;findImageForWord: got ${it.size} pics after face filtering&quot;) }
    // image labelling
    ?.let { findLabels(word, it) }
    // exclude stop list words
    ?.filterNot { it.normalizedLabels.any { it in stopList } }


// Prepare video upload request for the YouTube API:
val video = Video().also {
    it.snippet = VideoSnippet().also {
        it.set(&quot;categoryId&quot;, &quot;27&quot;)
        it.set(&quot;description&quot;, description)
        it.set(&quot;title&quot;, title)
        it.set(&quot;tags&quot;, tags)
    }
    it.status = status
}
</code></pre>



<p>I hope you found this article useful for you. Check out <a href="/tags/kotlin-fun">other posts</a> about functional constructions to get the most out of kotlin</p>The post <a href="https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/">Functional kotlin part 3: scoping functions</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.10/functional-kotlin-part-3-scoping-functions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3427</post-id>	</item>
		<item>
		<title>Functional kotlin part 2: elvis operator</title>
		<link>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/</link>
					<comments>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 25 Sep 2019 09:17:06 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3411</guid>

					<description><![CDATA[<p>Continuing series of posts #kotlin-showoff about functional constructions in kotlin I want to demostrate use of elvis operator Essentially, elvis operator lvalue ?: rexpression is returning left value if it's not null or executes rexpression otherwise. The crazy thing about kotlin is most of the constructions are expressions and that gives another way to express ... <a title="Functional kotlin part 2: elvis operator" class="read-more" href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/" aria-label="More on Functional kotlin part 2: elvis operator">Read more</a></p>
The post <a href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/">Functional kotlin part 2: elvis operator</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Continuing series of posts <a href="/tags/kotlin-showoff/">#kotlin-showoff</a> about functional constructions in kotlin I want to <g class="gr_ gr_17 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="17" data-gr-id="17">demostrate</g> use of <g class="gr_ gr_25 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="25" data-gr-id="25">elvis</g> operator </p>



<p>Essentially, elvis operator <strong>lvalue ?: rexpression</strong> is returning left value if it's not <code>null</code> or executes <strong>rexpression</strong> otherwise. The crazy thing about kotlin is most of the constructions are expressions and that gives another way to express business logic.</p>



<span id="more-3411"></span>



<h3 class="wp-block-heading">Returning alternative value</h3>



<p>In the simplest case we can return alternative value if left value is <code>null</code>, for example</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userList = cache.get(userId) ?: fetch(userId)</code></pre>



<p>Literally means: get value of <code>cache.get(userId)</code> if it's not null or <code>fetch(userId)</code> </p>



<p>In Java it can be expressed as</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">List&lt;User&gt; userList = cache.get(userId);
if (userList == null) userList = fetch(userId);</code></pre>



<p>Also, it's possible to chain <g class="gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="3" data-gr-id="3">elvis</g> operators</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val userList = memoryCache.get(userId) 
     ?: diskCache.get(userId)
     ?: fetch(userId)</code></pre>



<p>Looks lovely and clean, isn't it?</p>



<h3 class="wp-block-heading">Early return with elvis</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun displayUsers() {
    val userList = cache.get(userId) 
        ?: return
    updateUiWithNewUserList(userList)
}</code></pre>



<p>In this case return if <code>userList</code> is null function will return immideatelly</p>



<h3 class="wp-block-heading">Throw exception with <g class="gr_ gr_11 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="11" data-gr-id="11">elvis</g> operator</h3>



<p>In Java code we often need to manage an exceptional situation and allow callers to handle it themselves. Take a look on this example:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">void displayUsers() {
    List&lt;User&gt; userList = cache.get(userId);
    if (userList == null) 
        throw new NoDataAvailableException()
    . . . 
}</code></pre>



<p>Employing elvis operator in kotlin it looks more concise and logic is encapsulated within one expression:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun displayUsers() {
    val userList = cache.get(userId) 
        ?: throw NoDataAvailableException()
    . . .
}</code></pre>



<p>Looks cleaner, isn't it?</p>



<h3 class="wp-block-heading">Elvis operator with in loops</h3>



<p>In the same way as we used early return it's possible to make elvis to work with <code>break</code> and <code>continue</code>, in case if you're <em>still</em> using loops</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun top10Score(users: List&lt;User&gt;): Int {
    var totalScore = 0
    for(i in 0 until Math.min(users.size, 10)) {
        val score = users[i].gameProgress?.score 
            ?: continue
        totalScore += score
    }
    return totalScore
}</code></pre>



<p>If either <code>gameProgress</code> or <code>score</code> are <code>null</code> loop will continue to the next element. <br>By the way, there is a <strong>way</strong> expressive functional way to implement the same logic:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">fun top10Score(users: List&lt;User&gt;): Int = users
    .take(10)
    .fold(0) { acc, it -&gt; acc + (it.gameProgress?.score ?: 0) }</code></pre>



<h3 class="wp-block-heading">It works not only for nullable types</h3>



<p>Kotlin has numerous <strong>extension functions</strong> allowing to express flow in the concise and functional manner. We'll dive into this topic in the following articles. </p>



<p>But here is a spoiler for you, say it's need to throw exception in validator when user didn't provide name or it was empty. From data point of view <code>null</code> isn't same as empty string, empty string isn't same as a string full of spaces. But in our business logic it's <strong>practically the same</strong> since no name is provided. Here is an example of handling this situation:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-kotlin">val name = user.name?.takeIf(String::isNotBlank)
    ?: throw UserNameIsEmptyException()</code></pre>



<p><code>takeIf</code> returns receiver object if predicate is <code>true</code>. Even <code>user.name</code> is not <code>null</code> but consist of empty string <code>takeIf</code> will return <code>null</code> because it doesn't satisfy condition. Exception will be thrown in this case and it's guaranteed by compiler that <code>name</code>  is not null</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Elvis operator in kotlin is very powerful and helps to handle conditional logic naturally within the data flow</p>The post <a href="https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/">Functional kotlin part 2: elvis operator</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.09/functional-kotlin-part-2-elvis-operator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3411</post-id>	</item>
		<item>
		<title>Functional kotlin part 1: safe calls</title>
		<link>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/</link>
					<comments>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Tue, 24 Sep 2019 18:37:36 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[kotlin-showoff]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3398</guid>

					<description><![CDATA[<p>For the seasoned Java developer it's very easy to switch to kotlin. Even more, thanks to the great effort of JetBrains team for java interop, there is no need to wait for the greenfield project to start to write kotlin code. You can start koding straight away by either implementing new functionality in kotlin or ... <a title="Functional kotlin part 1: safe calls" class="read-more" href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/" aria-label="More on Functional kotlin part 1: safe calls">Read more</a></p>
The post <a href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/">Functional kotlin part 1: safe calls</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>For the seasoned Java <g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="11" data-gr-id="11">developer</g> it's very easy to switch to kotlin. Even more, thanks to the great effort of <g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="10" data-gr-id="10">JetBrains</g> team for java interop, there is no need to wait for the greenfield project to start to write kotlin code. You can start <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">koding</g> straight away by either implementing new functionality in kotlin or converting existing classes into the new language by employing Intellj Idea automagic converter</p>



<p>This is a first of this series of posts unioned by tag <a href="https://rux.vc/tags/kotlin-showoff/">#kotlin-showoff</a></p>



<span id="more-3398"></span>



<p>As from my experience it takes literally two days for average developer to switch to kotlin from java and start to write meaningful business logic</p>



<p>As time goes by code can use more kotlin specific constructions which make code much more readable and expressive. In this blog post I'd like to show off some of the nice functional constructions which help to make code more idiomatic.</p>



<h3 class="wp-block-heading">Extracting data from the nullable types</h3>



<p>Say, we have an class <code>Address</code> within <code>UserInfo</code> which holds information about the given user's address. <code>UserInfo</code> is a part of the <code>Person</code>. <code>UserInfo</code> can be nullalbe as well as <code>Address</code> but we want to extract city name. In java it would look like:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    Person person;
    String city;
    if (person.userInfo != null &amp;&amp; person.userInfo.address != null &amp;&amp; person.userInfo.address.city != null)
        city = person.userInfo.address.city;
    else city = &quot;Unknown city&quot;;

    System.out.println(&quot;User is in &quot; + city);
</code></pre>



<p>If you think it's a safe code I have <g class="gr_ gr_19 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="19" data-gr-id="19">a bad news</g> for you. Savvy java developer can immediately spot the issue - between checks and <g class="gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="8" data-gr-id="8">assigment</g> to <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="6" data-gr-id="6">the </g><code>city</code><g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="6" data-gr-id="6"> whole</g> bunch of things can happen on another threads and eventually we can end up with <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="9" data-gr-id="9"><g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="5" data-gr-id="5">accessing</g> </g><code>null</code><g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="9" data-gr-id="9">.</g> Hello <strong>NPE!</strong></p>



<p>The correct approach would be to <strong>capture</strong> values while we're performing the check:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    UserInfo userInfo = person.userInfo;
    if (userInfo != null) {
        Address address = userInfo.address;
        if (address != null) {
            city = address.city;
        }
    }
    if (city == null) 
        city = &quot;Unknown city&quot;;

    System.out.println(&quot;User is in &quot; + city);
</code></pre>



<p>Expressivity is not Java best strength. But wait, with Java 8 we can make it a <strong>bit</strong> more readable (and still safe):</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">    city = Optional.ofNullable(person.userInfo)
            .map(userInfo -&gt; userInfo.address)
            .map(address -&gt; address.city)
            .orElse(&quot;Unknown city&quot;);

    System.out.println(&quot;User is in &quot; + city);</code></pre>



<p>Looks better, isn't it? Wait for kotlin</p>



<pre class="wp-block-code"><code>println(&quot;User is in ${person.userInfo?.address?.city ?: &quot;Unknown city&quot;}&quot;)</code></pre>



<p><strong>Sorry java ¯\_(ツ)_/¯</strong></p>



<p>So what exactly happens here? The <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="9" data-gr-id="9">chain </g><code>person.userInfo?.address?.city</code><g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="9" data-gr-id="9"> returns</g> either city if it's <g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="10" data-gr-id="10">not </g><code>null</code><g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="10" data-gr-id="10"> </g><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="12" data-gr-id="12"><g class="gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="10" data-gr-id="10">or</g> </g><code>null</code><g class="gr_ gr_12 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="12" data-gr-id="12">.</g> Then using <g class="gr_ gr_6 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="6" data-gr-id="6">elvis</g> operator we make <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="7" data-gr-id="7">whole</g> expression to return <g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="11" data-gr-id="11">extracted </g><code>city</code><g class="gr_ gr_11 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="11" data-gr-id="11"> value</g> or string "Unknown city". Even more, we can concatenate everything in one string as an expression</p>



<blockquote class="wp-block-quote"><p>You can eat your cake, and have it too</p></blockquote>



<p>Is it safe one might wonder? Yes, it is. Look into the generated code:</p>



<pre class="wp-block-prismatic-blocks"><code class="language-java">public final class KotlinImplKt {
   public static final void kotlinImpl() {
      StringBuilder var10000;
      String var4;
      label14: {
         Person person = new Person();
         var10000 = (new StringBuilder()).append(&quot;User is in &quot;);
         UserInfo var10001 = person.userInfo;
         if (var10001 != null) {
            Address var3 = var10001.address;
            if (var3 != null) {
               var4 = var3.city;
               if (var4 != null) {
                  break label14;
               }
            }
         }

         var4 = &quot;Unknown city&quot;;
      }

      String var1 = var10000.append(var4).toString();
      boolean var2 = false;
      System.out.println(var1);
   }
}
</code></pre>



<p></p>



<p>Check out other posts in <a href="https://rux.vc/tags/kotlin-showoff/">#kotlin-showoff</a></p>The post <a href="https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/">Functional kotlin part 1: safe calls</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.09/functional-kotlin-part-1-nullable-safe-calls/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3398</post-id>	</item>
		<item>
		<title>Presentation &#8211; GCP APIs with kotlin</title>
		<link>https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/</link>
					<comments>https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Mon, 08 Jul 2019 22:13:06 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[http4k]]></category>
		<category><![CDATA[presentation]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3361</guid>

					<description><![CDATA[<p>I was invited for the talk as part of kotlin/everywhere at GDG Cloud London meetup on June 8th 2019. Unlike previous talks in this one I focused on the live coding part after brief intro into the language. The demo project I prepared is a web site allowing user to upload pictures into GCP Storage, ... <a title="Presentation &#8211; GCP APIs with kotlin" class="read-more" href="https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/" aria-label="More on Presentation &#8211; GCP APIs with kotlin">Read more</a></p>
The post <a href="https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/">Presentation – GCP APIs with kotlin</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>I was invited for the talk as part of <a href="https://github.com/kotlin-everywhere?language=kotlin">kotlin/everywhere </a>at <a href="https://www.meetup.com/gdgcloud/events/261892954/">GDG Cloud London meetup</a> on June 8th 2019. Unlike previous talks in this one I focused on the live coding part after brief intro into the language. </p>



<p>The demo project I prepared is a web site allowing user to upload pictures into GCP Storage,  automatically annotate content using Vision API, synthesise voice which describes content of the image.</p>



<span id="more-3361"></span>



<p></p>



<figure class="wp-block-image"><img decoding="async" width="1024" height="454" src="https://rux.vc/wp-content/uploads/2019/07/demo-gallery-1024x454.png" alt="" class="wp-image-3362" srcset="https://rux.vc/wp-content/uploads/2019/07/demo-gallery-1024x454.png 1024w, https://rux.vc/wp-content/uploads/2019/07/demo-gallery-150x66.png 150w, https://rux.vc/wp-content/uploads/2019/07/demo-gallery-300x133.png 300w, https://rux.vc/wp-content/uploads/2019/07/demo-gallery-768x340.png 768w, https://rux.vc/wp-content/uploads/2019/07/demo-gallery.png 1146w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<figure class="wp-block-image"><img decoding="async" width="878" height="592" src="https://rux.vc/wp-content/uploads/2019/07/demo-vision.png" alt="" class="wp-image-3363" srcset="https://rux.vc/wp-content/uploads/2019/07/demo-vision.png 878w, https://rux.vc/wp-content/uploads/2019/07/demo-vision-150x101.png 150w, https://rux.vc/wp-content/uploads/2019/07/demo-vision-300x202.png 300w, https://rux.vc/wp-content/uploads/2019/07/demo-vision-768x518.png 768w" sizes="(max-width: 878px) 100vw, 878px" /></figure>



<p>Web service is using kotlin, http4k, kotlinx.html, GCP APIs and has <strong>no JavaScript</strong>, which is very rare nowadays</p>



<p>The presentation is available here </p>



<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vQtUi7CgO5WCR3jjdCQwqssMtZsTF5DTVV1vndesy02qviHbHlwRus7-P1-6vESYVkjcXqeiy86ZmbI/embed?start=false&amp;loop=false&amp;delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>



<p>GitHub repository with project: <a href="https://github.com/ruXlab/kotlin-gcp-vision-tts-demo">https://github.com/ruXlab/kotlin-gcp-vision-tts-demo</a></p>



<p>But things went really wrong, demo daemons have attacked my computer(yes, it's a silly excuse!)</p>



<h2 class="wp-block-heading">What went wrong</h2>



<p>Normally, before presentation I plug my laptop to the projector and everything works well, but not this time. Here is a postmortem of my effort to run presentation </p>



<ul><li>Projector was recognised by my laptop and picture was shown for the 5 seconds. After than it started to <strong>glitching and blinking</strong> like a disco lights.</li><li>I was given HDMI to mDP converted which didn't help at all</li><li>I started to panic because it's the only laptop I have. Luckily, person from Google Campus gave me the MacBook which works perfectly. But it had a <em>tiny</em> issue - no development software was installed there, even no java VM. Also, I'm terrible with macs</li><li>I have tried to reboot system many times trying different kernels. Because of that I <strong>lost all</strong> open windows and prepared environment.</li><li>I realised that I just need to stream my screen to Mac and it would be a solution. I <em>just</em> need to <strong>broadcast screen</strong> to local network</li><li>Not that easy, huh. Google Campus WiFi is well protected - it <strong>doesn't allow</strong> members to connect to each other. Hence, there is no way Mac can consume image from my laptop through local network</li><li>That situation absolutely derailed me since it was time to start meetup and audience was already in the room.</li><li>Bingo! I realised I can use my <strong>phone as a router</strong> to allow laptops to talk to each other over LAN. It sounded good to me!</li><li>Not that easy. There was no 4G coverage, <strong>no signal at all</strong> inside the building(it's a well known Google Campus issue). That means no cloud APIs are available :(. So I had to run to the window searching for the cell network signal</li><li>After all I was trying to google simple recipe for vlc I failed, and the time pressure was very high.</li><li>Deep breath, step back, "How do I deliver screen picture over network?". <strong>Google Hangouts</strong>, of course!  </li><li>"All sorted" - I thought.</li><li>Nearly sweating and thirsty I have started presentation. Once I finished my slides I switched to Idea and quickly prepared environment for demo(which I lost during reboots). </li><li>Idea started to <strong>play badly</strong>. Apparently it didn't replace title of the project so I was thinking that I was editing original project(with all code completed) instead of demo. I didn't realized that from the beginning so after few lines of code I had to open another "demo" folder which apparently was already opened. </li><li>Idea didn't allow me to do so and I renamed folder "demo" to "demo1", continued to write code. At some point Idea <strong>stopped running application</strong> even "run" icon has gone from the "main" method. Disaster.</li><li>2 mins of <strong>silent voodoo</strong> in the command line in front of the dozens people and I still did not have a clue. </li><li>My time was running up and organisers proposed me to continue after next talk. Unfortunately continuation never happened since given time was up</li></ul>



<p>That's a very common thing which happens during live demo from what I heard from more experienced presenters. I feel I need to learn a lesson from this:</p>



<ul><li>Always check that projector works fine with laptop</li><li>It might worth to buy external video adapter, just in case.</li><li>I should swap timeslots with next presenter allowing myself more time to prepare environment</li><li>Demo environments should have backups</li></ul>



<p>That's it, folks! (c)<br>I'd like to have the same talk another time :)</p>The post <a href="https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/">Presentation – GCP APIs with kotlin</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.07/presentation-gcp-apis-with-kotlin/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3361</post-id>	</item>
		<item>
		<title>Dynamically typed languages are selling snake oil</title>
		<link>https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/</link>
					<comments>https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sun, 09 Jun 2019 13:17:17 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[relability]]></category>
		<category><![CDATA[system design]]></category>
		<category><![CDATA[type]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3233</guid>

					<description><![CDATA[<p>I truly believe they are I hear the same statements and misunderstandings over and over again from people who like dynamically typed languages. Obliviously, that spikes a lot of endless conversations and fights between two camps. Generally, I'm avoiding conversations about static vs dynamic typing but every once in the while I drifted into that ... <a title="Dynamically typed languages are selling snake oil" class="read-more" href="https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/" aria-label="More on Dynamically typed languages are selling snake oil">Read more</a></p>
The post <a href="https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/">Dynamically typed languages are selling snake oil</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>I truly believe they are</p>
<p>I hear the same statements and misunderstandings over and over again from people who like dynamically typed languages. Obliviously, that spikes a lot of endless conversations and fights between two camps.</p>
<p>Generally, I'm avoiding conversations about static vs dynamic typing but every once in the while I drifted into that and hear the same statements, all the time. Often both sides just aren't able to listen to each other and thus conversation end up in the dead end.</p>
<p><span id="more-3233"></span></p>
<p>Let me lay out those statements</p>
<h2>It's faster to start to code!</h2>
<p>I'm sure it is. It's cool if it's possible to fit the &quot;hello world&quot; application into a tweet but how useful is that? If one really cares about it - <a href="helloworldcollection.de">helloworldcollection.de</a>.</p>
<p>Normally we create applications for businesses and they're always <em>slightly</em> complex than &quot;hello world&quot;. We as developers not only create apps, we work in the teams, we support our code - it has to be <strong>maintainable</strong>.</p>
<h2>Dynamic languages are cool for MVP</h2>
<p><img decoding="async" class="aligncenter size-full wp-image-3293" src="https://rux.vc/wp-content/uploads/2019/03/1511706160190215458.jpg" alt="" width="400" height="277" srcset="https://rux.vc/wp-content/uploads/2019/03/1511706160190215458.jpg 400w, https://rux.vc/wp-content/uploads/2019/03/1511706160190215458-150x104.jpg 150w, https://rux.vc/wp-content/uploads/2019/03/1511706160190215458-300x208.jpg 300w" sizes="(max-width: 400px) 100vw, 400px" /></p>
<p>I have to agree, at least partially. Whenever business wants to validate hypothesis we build a simple implementation using whatever we find around and glue altogether somehow. The biggest mistake I see that people take it as a base and continue to improve that. In most of the cases it has to be throw-away code. Unfortunately, it doesn't work this way. Weak foundation will fire back very soon and instead of developing product tech teams fights with legacy and building workarounds around crutches.</p>
<p>In other words it's very difficult to <strong>scale</strong> your project's codebase without aid from the compiler and IDE inherently.</p>
<h2>Types make you busy thinking!</h2>
<blockquote><p>I don't have time to think!</p></blockquote>
<p>It's easy to start working without thinking about how data is organised, business domain, and how it flows through components(especially if there is no implementation yet). It's uneasy to think about that <strong>ahead</strong> but we have to do so at some point. If all rules are known from the beginning it's way easier to organise the structure.</p>
<p>Types really help in this place. They allow to draw a bold line and add meaning to the data, specify contract.</p>
<p>Oh wait, did you just complained that your employer <strong>makes you think </strong>of what you're doing?</p>
<h2>Contracts</h2>
<blockquote><p>What if you <em>ask</em> <em>glass</em> to <em>bark</em>?</p></blockquote>
<p>What happens when you <strong>drop</strong> an apple? Or an Apple MacBook? Since the same rules apply to every object we know what to expect from our actions. The last thing you <strong>expect</strong> when you dropped banana is to become coffee and <strong>fly</strong> to the stratosphere.</p>
<p>On another hand, you can't drop the <span style="color: #339966;">green</span> colour. It simply doesn't make any sense. Why would you <strong>allow</strong> do to so? Without contracts with known types and strict checks developer can likely can make a mistake without intention and <strong>world can collapse.</strong> Types can help to prevent that without exposing the dangerous situation to the end customer who, you know, pays money. One can say that those <em>corner-case</em> situations <em>can</em> be covered by unit tests.</p>
<h2>Unit testing</h2>
<blockquote><p>Necessary evil we deal with</p></blockquote>
<p>I sincerely believe that unit-testing is evil. We should avoid it as much as we can. For most of us who aren't using something like Haskell, the reality is very different. Due nature of the <strong>complexity</strong> of the systems we design, lack of math education(probably PhD) we simply can't comprehend <strong>all variations</strong> and ways program works. On another side modern programming languages have very limited support due to the complexity of implementation or lack of demand, I suppose.</p>
<p>That all make us write unit tests. It's a good compromise between creating very complex programs and being confident that things work as expected.</p>
<p>One might have noticed that the world isn't black and while. While we still have to write unit tests it would be nice to have some aid from the compiler.</p>
<p>Say, we have a contract which takes <strong>a specific type</strong> of object and returns something nice. Why would we write a unit test which supplies array instead if it's <strong>simply can't be a case</strong>, like at all? Contract with types can significantly reduce the number of tests have to be written and brain power to be used since the compiler will check that for us</p>
<h2>We are humans</h2>
<blockquote><p>sin((5452 * 3023) / 2342.23053)<sup>42</sup></p></blockquote>
<p>It's an interesting observation, isn't it? We do creative things, talk to the businesses, understand requirements and satisfy business, get paid for that.<br />
Problem with humans that we don't really have much capacity to fit complex systems on different levels. We can easily make stupid<strong> mistakes</strong> while focusing on the high level, and <strong>that's okay</strong>.</p>
<p><strong>Developers don't write code. Developers help businesses to solve problems.</strong> Focus on the result and deliverables are the most priority, implementation - is just a detail. I hope this fact doesn't hurt you much :)</p>
<p>In my understanding, we should focus on the business problem solving not on the low-level fights with code. Why do I even need to think what happens if string passed to the function which takes a number? I'd prefer a computer to check those things for me. That's a nature of <strong>automation</strong>.</p>
<h2>So what?</h2>
<blockquote><p>¯\_(ツ)_/¯</p></blockquote>
<p>I want to believe that everyone chooses the right tool for the task. But sometimes we simply can't see options as we didn't know about them. I appreciate that many people came to the industry recently not only without a CS degree but without high education at all. I think it's beautiful that nowadays it's possible! Also, my appreciation for ones who had the courage to change the industry - <strong>you're the best</strong>.</p>
<p>I hope this article can help to <em>re</em>consider the use of tools which supports types - for better you!</p>
<h2>Interesting fact.</h2>
<p>For more than a decade, I was observing how the industry of dynamically typed languages changes their approach to handling big projects. Here is a list of popular projects gaining huge adoption for  type checks  in dynamically typed languages:</p>
<ul>
<li>PHP - <a href="https://www.php.net/manual/en/migration70.new-features.php">built-in from version 7.0</a></li>
<li>JavaScript - <a href="https://www.typescriptlang.org/">TypeScript</a>,  <a href="https://flow.org/">flowjs</a></li>
<li>python - <a href="https://www.python.org/dev/peps/pep-0484/">PEP 484</a></li>
<li>ruby - <a href="https://sorbet.org/">Sorbet</a></li>
<li>groovy - <a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/CompileStatic.html">@CompileStatic</a></li>
</ul>
<p>I'm not saying that every user of those languages is adopting type checkers but from my observation, it's getting huge traction especially last 3 years.</p>
<hr />
<p>disclaimer: if you think that technology works for you and does what you expect it to do - you're doing the right thing.</p>The post <a href="https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/">Dynamically typed languages are selling snake oil</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.06/dynamically-typed-languages-are-selling-snake-oil/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3233</post-id>	</item>
		<item>
		<title>Kotlin Presentation &#8211; GDG Reading Meetup @ Spaces, Reading 21 Feb 2019</title>
		<link>https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/</link>
					<comments>https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Fri, 22 Feb 2019 00:19:41 +0000</pubDate>
				<category><![CDATA[events]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[gdg]]></category>
		<category><![CDATA[meetup]]></category>
		<category><![CDATA[talk]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3242</guid>

					<description><![CDATA[<p>Just returned from meetup where I had a talk about kotlin language - "Why Kotlin? Why now?" The talk took place in Spaces, Reading on 21st of February 2019 and was organised by Google Developer Group Reading, namely by Chris Guest and his team. In this talk, I highlighted reasons for learning one more language, ... <a title="Kotlin Presentation &#8211; GDG Reading Meetup @ Spaces, Reading 21 Feb 2019" class="read-more" href="https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/" aria-label="More on Kotlin Presentation &#8211; GDG Reading Meetup @ Spaces, Reading 21 Feb 2019">Read more</a></p>
The post <a href="https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/">Kotlin Presentation – GDG Reading Meetup @ Spaces, Reading 21 Feb 2019</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Just returned from meetup where I had a talk about kotlin language - "Why Kotlin? Why now?"</p>
<p>The talk took place in Spaces, Reading on 21<sup>st</sup> of February 2019 and was organised by <a href="https://www.meetup.com/GDG-Reading-Thames-Valley/events/258373119/">Google Developer Group Reading</a>, namely by <a href="https://twitter.com/GuestChris">Chris Guest</a> and his team.<br />
In this talk, I highlighted reasons for learning one more language, guided through most noticeable features. In the second part, we had a live demo - kwitter REST web server.</p>
<p>I found people there were very friendly, it feels like they know each other for a long time. Really nice atmosphere and good vibes!</p>
<p><span id="more-3242"></span></p>
<p>For me, it was the first time when I was talking for two hours. I think it went not terribly bad, at least I saw some people engaged in the demo, some questions were asked. If you were there - I'd love to hear the feedback!</p>
<p>My presentation with code snippets:</p>
<p><iframe src="https://docs.google.com/presentation/d/e/2PACX-1vSlCI1gZaXbyHIduC1vpz0rsEIP7Oj6J0HFqdRqX1Sdz-nWYUUMgQqN7KzN0IgtXWRV6MvD6pADgUzJ/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></p>
<p>Demo project is available too - <a href="https://github.com/ruXlab/kwitter-demo">https://github.com/ruXlab/kwitter-demo</a></p>
<p>Thank you for attending the event, I hope you've learnt something useful.<br />
And big kudos to <a href="https://twitter.com/GuestChris">Chris</a> who helped me to prepare a presentation structure and gave very practical bits of advice.</p>
<p align="right" style="color: gray">
Cover picture for this post is taken by <a href="https://twitter.com/akostarevas/status/1098686335169249280">@akostarevas</a></p>The post <a href="https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/">Kotlin Presentation – GDG Reading Meetup @ Spaces, Reading 21 Feb 2019</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2019.02/gdg-reading-meetup-reading-21-feb-2019/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3242</post-id>	</item>
		<item>
		<title>JavaScript vs logic</title>
		<link>https://rux.vc/2018.10/javascript-vs-logic/</link>
					<comments>https://rux.vc/2018.10/javascript-vs-logic/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sat, 27 Oct 2018 11:56:32 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[productivity]]></category>
		<category><![CDATA[thoughts]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3041</guid>

					<description><![CDATA[<p>In programming world we are working with logic. Everything relies on it, it's a fundamental part of computers. If we do 3+4 we always expect to get 7. Call to createDatabase shall not destroy database. As experience grows developer grasps more and more concepts and approaches because of the past experience and logic. It's very ... <a title="JavaScript vs logic" class="read-more" href="https://rux.vc/2018.10/javascript-vs-logic/" aria-label="More on JavaScript vs logic">Read more</a></p>
The post <a href="https://rux.vc/2018.10/javascript-vs-logic/">JavaScript vs logic</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>In programming world we are working with logic. Everything relies on it, it's a fundamental part of computers.</p>
<p>If we do <code>3+4</code> we always <em>expect</em> to get <code>7</code>. Call to <code>createDatabase</code> shall not <strong>destroy database</strong>. As experience grows developer grasps more and more concepts and approaches because of the past experience and logic. It's very important part of programming ecosystem which helps to grow skill set without getting another Masters degree or attending classes/courses</p>
<p>People ended up with very common concepts and gave them names - algorithms, design patterns, data types, naming conventions.</p>
<p><span id="more-3041"></span></p>
<p>I've used dozens of different languages for different platforms such as (android, web, desktops, symbian, j2me, embedded AVR &amp; ARM, etc..) and I see quite the same patterns and approaches pretty much everywhere, almost. <strong>But JavaScript is always stands out!</strong></p>
<h3>Add mayo to the socks</h3>
<p>I won't mention about hieracy system in JS - it's a mess, nonsense and you probably know about that. I want to point out on another amusing parts of the language.</p>
<pre><code>&gt; {}+[]
0
&gt; []+{}
&#039;[object Object]&#039;
</code></pre>
<p>:thinking_face: Generally in the real life and normal languages you won't sum up <em>chairs and color</em> because they are too different. I'd except to get error, ideally compile time error because this code is nonsense. But no, JS actually executes it and returns result (different result, you woulnd't expect that, whould you?)</p>
<h3>It's not true, because of "soda"</h3>
<p>Boolean math is the foundation of the computers. Literally.<br />
As a type Boolean is one of the most important way to express conditions and flags, binary state(means it has two states)</p>
<p><em>disclaimer: it's not only JS problem, most of weak-typed languages have that nonsense</em></p>
<pre><code>&gt; true == 0
false
&gt; true == 1
true
&gt; true == 10
false
&gt; true &lt;= 0
false
&gt; true &gt;= 0
true

</code></pre>
<p>So wait, true is not 0 but 1. My common sense says me that <code>false</code> should only correspond to 0 and <code>true</code> - for any other value, because you know, it's boolean. But JS engine is cheating here as well. For <strong>two state</strong> value we have an integer range lying in the range of <code>true 𝈨 (-Min, 0) 𝉅 (0, +Max)</code>. Is it only me who founds it weird?</p>
<p>Obviously, my initial understanding of how to compare apples to sheeps might be wrong. But how can we use programming language which allows us to refer to the gut feelings?</p>
<h3>Nono no, it's 'true'</h3>
<p>There is an binary operator which makes sense only in context of boolean or group of booleans - <code>not</code>. What it does it simply inverts boolean value or bits in the number</p>
<p>But wait, in JS there are more usages!</p>
<pre><code>&gt; !&quot;&quot;
true
&gt; !&quot;rabbit&quot;
false
</code></pre>
<p>According to JS architects it's okay to perform negation on the string. If they could really try to use their imagination they could come up with real negation/inversion operation which makes sense to given datatype, for example by performing <code>!&quot;manDARIN&quot;</code> -&gt; <code>!&quot;MANdarin&quot;</code>.</p>
<p>Boolean <code>not</code> in JS inverts string and produces boolean. If string is empty - it's true, otherwise it's false. That's strange but okay, may be it's supposed to be a shortcut to check if there is something? If so why not to call <code>string.isEmpty()</code>, for example?</p>
<pre><code>&gt; !nonExistingString
    ReferenceError: nonExistingString is not defined
        at repl:1:2
        at ContextifyScript.Script.runInThisContext (vm.js:23:33)
        at REPLServer.defaultEval (repl.js:339:29)
</code></pre>
<p>Oops no, I mean, <code>!&quot;oops&quot;</code></p>
<p><em>Who said that JS is easy language?</em></p>
<h3>Strings are <s>easy</s> dangerous</h3>
<p>Typical JS application operates with massive number of strings, so I'd assume toolkit for this data type should be perfect</p>
<h4>Strings are <em>almost</em> arrays</h4>
<p>Just recent discover. You would think you can access chars of the string the same way as you do in the vast majority of the languages using indexed access, but..</p>
<pre><code>&gt; var s = &#039;abcd&#039;
undefined
&gt; s[0]
&#039;a&#039;
&gt; s[0] = &#039;X&#039;
&#039;X&#039;
&gt; s
&#039;abcd&#039;
</code></pre>
<p>Basically, it is possible to extract character at given position <strong>AND</strong> assign something to the specific position BUT it <strong>DOESN'T WORK</strong>. How do you feel about code which doesn't throw any error AND doesn't work, by design. Difficult to believe that it's in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting">language spec</a></p>
<h4>String literals aren't really strings, sort of</h4>
<p>Let me impress some professional developers - there are string literals and string object, which behave, <em>almost</em> the same way. Something tells me some developers even didn't know there is a difference between.</p>
<p>Consider example from <a href="https://stackoverflow.com/a/36614897">SO</a>:</p>
<pre><code>var x = &quot;hello&quot; ;
x.y = &quot;world&quot;;
console.log(x.y); // this will print undefined

var x = new String(&quot;hello&quot;);
x.y = &quot;world&quot;;
console.log(x.y); // this will print world
</code></pre>
<p>One can say, it's completely fine as they're different datatypes, <em>even</em> it's dynamically typed language. Generally speaking I hate inconsistent behaviour but if it significantly improve performance sometimes we have to go with this kind of tradeoff. My main issue here with error swallowing. Lovely javascript doesn't indicate that property wasn't set, <em>even</em> in strict mode.</p>
<h3>Map/Set are useless</h3>
<p>If you like to use existing data structures you also might use Set and Map, which finally were introduced in JS6. I really was waiting for that and had to use <code>lodash</code> before</p>
<p><strong>But don't celebrate it yet.</strong></p>
<p>Let me tell you story about <code>Iterator</code>s. There is a design pattern which allows consumer to walk through collection(basically list of items organised in some way) and get every next element, only one element an iteration. In functional languages and pretty much everywhere nowadays it's common to use <code>Iterator</code> interface to perform functional-like operations on collections, such as <code>map</code>, <code>filter</code>, <code>reduce</code>.</p>
<p>I'm happy to confirm that these operators were around for a while for Arrays. But, think about it, in 2017 after <em>ten years</em> of working on new version architects didn't bother to add these operations on all-new <code>Map</code> and <code>Set</code>. Iterators there are half-backed and don't behave as you might expect.</p>
<p>You simple can't transform or filter key-value pairs on it</p>
<pre><code>var m = new Map() 
m.set(&quot;a&quot;, 11)
m.set(&quot;b&quot;, 22)

&gt; m.filter
undefined
&gt; m.map
undefined
</code></pre>
<p>You might think I've forgotten about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries"><code>entries()</code></a>. Well, look at this nonsense:</p>
<pre><code>&gt; m.entries()
MapIterator { [ &#039;a&#039;, 11 ], [ &#039;b&#039;, 22 ] }
&gt; m.entries().map
undefined
&gt; m.entries().filter
undefined
&gt; m.entries().reduce
undefined
</code></pre>
<p>So what is a javascript way?</p>
<p>If you understand roughly what is happening here you might be terrified:</p>
<pre><code>&gt; new Map(Array.from( m ).filter(([key, value]) =&gt; value &gt; 20 ))
Map { &#039;b&#039; =&gt; 22 }
</code></pre>
<p>Same thing is happening with <code>Set</code>:</p>
<pre><code>var s = new Set([1,2,2,3])
&gt; s.map
undefined
&gt; s.filter
undefined
</code></pre>
<p>And the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Relation_with_Array_objects">recommended</a> way to perform operation on collection is using <code>Array</code>:</p>
<pre><code>&gt; new Set(Array.from(s).filter(v =&gt; v &gt;= 3))
Set { 3 }
</code></pre>
<p>When I see those unnecessary allocations due transformations to array and back to map I'm shivering. It immediately became <strong>known anti-pattern</strong> and no one uses this approach. Apparently because of those issues developers consider neither <code>Set</code> nor <code>Map</code> to use. :sad_face:</p>
<p>The good news both <code>Set</code> and <code>Map</code> do have <code>forEach</code> function which returns iterator with pairs of key-value wrapped with array, if you still care after all:</p>
<pre><code>&gt; m.forEach((k, v) =&gt; console.log(&lt;code&gt;${k}=${v}</code>))
11=a
22=b
</code></pre>
<p>As I love to say those data types are implemented in JavaScript style.</p>
<h3>But wait, how do people write so many apps and they seem to be working?</h3>
<p>The answer is simple:</p>
<p>1) <strong>Luck</strong>. Yes, sometimes we're lucky enough to make app which doesn't fail for years because corner case never comes. It doesn't mean it won't happen. The more system in use the more likely hidden bug will be discovered in the next moment, as per Bayes' theorem. Also, having one failure of thousand requests can be considered &quot;okay&quot;.<br />
2) <strong>Unit tests</strong>. The biggest unit tests and TDD adopters are found in javascript community. I believe unit tests are important, unfortunately. Many of them simply cover what compiler can't infer itself - practically we complement compiler's stupidity/simplicity paying high cost of time of our human lives. On another extreme in Haskell world you won't find much unit tests since compiler guarantees really <strong>a lot</strong>.<br />
3) <strong>Good practices</strong>. They exists in any ecosystem and they guide developer to write good, readable code, solve well-defined problems in common way. In javascript world good practice is more of &quot;must use practice&quot; otherwise system explodes. Even you can you should never assign property to string object, because it could be literal. Instead <s>pollute namespace via <code>prototype</code></s> use helper functions, because, you know, js is not <s>fully</s> classic OOP language &#xAF;&#95;(&#x30C4;)_/&#xAF;</p>
<h2>Instead of conclusion</h2>
<p>I always say if technology works for someone I don't mind what is being used until business is happy. But looking on javascript ecosystem I feel it drains a lot of human energy, which could be used in more conscious way in another worlds. Developers often fight windmills instead of bringing more value to business.</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2018/10/js-is-a-lovely-language.jpg" alt="" width="504" height="415" class="aligncenter size-full wp-image-3176" srcset="https://rux.vc/wp-content/uploads/2018/10/js-is-a-lovely-language.jpg 504w, https://rux.vc/wp-content/uploads/2018/10/js-is-a-lovely-language-150x124.jpg 150w, https://rux.vc/wp-content/uploads/2018/10/js-is-a-lovely-language-300x247.jpg 300w" sizes="(max-width: 504px) 100vw, 504px" /></p>The post <a href="https://rux.vc/2018.10/javascript-vs-logic/">JavaScript vs logic</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2018.10/javascript-vs-logic/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3041</post-id>	</item>
		<item>
		<title>Nexmo Voice API demo: voicemail app</title>
		<link>https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/</link>
					<comments>https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Mon, 02 Jul 2018 19:05:30 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[nexmo]]></category>
		<category><![CDATA[spring boot]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[voice]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3132</guid>

					<description><![CDATA[<p>This article features voicemail service built using Nexmo Voice APIs and Spring Boot As a business owner it's not always easy to handle huge volume of calls 24/7. On another hand each customer is important and it deserve to be served well. To kick off development you can checkout demo repository What to expect in ... <a title="Nexmo Voice API demo: voicemail app" class="read-more" href="https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/" aria-label="More on Nexmo Voice API demo: voicemail app">Read more</a></p>
The post <a href="https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/">Nexmo Voice API demo: voicemail app</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>This article features voicemail service built using Nexmo Voice APIs and Spring Boot</p>
<p>As a business owner it's not always easy to handle huge volume of calls 24/7. On another hand each customer is important and it deserve to be served well.</p>
<p>To kick off development you can <a href="https://github.com/ruXlab/nexmo-voicemail-service-tutorial">checkout demo repository</a></p>
<h2>What to expect in this tutorial</h2>
<p>In this tutorial we build simple voice mail forwarder where  callers asked to leave a voice message which will be sent to the email using <a href="https://developer.nexmo.com/api/voice">Nexmo Voice API</a> as an attachment.<br />
Example of result:</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2018/07/received-email.png" alt="" width="669" height="346" class="size-full wp-image-3134" srcset="https://rux.vc/wp-content/uploads/2018/07/received-email.png 669w, https://rux.vc/wp-content/uploads/2018/07/received-email-150x78.png 150w, https://rux.vc/wp-content/uploads/2018/07/received-email-300x155.png 300w" sizes="(max-width: 669px) 100vw, 669px" /></p>
<p><span id="more-3132"></span></p>
<p>That can be done just in a few steps:</p>
<ul>
<li><a href="#configure-environment">Configure environment</a></li>
<li><a href="#create-an-voice-application">Create a voice application and assign it to the phone number using Nexmo CLI</a></li>
<li><a href="#spring-boot-application-skeleton">Build a simple Spring Boot application</a> </li>
<li><a href="#handle-call-events">Handle call events</a> </li>
<li><a href="#handle-recording-webhook-event-and-email-record">Handle recording webhook event and email record</a></li>
</ul>
<h2>Prerequisites</h2>
<ul>
<li><a href="https://dashboard.nexmo.com/sign-up">A Nexmo account</a> </li>
<li><a href="https://github.com/ruXlab/nexmo-voicemail">Demo Source code</a></li>
<li><a href="https://github.com/nexmo/nexmo-cli">The Nexmo CLI</a> installed and set up</li>
</ul>
<h3>Configure environment</h3>
<p>Service has to be available from the internet. The easiest way to do so is to use tunnel such as ngrok or servio.net:</p>
<pre><code class="bash">ssh -R 80:localhost:8080 serveo.net
Forwarding HTTP traffic from https://iste.serveo.net
</code></pre>
<p>It will forward all incoming traffic from the randomly assigned host to your machine to port 8080.</p>
<h3>Create an voice application</h3>
<p>Next step is to create application associated with this service</p>
<pre><code class="bash">➜  nexmo app:create &quot;voicemail app&quot; https://iste.serveo.net/answer https://iste.serveo.net/event \
             --keyfile nexmo_app.key
Application created: 0d76428d-a914-4d65-8c38-814d76986391
Private Key saved to: nexmo_app.key
</code></pre>
<p>Afterwards we can purchase phone number and link it to the app</p>
<pre><code class="bash">➜  nexmo number:buy --country_code GB --confirm
Number purchased: 441414658675

➜  nexmo link:app 441414658675 0d76428d-a914-4d65-8c38-814d76986391
Number updated

</code></pre>
<h3>Spring Boot Application skeleton</h3>
<p>In this gradle file apart of spingboot itself we also need two more dependencies: spring-mail for SMTP client and <a href="https://github.com/Nexmo/nexmo-java">nexmo-java</a> library which simplifies access to the Nexmo APIs</p>
<pre><code class="gradle">dependencies {
    . . . 
    compile &#039;com.nexmo:client:3.3.0&#039;
    compile &quot;org.springframework.boot:spring-boot-starter-web:2.0.0.RELEASE&quot;
    compile &#039;org.springframework.boot:spring-boot-starter-mail:2.0.0.RELEASE&#039;
}
</code></pre>
<p>Main application class is very basic but we need to add a bean factory for <code>NexmoClient</code> for further handy access:</p>
<pre><code class="java">@SpringBootApplication
public class VoiceMailSrv {
    public static void main(String[] args) {
        SpringApplication.run(VoiceMailSrv.class, args);
    }

    @Bean
    public NexmoClient nexmoClient(
            @Value(&quot;${nexmoApplicationId}&quot;) String applicationId,
            @Value(&quot;classpath:nexmo_app.key&quot;) Resource cert
    ) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
        return new NexmoClient(new JWTAuthMethod(applicationId, Files.readAllBytes(cert.getFile().toPath())));
    }
}
</code></pre>
<p>Here you might notice that we need to provide <code>applicationId</code> and key, generated using nexmo-cli. To do so put <code>nexmo_app.key</code> to the <code>resources</code> folder and create <code>application.properties</code> file where spring boot will pick up application configuration.</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2018/07/resources-layout.png" alt="" width="353" height="144" class="size-full wp-image-3135" style="clear:both" srcset="https://rux.vc/wp-content/uploads/2018/07/resources-layout.png 353w, https://rux.vc/wp-content/uploads/2018/07/resources-layout-150x61.png 150w, https://rux.vc/wp-content/uploads/2018/07/resources-layout-300x122.png 300w" sizes="(max-width: 353px) 100vw, 353px" /></p>
<p>In resouces file you need to provide applicationId and additional configuration for SMTP server:</p>
<pre><code>nexmoApplicationId = 0d76428d-a914-4d65-8c38-814d76986391
destinationEmail = bob@email.com
senderEmail = me@localhost


# Email server configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=&lt;login user to smtp server&gt;
spring.mail.password=&lt;login password to smtp server&gt;
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
</code></pre>
<p>As it normal spring configuration it can be provided/overloaded via environment variables, command line arguments and <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html">many other options</a></p>
<p>More information about SMTP configuration can be found in <a href="http://www.baeldung.com/spring-email">blog post on Baeldug</a></p>
<h3>Handle call events</h3>
<p>When Nexmo receives an inbound call to purchased number it makes a request to the webhook endpoint you set when you created a Voice application. There are two of them - <strong>AnswerURL</strong> used to provide <a href="https://developer.nexmo.com/api/voice/ncco">NCCO Object</a> and <strong>EventURL</strong> for events happening throughout call lifecycle</p>
<p>To instruct Nexmo about actions we need to return NCCO Object when we recieve call on <strong>AnswerURL</strong>, our controller handler should look like:</p>
<p>In our case we design NCCO of following actions:</p>
<ul>
<li><a href="https://developer.nexmo.com/api/voice/ncco#talk"><strong>Talk</strong></a> - Using Nexmo TTS say <em>"Thanks for calling us. Please leave your message and press hash key"</em> </li>
<li><a href="https://developer.nexmo.com/api/voice/ncco#record"><strong>Record</strong></a> - Record a message and put it on Nexmo Media service. In this action we need to provide callback url to be called when voice message is recorded</li>
<li><a href="https://developer.nexmo.com/api/voice/ncco#talk"><strong>Talk</strong></a> - Speak <em>"Thank you. Your message has been recorded. Bye"</em></li>
</ul>
<pre><code class="java">@GetMapping(&quot;/answer&quot;)
public Object onAnswer(
        @RequestParam(&quot;conversation_uuid&quot;) String conversation,
        @RequestParam(&quot;from&quot;) String caller,
        HttpServletRequest request
) {
    log.info(&quot;onAnswer: got call from {} (conversation {})&quot;, caller, conversation);
    return new NccoResponseBuilder()
        .appendNcco(new TalkNcco(&quot;Thanks for calling us. Please leave your message and press hash key&quot;))
        .appendNcco(new RecordNcco() {{
            String schema = Optional.ofNullable(request.getHeader(&quot;x-forwarded-proto&quot;)).orElse(request.getScheme());
            String host = Optional.ofNullable(request.getHeader(&quot;host&quot;)).orElse(request.getLocalAddr());
            setBeepStart(true);
            setEndOnKey(&#039;#&#039;);
            setEventUrl(String.format(&quot;%s://%s/record&quot;, schema, host));
            setEventMethod(&quot;GET&quot;);
        }})
        .appendNcco(new TalkNcco(&quot;Thank you. Your message has been recorded. Bye&quot;))
        .getValue().toJson();
}

</code></pre>
<p>No need to craft NCCO manually - it can be done by using fluent API.</p>
<p>Also, we need a SMTP server. There are plenty of options such as <a href="https://sendgrid.com">sendgrid</a> or <a href="https://www.mailgun.com/">mailgun</a>.</p>
<h3>Handle recording webhook event and email record</h3>
<p>When recording is finished the specified callback for <strong>record</strong> action will be called with url to mp3 file. Our handler should download it and compose an email attaching it.</p>
<pre><code class="java">&lt;br /&gt;@GetMapping(&quot;/record&quot;)
public void onRecordingFinished(
        @RequestParam(&quot;recording_url&quot;) String recordingUrl
) throws MessagingException, IOException, NexmoClientException {
    log.info(&quot;onRecordingFinished: new recording detected: {}&quot;, recordingUrl);

    Recording recording = nexmoClient.getVoiceClient().downloadRecording(recordingUrl);
    byte[] binaryRecording = IOUtils.toByteArray(recording.getContent());
    log.info(&quot;onRecordingFinished: recording has been downloaded, {}bytes&quot;, binaryRecording.length);

    MimeMessage message = emailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom(senderEmail, &quot;Voicemail demo service&quot;);
    helper.setSubject(&quot;Your voicemail recorded at &quot; + new Date());
    helper.addTo(destinationEmail);
    helper.setText(&quot;Please find voice recording in attachment&quot;);

    helper.addAttachment(&quot;Recording.mp3&quot;, () -&gt; new ByteArrayInputStream(binaryRecording), &quot;audio/mpeg3&quot;);

    emailSender.send(message);
    log.info(&quot;onRecordingFinished: email has been sent to {}&quot;, destinationEmail);
}

</code></pre>
<p>Media storage is protected by JWT authorization but <code>NexmoClient</code> simplifies access to it and returns <code>InputStream</code> we can work with</p>
<p>The full code of controller can be found <a href="https://github.com/ruXlab/nexmo-voicemail-service-tutorial/blob/master/src/main/java/com/nexmo/demo/voicemail/VoiceMailController.java">on github</a></p>
<h1>Conclusion</h1>
<p>In this tutorial we quickly built simple voicemail recorder using seamlessly integrated nexmo-client to the spring boot application</p>
<p>Nexmo has various actions in NCCO and combining them together it is possible to create endless applications for different use cases.</p>The post <a href="https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/">Nexmo Voice API demo: voicemail app</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2018.07/nexmo-voice-api-demo-voicemail-app/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3132</post-id>	</item>
		<item>
		<title>Presentation &#8220;kotlin 101 by example&#8221; @ Gran Canaria</title>
		<link>https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/</link>
					<comments>https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Mon, 29 Jan 2018 10:05:32 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[Reality]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[spring boot]]></category>
		<category><![CDATA[workshop]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3081</guid>

					<description><![CDATA[<p>Recently I had a talk at event organised by Google Developer Group community at lovely island Gran Canaria, Spain It was first experience of this kind. Although I already had number of public talks related to kotlin this one was in new format for me - live coding. After short introduction about myself and kotlin ... <a title="Presentation &#8220;kotlin 101 by example&#8221; @ Gran Canaria" class="read-more" href="https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/" aria-label="More on Presentation &#8220;kotlin 101 by example&#8221; @ Gran Canaria">Read more</a></p>
The post <a href="https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/">Presentation “kotlin 101 by example” @ Gran Canaria</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Recently I had a talk at event organised by Google Developer Group community at lovely island Gran Canaria, Spain</p>
<p><span id="more-3081"></span></p>
<p>It was first experience of this kind. Although I already had number of public talks related to kotlin this one was in new format for me - live coding. After short introduction about myself and kotlin language I started to show off main features of the language while developing REST notebook service using Spring Boot. I found it's unfair that kotlin is getting associated more with Android while it's actually very good on backend too. More importantly - not only as better replacement for enterprise applications but also for prototypes - it easily can compete with python and nodejs for PoC/MVP projects</p>
<p>Here are slides</p>
<p><iframe frameborder="0" src="https://docs.google.com/presentation/d/e/2PACX-1vRf1QYoaU9_jPUHUS4tSucM14_fZp_rlgMsZKjeBu7iHU7wKONFuZO0rNkmm7FF2MvIKQgIdCjrklR9/embed?start=false&amp;loop=false&amp;delayms=3000" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></p>
<p>The source code is available at github<br /><a href="ruXlab/kotlin-springboot-demo">https://github.com/ruXlab/kotlin-springboot-demo</a> as well as <a href="https://github.com/ruXlab/kotlin-springboot-demo/blob/master/demo-script.md">script for scenario</a></p>The post <a href="https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/">Presentation “kotlin 101 by example” @ Gran Canaria</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2018.01/presentation-kotlin-101-by-example-gran-canaria/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3081</post-id>	<georss:point>28.1235459 -15.4362574</georss:point>
		<geo:lat>28.1235459</geo:lat>
		<geo:long>-15.4362574</geo:long>
	</item>
		<item>
		<title>JavaScript must go (ASAP)</title>
		<link>https://rux.vc/2017.12/javascript-must-die-asap/</link>
					<comments>https://rux.vc/2017.12/javascript-must-die-asap/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Tue, 26 Dec 2017 18:31:54 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Quick notes]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3038</guid>

					<description><![CDATA[<p>JavaScript it's a cancer of modern software development industry 💥 DISCLAMER 1. This article is about JavaScript - the language happen to become a runtime for many types of applications. 2. TypeScript, CoffeeScript, *Script have nothing to do with JS, this post is not about it. 3. As many of you I'm also a JavaScript ... <a title="JavaScript must go (ASAP)" class="read-more" href="https://rux.vc/2017.12/javascript-must-die-asap/" aria-label="More on JavaScript must go (ASAP)">Read more</a></p>
The post <a href="https://rux.vc/2017.12/javascript-must-die-asap/">JavaScript must go (ASAP)</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<h3>JavaScript it's a cancer of modern software development industry</h3>
<blockquote><p>
<b> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a5.png" alt="💥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> DISCLAMER</b><br />
1. This article is about JavaScript - the language happen to become a runtime for many types of applications.<br />
2. TypeScript, CoffeeScript,  <sup>*</sup>Script have nothing to do with JS, this post is not about it.<br />
3. As many of you I'm also a JavaScript developer. I'm not addressing to anyone personally, the post below is just my opinion about  <u>technology</u><br />
4. If you're happy with any technology and it helps to archive the business goals - I can be only happy for that!
</p></blockquote>
<p>Big claim, isn't it? Well, I'm sure I have a right to say that. I've been <s>using</s> suffering from JavaScript in last 10+ years. Really, I can't remember anything good about this shit language since I started to make money on programming being freelancer. I'm not mean, I just had enough. And please, don't take this article personally, you're not a programming language you use.</p>
<h3>I'm a normal developer.</h3>
<p>It means I'm not genius and I can't and wouldn't keep whole program code and it's complicated flow and branching in my head. I'd rather delegate this boring work to computer and focus on business logic as much as I can. I'm certain, there are about 2.5 really good developers who <em>can</em> write good code in javascript. But probably they <em>don't</em> as they are busy talking on conferences  ¯&#95;(ツ)_/¯</p>
<h3>You cannot avoid JS</h3>
<p><span id="more-3038"></span></p>
<p>Yes, you can try but you won't be able to. As a cancer it's being integrated in everything - web, backend, databases, mobile and embedded systems.</p>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2017/12/javascript-javascript-everywhere.jpg" alt="" width="600" height="327" class="aligncenter size-full wp-image-3043" srcset="https://rux.vc/wp-content/uploads/2017/12/javascript-javascript-everywhere.jpg 600w, https://rux.vc/wp-content/uploads/2017/12/javascript-javascript-everywhere-150x82.jpg 150w, https://rux.vc/wp-content/uploads/2017/12/javascript-javascript-everywhere-300x164.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /></p>
<p>On frontend we don't really have any option - js ended up as the <strong>only</strong> tool for programming in your browser(I don't count dart, it's dead as virtual machine). It's far from perfection and that's why ecosystem created <strong>hundreds</strong> of different languages on top of it - coffeescript, typescript, etc.. They are actually <em> transpiling </em> to javascript. Even new versions of JS - ECMA6 still needs to be transpiled</p>
<p>Again, due historical reasons browsers don't have other options, suck it up, bite your tongue and write frontend. I know it's a hard work, <strong>thanks</strong> to people who doing that.</p>
<h3>JS is cool on backend too</h3>
<p><code>:facepalm:</code><br />
I hear that all the time, especially from newbie developers. They're claiming that JS is so <em>simple</em> to use so even backend can benifit.<br />
There are dozens of tools have been created for backend - JVM/Java, RubyOnRails, Python and, I'm sorry, PHP.</p>
<p>So why do <em>they</em> think we deserve one more creature in our crowded backend zoo?</p>
<p>I'd like to go through most popular answers I've heard</p>
<h2>JS is fast!</h2>
<p>Sorry, comparing to what? How do you measure? I'm not surprised anymore when <strong>mature</strong> JS developers have never heard of costs of context switching, for example. Or maybe one heard about new <a href="https://keithwhor.github.io/multithread.js/">mutlithreading in javascript</a>? Oh c'mon you serious?</p>
<h2>JS is modern language</h2>
<p>Oh well. I want to share pain with you.</p>
<p>I'm sure you have heard about JS6, along with cool systax stuff they finally brought in classic datatypes - Map &amp; Set. I hope dear reader know these are very basic data structures known to any developers(even to JS ones, I hope). I was really happy that finally I could use innovations dated back to 1970</p>
<p>But here is a catch. Being <em>so-so</em> developer I expect collections to be <strong>iteratable</strong> same as Arrays in javascript, not a bit deal, isn't?</p>
<p>You easily can do <code>[1, 2, 3, 4].map(i =&gt; i*10)</code> because it's so normal nowadays, and, of course, JS clamed to be <em>functional</em>. But, apparently JS <em>&quot;architectors&quot;</em> don't think so. Althogh <code>Set</code> has forEach method but doesn't have <code>map</code>, <code>filter</code>, <code>reduce</code>, etc...</p>
<p>I mean, WHY?! What held developers from doing that?</p>
<p>Same with <code>Map</code> - it's simply not possible to map via <code>key</code> or <code>entries</code> even <code>forEach</code> works fine. But JS community doesn't care, it's okay to write another leftpad or money-patch global objects(or classes? Or functions?). It's even interesting! Writing more code it's always fun, <em>isn't it</em>? You can find more amusing things in <a href="https://rux.vc/2018.10/javascript-vs-logic/">&quot;javascript vs logic&quot; post</a>.</p>
<h2>Type system</h2>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2017/12/r_421556_deqGS.jpg" alt="" width="504" height="415" class="aligncenter size-full wp-image-3044" srcset="https://rux.vc/wp-content/uploads/2017/12/r_421556_deqGS.jpg 504w, https://rux.vc/wp-content/uploads/2017/12/r_421556_deqGS-150x124.jpg 150w, https://rux.vc/wp-content/uploads/2017/12/r_421556_deqGS-300x247.jpg 300w" sizes="(max-width: 504px) 100vw, 504px" /></p>
<p>I was told that types slow down development. And I'm absolutely agree, if you write <strong>Hello World</strong> every day JS is hell faster to use. But sorry, I'm writing production code for medium and big sized applications, which are business critical.</p>
<p>They funny thing is while application is growing it <strong>increases</strong> amount of errors and tests for JS, while for staticly-typed languages(hello JVM) code maintance complexity stays about the same. It takes time and experience for JS guys to understand that, and when they finally open eyes shit started to happen. They are pulling <strong>TypeScript</strong> and <strong>flowjs</strong> to make code <strong>SAFER</strong>, basically trying to make remove <em>script</em> part from <em>JavaScript</em>. It always amuses me</p>
<h2>Tests</h2>
<p>One claims that JS is safe if you write tests. It's true, but why whould you write tests if compiller can prevent developer from obvilius mistakes? I mean, why? Why do you need to check input arguments for type(say, MongoId as object or string) if you expect only one type?</p>
<p>I'm sure it's easier to write <code>id: MongoId</code> in the contract rather that cover that scenario in the dozens of tests(and still it will leak some usecases)</p>
<p>I love reckless approach of some JS developers - we have tests covered that - they say. Often I don't have tests I don't need - compiller won't allow me to run something which doesn't work</p>
<p>Again, I see zero reasons why you would run broken code, <strong>you should not be able to</strong>!!</p>
<h2>JS is envolving all the time</h2>
<p>Actully it's other way around. Because of the low learning curve we're having a lot of shit code outthere(same as PHP). Honestly it looks like there is a rally of producing another shit-framework.</p>
<p>While JS devs are bragging about production deployment of all-shinny-new library released yesterday world is shocking observing that. Why so? It might sound a bit conservative but production code supposed to <em>work</em>.</p>
<h3>It's very easy to write code in JS</h3>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2017/12/DKUR9Tk.png" alt="" width="365" height="277" class="aligncenter size-full wp-image-3052" srcset="https://rux.vc/wp-content/uploads/2017/12/DKUR9Tk.png 365w, https://rux.vc/wp-content/uploads/2017/12/DKUR9Tk-150x114.png 150w, https://rux.vc/wp-content/uploads/2017/12/DKUR9Tk-300x228.png 300w" sizes="(max-width: 365px) 100vw, 365px" /></p>
<p>Yes, it's always easy to write code, but don't you write Programms and Applications? It's not that simple, and, if tool doesn't put constrains on you it's very difficult to keep consistency.</p>
<p>Think about writing code on the sheet of paper? It's very <em>simple</em> but never <em>easy</em></p>
<h3>So what?</h3>
<p>If you're frontend developer - accept it, suffer and do your job. It's hard but very important.<br />
If you're JS backend developer - stop bragging about that. It's not fine. Open your eyes as look around, world of programming is beatuful and got different tools, don't reinvent the wheel. I know you can do better.</p>
<h3>Dude, do you use JS?</h3>
<p>Of couse I do.</p>
<p>I'm just minimizing usage to keep mine nerve system for more pleasant experience.<br />
Yes, I do write frontend (and do it well) when I have to, and yes, I do write prototypes on nodejs(but it never ever goes outside of prototype stage)</p>
<h3>Why so angry?</h3>
<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2017/12/javascript-fuck-you.jpg" alt="" width="400" height="400" class="aligncenter size-large wp-image-3046" srcset="https://rux.vc/wp-content/uploads/2017/12/javascript-fuck-you.jpg 400w, https://rux.vc/wp-content/uploads/2017/12/javascript-fuck-you-150x150.jpg 150w, https://rux.vc/wp-content/uploads/2017/12/javascript-fuck-you-300x300.jpg 300w, https://rux.vc/wp-content/uploads/2017/12/javascript-fuck-you-144x144.jpg 144w" sizes="(max-width: 400px) 100vw, 400px" /></p>
<p>Coz I'm sick of observing how JS is holding back whole software development ecosystem. As part of it I have my word.</p>
<p>The goal of this article is to doubt your <em>(most likely)</em> blind love to JavaScript and look around in the Bigger world</p>The post <a href="https://rux.vc/2017.12/javascript-must-die-asap/">JavaScript must go (ASAP)</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.12/javascript-must-die-asap/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3038</post-id>	</item>
		<item>
		<title>Presentation &#8220;Data Mining 101&#8221; @ Santander</title>
		<link>https://rux.vc/2017.11/presentation-data-mining-101-santander/</link>
					<comments>https://rux.vc/2017.11/presentation-data-mining-101-santander/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Tue, 07 Nov 2017 13:39:44 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[data mining]]></category>
		<category><![CDATA[data sets]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jsoup]]></category>
		<category><![CDATA[presentation]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=3015</guid>

					<description><![CDATA[<p>I had a talk "Data Mining Toolbox" in University of Cantabria, Santander, Spain organized by meetup group "Data Science Santander" on November 9th, 2017 It was my first public presentation on this topic where I accumulated some my experience in html data extraction and processing. Code snippets used in presentation For convenient access I put ... <a title="Presentation &#8220;Data Mining 101&#8221; @ Santander" class="read-more" href="https://rux.vc/2017.11/presentation-data-mining-101-santander/" aria-label="More on Presentation &#8220;Data Mining 101&#8221; @ Santander">Read more</a></p>
The post <a href="https://rux.vc/2017.11/presentation-data-mining-101-santander/">Presentation “Data Mining 101” @ Santander</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" src="https://rux.vc/wp-content/uploads/2017/11/highres_466028440-1024x768.jpeg" alt="" title="Photo credit to Claudiu" width="1024" height="768" class="aligncenter size-large wp-image-3025" srcset="https://rux.vc/wp-content/uploads/2017/11/highres_466028440-1024x768.jpeg 1024w, https://rux.vc/wp-content/uploads/2017/11/highres_466028440-150x113.jpeg 150w, https://rux.vc/wp-content/uploads/2017/11/highres_466028440-300x225.jpeg 300w, https://rux.vc/wp-content/uploads/2017/11/highres_466028440-768x576.jpeg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>I had a talk "Data Mining Toolbox" in University of Cantabria, Santander, Spain organized by meetup group <a href="https://www.meetup.com/Data-Science-Santander/events/244861375/" rel="noopener" target="_blank">"Data Science Santander"</a> on November 9th, 2017</p>
<p>It was my first public presentation on this topic where I accumulated some my experience in html data extraction and processing.</p>
<p><span id="more-3015"></span></p>
<p><iframe src="https://docs.google.com/presentation/d/e/2PACX-1vRz-t7MijVvt-fXJYZx-T_RL7JQX5j1OrhuSJrVWwf88hZ1Y4eigfzalMmH60whEI1Je7LCbOZeRYSz/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></p>
<h2>Code snippets used in presentation</h2>
<p>For convenient access I put all code snippets below instead of creating new repo on github</p>
<h3>Basic example with reddit</h3>
<pre><code>$(&#039;.thing.link&#039;).map((k, i) =&gt; {
   var i = $(i);
   return {
       title: i.find(&quot;.title a.title&quot;).text(),
       url: i.find(&quot;.title a.title&quot;).attr(&quot;href&quot;),
       score: i.find(&quot;.score.unvoted&quot;).text(),
       subreddit: i.find(&quot;.subreddit&quot;).text()
   }
}).toArray()

</code></pre>
<p>And</p>
<pre><code>window.open().document.write(JSON.stringify(a))
</code></pre>
<p>To create new browser window and put there json representation of the javascript array</p>
<h3>Pagination in reddit</h3>
<p>As it was shown it is possible to parse not only currently loaded page in the browser but get number of the pages</p>
<pre><code class="javascript">function _page(n, afterId) {
   $.get(&quot;https://www.reddit.com/?count=10&amp;after=&quot; + afterId, data =&gt; {
       var result = $(data).find(&#039;.thing.link&#039;).map((k, i) =&gt; {
           var i = $(i);
           return {
               id: i.attr(&#039;data-fullname&#039;),
               title: i.find(&quot;p.title a.title&quot;).text(),
               url: i.find(&quot;p.title a.title&quot;).attr(&quot;href&quot;),
               score: i.find(&quot;.score.unvoted&quot;).text(),
               subreddit: i.find(&quot;.subreddit&quot;).text()
           }
       }).toArray()
       console.log(&quot;page&quot;, n, &quot;=&gt;&quot;, result)
       a.push(result);
       if (n &lt;= 0) return;
       _page(n - 1, result[result.length-1].id)
   })
}
</code></pre>
<h3>Code snippet from real project</h3>
<p>Code snippet bellow potentially can get extract from the StackOverflow job page including tags and optional salary. Published for educational purposes only</p>
<pre><code class="groovy">    fun fetchRecentPage(): List&lt;StackOverflowJob&gt; {
        val jobs = jsoupGetDocument(url).select(&quot;.jobs .listResults &gt; div[data-jobid]&quot;)
        return jobs.map {
            val job = StackOverflowJob(
                wipeoutHtml(it.attr(&quot;data-jobid&quot;).trim()),
                normalizeUrl(wipeoutHtml(it.select(&quot;.-title a.job-link&quot;).attr(&quot;href&quot;).trim())),
                it.select(&quot;.-title h2&quot;).first()?.text()!!,
                it.select(&quot;p.description&quot;).text()
            )
            job.location = it.select(&quot;li.location&quot;)?.text()?.trim()
            job.tags = it.select(&quot;.tags a&quot;).orEmpty().mapNotNull {
                it.text()?.trim()?.let { wipeoutHtml(it) }
            }
            job.company = it.select(&quot;li.employer&quot;).first()?.text()?.trim()
            job.salary = it.select(&quot;.salary&quot;).first()?.text()?.trim()
            job
        }
    }
</code></pre>
<p>In this example kotlin and jsoup are used</p>
<p><!--
## A few words about meetup itself

Although event was organised almost spontaneously it gathered a number of people. It took place in one of the University of Cantabria buildings surrounded by peaceful park. 
--></p>The post <a href="https://rux.vc/2017.11/presentation-data-mining-101-santander/">Presentation “Data Mining 101” @ Santander</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.11/presentation-data-mining-101-santander/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3015</post-id>	</item>
		<item>
		<title>Safe and sound code with kotlin</title>
		<link>https://rux.vc/2017.06/safe-and-sound-code-with-kotlin-meetup-in-spb/</link>
					<comments>https://rux.vc/2017.06/safe-and-sound-code-with-kotlin-meetup-in-spb/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sun, 18 Jun 2017 11:31:11 +0000</pubDate>
				<category><![CDATA[kotlin]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[meetup]]></category>
		<category><![CDATA[presentation]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=2985</guid>

					<description><![CDATA[<p>kotlin hardcore whitenights SPb meetup</p>
The post <a href="https://rux.vc/2017.06/safe-and-sound-code-with-kotlin-meetup-in-spb/">Safe and sound code with kotlin</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Following my first talk about writing safe code in kotin at <a href="https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/" target="_blank">London Kotlin Meetup #2</a> I recently had one in Saint-Petersburg. It was organised by Spb Google Developers Group, namely by Oleg Makarov. <a href="https://www.meetup.com/gdgspb/events/240686457/" target="_blank" rel="nofollow">Event</a> took place in the most appropriate place - place where kotlin was born - Jetbrains "Universe" Office at Vasilyevskiy island (it's <i>not</i> kotlin island as someone might think :D).</p>
<p><span id="more-2985"></span></p>
<p>Topic of that talk was same as in London but reflected by received feedback plus some extra things.</p>
<p>Here is slides</p>
<p><iframe src="https://docs.google.com/presentation/d/13WugBvIxNgYVfsyTaFn0n3Wp0wqIOY6yiSsLsuyKWPI/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></p>
<p>All examples can be found at my repo <a href="https://github.com/ruXlab/safe-kotlin-features-showcase/tree/gdg-spb-meetup-15jun2017" target="_blank">github.com/ruXlab/safe-kotlin-features-showcase</a></p>
<p>The extra example was with typesafe units math. With kotlin it's possible to work with different dimensions in very safe manner, so you won't <b>subtract liters from wats</b>. In my basic example I work with distance, time and speed:</p>
<pre><code class="java">fun main(args: Array&lt;String&gt;) {
    println(10.asSeconds + 5.asMinutes)
    // 310.0s

    val speed = 10.asKilometers / 5.asHours
    val speedInMPerSecond = speed.to(Meters / Seconds)
    println(&quot;$speed = $speedInMPerSecond&quot;)
    // 2.0km/h = 0.556m/s

    val speedInMPerHour = speed.to(Miles / Hours)
    println(&quot;$speed = $speedInMPerHour&quot;)
    // 2.0km/h = 1.2427454732996135mi/h

    val `50mph` = 50.asMiles / 1.asHours
    println(&quot;$`50mph` = ${`50mph`.to(Kilometers / Hours)}&quot;)
    // 50.0mi/h = 80.467km/h
}
</code></pre>
<p>From km/h to mi/h - easily! Implementation might seem difficult to understand for someone isn't familiar with kotlin syntax alot, so I <a href="https://github.com/ruXlab/safe-kotlin-features-showcase/tree/gdg-spb-meetup-15jun2017/src/units_conversion" target="_blank">broke up it to step-by-step instructions</a></p>
<p>According to meetup.com there were ~100 people while I'd say ~80. After talk I was asked a lot of questions starting from presentation's topics ending up with testing, frameworks and some hate of php and js <b>of course</b>.</p>
<p>And yeah, I already know what is the next topic I want to present :)</p>The post <a href="https://rux.vc/2017.06/safe-and-sound-code-with-kotlin-meetup-in-spb/">Safe and sound code with kotlin</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.06/safe-and-sound-code-with-kotlin-meetup-in-spb/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2985</post-id>	</item>
		<item>
		<title>Safe code with kotlin &#8211; slides from meetup</title>
		<link>https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/</link>
					<comments>https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Thu, 04 May 2017 21:27:47 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[kotlin]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[meetup]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=2938</guid>

					<description><![CDATA[<p>I had my first talk at Kotlin London meetup #2 about writing safe code. You probably know that I really care about productivity, hence writing safe code is very important part of software development for me. I want compiler check things during compile time not to have exception in production when business can suffer. I ... <a title="Safe code with kotlin &#8211; slides from meetup" class="read-more" href="https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/" aria-label="More on Safe code with kotlin &#8211; slides from meetup">Read more</a></p>
The post <a href="https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/">Safe code with kotlin – slides from meetup</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>I had my first talk at <a href="https://www.meetup.com/kotlin-london/events/239327485/">Kotlin London meetup #2</a> about writing safe code.</p>
<p><span id="more-2938"></span></p>
<p>You probably know that I really care about productivity, hence writing safe code is very important part of software development for me. I want compiler check things during compile time not to have exception in production when business can suffer. I want to code business logic not reinvent checks and write tests(especially unit tests)</p>
<p>There is no video recorded but I have my presentation shared:</p>
<p><iframe src="https://docs.google.com/presentation/d/1WLULsbU1ie6sHzJoFpcHktPTF7_TVY-Q6k7YzxIJ4Po/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></p>
<p>Also, all code snippets are available on <a href="https://github.com/ruXlab/safe-kotlin-features-showcase">github ruXlab/safe-kotlin-features-showcase</a></p>
<h3>Personal note</h3>
<p>It's been a while since I had public presentation.<br />
Before I had only one public presentation in London - at Nexmo, which was internal, only for my colleagues. It was about kotlin as well<br />
That's it. Back in Saint-Petersburg I had a lot of public talks, sometimes even few times a week. Hopefully I can return back on track :)</p>
<p><!--
This presentation was okay, even seems people understood something, I got like 5-7 questions. Unfortunately my vocabulary had been vanished so I used very simple expressions like a kid from kindergarten :D   
--></p>The post <a href="https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/">Safe code with kotlin – slides from meetup</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.05/safe-code-with-kotlin-slides-from-meetup/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2938</post-id>	</item>
		<item>
		<title>RPI Zero scan button</title>
		<link>https://rux.vc/2017.03/rpi-zero-scan-button/</link>
					<comments>https://rux.vc/2017.03/rpi-zero-scan-button/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Wed, 29 Mar 2017 21:33:45 +0000</pubDate>
				<category><![CDATA[Electronics]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Quick notes]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[raspberry pi]]></category>
		<guid isPermaLink="false">https://rux.vc/?p=2926</guid>

					<description><![CDATA[<p>While I was finishing wireless scanner and printer server I realised that traditional document scanning approach is not so nice from UX point of view. I really like the way office scanners in multi-functional devices work. Normally if you want to scan you just load stack of paper into and put your email address. Scanner ... <a title="RPI Zero scan button" class="read-more" href="https://rux.vc/2017.03/rpi-zero-scan-button/" aria-label="More on RPI Zero scan button">Read more</a></p>
The post <a href="https://rux.vc/2017.03/rpi-zero-scan-button/">RPI Zero scan button</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>While I was finishing wireless scanner and printer server I realised that traditional document scanning approach is not so nice from UX point of view.</p>
<p>I really like the way office scanners in multi-functional devices work. Normally if you want to scan you just load stack of paper into and put your email address. Scanner does the rest and in minute you'll get ready-to-use pdf file in your inbox.</p>
<p>I was thinking about having button attached to RPI Zero which initiates scanning and document upload.</p>
<p><span id="more-2926"></span></p>
<p>Alternatively it's possible to program another/one more action, for instance document copy. It's really up to developer - Raspberry PI provides you endless possibilities!</p>
<p>Let's build this scan button:</p>
<ul>
<li>It should indicate scanning process right after user hit the button. The problem is the scanner has to be pre-heated to operate and it can take up to 20-30 seconds. User shouldn't be puzzled by current process. </li>
<li>To display current process we need LED. I found yellow LED 3v</li>
<li>Scanned document should be placed in shared folder accessible from all popular OS. There are not so many options, hence we have to use <strong>Samba</strong>(windows files sharing service)</li>
<li>Documents older than 1h should be removed from that shared folder</li>
<li>Scanned document format - <strong>jpg</strong></li>
</ul>
<h2>Prepare environment</h2>
<p>First things first - we need python libraries and samba server</p>
<pre><code class="bash">sudo apt-get install samba
sudo apt-get install python3-gpiozero python-gpiozero python-pkg-resources
</code></pre>
<h2>Button script</h2>
<p>The script is fairly simple.</p>
<p>It configures LED and Button ports. Then listens to button event. When button is clicked LED blinks to indicate process start and script excecutes <strong>scanimage</strong> utility which convert output from <strong>ppm</strong> to <strong>jpg</strong> format.</p>
<pre><code class="python">&lt;br /&gt;from gpiozero import Button, PWMLED
from signal import pause
from time import sleep, strftime
import os;


OUT_FOLDER=&quot;/smb/scanner&quot;

led = PWMLED(15)
button = Button(23, pull_up=True, hold_repeat=False)

def blink():
  for i in range(20):
    if i % 2 == 0: led.off()
    else: led.value = 0.3
    sleep(0.1)
  led.off()

def toggle():
  blink()
  led.value = 0.3
  ts = strftime(&quot;%d-%b-%Y %H.%M.%S.jpg&quot;)
  cmd = &quot;scanimage --resolution 150 | convert - jpg:- &gt; &#039;{}/{}&#039;&quot;.format(OUT_FOLDER, ts)
  print(&quot;Scanning... {}&quot;.format(cmd))
  os.system(cmd)
  led.off()


button.when_released = toggle

pause()
</code></pre>
<p>PWMLED is used in this script on purpose. Seems like I bought too powerful led without any specs - lady in the shop ensured me that it's low current LED. Unfortunately one of GPIO port has died after I left it on for 10 minutes. To avoid burning another GPIO pin I enabled PWM for LED, if you never heard about it <a href="https://en.wikipedia.org/wiki/Pulse-width_modulation">read wikipedia</a>. From my experiments I found brightness of 30%(0.3) seems minimum acceptable for me. You might need to connect your led via resistor, depending on it's current and voltage.</p>
<p>I couldn't run this script under non-privileged user unfortunately because <strong>scanimage</strong> command doesn't detect scanner. I think there were problems with USB device permission but if you care I'm sure it's possible to fix it.</p>
<h2>Done</h2>
<p>I forgot to copy other configuration files for samba server, crond and systemd and now I don't have access to RPI but trust me it used to work :D I'll put here other configs later on</p>
<p align="right" style="color: gray">This blogpost has been written in airplane over Baltic sea on the way to London</p>The post <a href="https://rux.vc/2017.03/rpi-zero-scan-button/">RPI Zero scan button</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.03/rpi-zero-scan-button/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2926</post-id>	</item>
		<item>
		<title>ML: Predict sequence of values</title>
		<link>https://rux.vc/2017.03/ml-predicting-values-in-sequence/</link>
					<comments>https://rux.vc/2017.03/ml-predicting-values-in-sequence/#respond</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Sat, 11 Mar 2017 21:41:54 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[keras]]></category>
		<category><![CDATA[machine learning]]></category>
		<category><![CDATA[neural networks]]></category>
		<category><![CDATA[sequence]]></category>
		<guid isPermaLink="false">http://rux.vc/?p=2878</guid>

					<description><![CDATA[<p>Let's say we have nice a line built up of two damped oscillators as it displayed on the picture. What if I say it's possible to predict 700 values of this line using just: 30 data points for feeding neural network(which is just half-period) using just two fully-connected layers (hence it's not deep network) having ... <a title="ML: Predict sequence of values" class="read-more" href="https://rux.vc/2017.03/ml-predicting-values-in-sequence/" aria-label="More on ML: Predict sequence of values">Read more</a></p>
The post <a href="https://rux.vc/2017.03/ml-predicting-values-in-sequence/">ML: Predict sequence of values</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Let's say we have nice a line built up of two damped oscillators as it displayed on the picture.</p>
<p>What if I say it's possible to predict 700 values of this line using just:</p>
<ul>
<li>30 data points for feeding neural network(which is just half-period)</li>
<li>using just <strong>two</strong> fully-connected layers (hence it's not <em>deep</em> network)</li>
<li>having just <strong>three</strong> neurons in whole network</li>
</ul>
<p><span id="more-2878"></span></p>
<p>I was quite surprised how fast NN could learn from such a small input even without &quot;seeing&quot; one full period. In <a href="https://github.com/ruXlab/keras-experiments/blob/master/2-SGD-for-polynomial-function/stochastic-gradient-descent-for-polynomial-fn.ipynb">previous experiment</a> I trained network providing <em>actual</em> argument of that function as input of NN.</p>
<p>So what is the difference? In this experiment you can find method <strong>dataset()</strong> which generates pair of (X, Y) from the actual function values. It's something similar to &quot;sliding window&quot; over function's values. For instance if our function <strong>f()</strong> produces values (n<sub>1</sub>, n<sub>2</sub>, n<sub>3</sub>, n<sub>4</sub>) then dataset to be fed to NN looks like (n<sub>1</sub>, n<sub>2</sub>), (n<sub>2</sub>, n<sub>3</sub>), (n<sub>3</sub>, n<sub>4</sub>).</p>
<h2>Show me output!</h2>
<p><img decoding="async" src="http://rux.vc/wp-content/uploads/2017/03/Screenshot-from-2017-03-11-21-26-31.png" alt="" width="891" height="306" class="aligncenter size-full wp-image-2883" srcset="https://rux.vc/wp-content/uploads/2017/03/Screenshot-from-2017-03-11-21-26-31.png 891w, https://rux.vc/wp-content/uploads/2017/03/Screenshot-from-2017-03-11-21-26-31-150x52.png 150w, https://rux.vc/wp-content/uploads/2017/03/Screenshot-from-2017-03-11-21-26-31-300x103.png 300w, https://rux.vc/wp-content/uploads/2017/03/Screenshot-from-2017-03-11-21-26-31-768x264.png 768w" sizes="(max-width: 891px) 100vw, 891px" /></p>
<p><span style="color: red">Red line</span> is what our NN has predicted. Barely visible <span style="color: lightblue">light blue spikes</span> - true value. Not bad for just 3 neurons, huh?</p>
<p>In the first cell of <a href="https://github.com/ruXlab/keras-experiments/blob/master/6-damped-oscillator-function/6-damped-oscillator-regression.ipynb">notebook</a> you can play with hyperparameters <em>(SAMPLES, EPOCHS, BATCH_SIZE)</em> and see differences in the result. Default ones aren't optimal thats why you can spot light blue line on the chart. Increasing amount of input datapoints and/or number of epochs will dramatically increase precision quality and MSE → 0</p>
<p><a href="https://github.com/ruXlab/keras-experiments/blob/master/6-damped-oscillator-function/6-damped-oscillator-regression.ipynb" target="_blank" style="font-size: 200%" rel="noopener noreferrer">Open Experiment In GitHub</a></p>
<p>For other experiments using keras check out <a href="http://rux.vc/2016.11/first-experiments-with-ml-using-keras/">this 1st post</a></p>The post <a href="https://rux.vc/2017.03/ml-predicting-values-in-sequence/">ML: Predict sequence of values</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.03/ml-predicting-values-in-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2878</post-id>	</item>
		<item>
		<title>Amazon Alexa Skill: London Bus Stop</title>
		<link>https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/</link>
					<comments>https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/#comments</comments>
		
		<dc:creator><![CDATA[ruX]]></dc:creator>
		<pubDate>Tue, 07 Mar 2017 23:59:02 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Notes about life in London]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[alexa-london-bus-stop]]></category>
		<category><![CDATA[bus stop]]></category>
		<category><![CDATA[flask]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">http://rux.vc/?p=2869</guid>

					<description><![CDATA[<p>Do you prefer to use warm, quiet, spacious bus? Me too Every time I'm leaving home I have to get updates about time when next busses come to my bus stop. For that reason I literally keep TFL tab open all the time in my mobile I've got freelance job to write Alexa Skill so ... <a title="Amazon Alexa Skill: London Bus Stop" class="read-more" href="https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/" aria-label="More on Amazon Alexa Skill: London Bus Stop">Read more</a></p>
The post <a href="https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/">Amazon Alexa Skill: London Bus Stop</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></description>
										<content:encoded><![CDATA[<p>Do you prefer to use warm, quiet, spacious bus? Me too<br />
Every time I'm leaving home I have to get updates about time when next busses come to my bus stop. For that reason I literally keep TFL tab open all the time in my mobile</p>
<p>I've got freelance job to write Alexa Skill so I decided to play around with pet project. It's <a href="https://www.amazon.co.uk/dp/B01N4DKTNY">London Bus Stop</a> - custom Alexa Skill which helps user to get information about busses coming to saved bus stop.</p>
<p><span id="more-2869"></span></p>
<h2>How to install it?</h2>
<p>Go to <a href="https://www.amazon.co.uk/dp/B01N4DKTNY">London Bus Stops</a> and get this skill or just say <strong>Alexa enable London Bus Stops skill</strong>.</p>
<h2>How to configure it?</h2>
<h3>TL;DR;</h3>
<p>Go to <a href="https://tfl.gov.uk/travel-information/stations-stops-and-piers/">TFL website</a> and search for bus stop you want to use. On the stop's page you'll find a short 5-digit code(same one you can find on the sign plate):</p>
<p><img decoding="async" src="http://rux.vc/wp-content/uploads/2017/03/tfl-short-bus-code.png?" alt="" width="844" height="560" class="aligncenter size-full wp-image-2871" srcset="https://rux.vc/wp-content/uploads/2017/03/tfl-short-bus-code.png 844w, https://rux.vc/wp-content/uploads/2017/03/tfl-short-bus-code-150x100.png 150w, https://rux.vc/wp-content/uploads/2017/03/tfl-short-bus-code-300x199.png 300w, https://rux.vc/wp-content/uploads/2017/03/tfl-short-bus-code-768x510.png 768w" sizes="(max-width: 844px) 100vw, 844px" /></p>
<p>After that say <strong>«Alexa, ask London Bus Stops for setup»</strong>. You'll be asked for that 5 digit code you have to verb and confirm. Sometimes Alexa Platform can't understand what number you meant so try different combinations. For <strong>48584</strong> if could be <strong>48-58-4</strong>, <strong>4-85-84</strong> or <strong>48-584</strong> and so on.</p>
<h3>Why configuration is so difficult?</h3>
<p>This is very tricky question. Due Alexa platform restrictions it's nearly impossible say something like <strong>«Remember my bus stop is Old Street»</strong> because:</p>
<ul>
<li>Old Street has 4 pairs of bus stops</li>
<li>Each pair has 2 directions</li>
<li>Platform restrictions don't allow to use speech-to-text</li>
<li>If skill found few bus stops it's annoying to use voice interface to make a selection</li>
</ul>
<p>After some experiment I ended up with most reliable way to setup bus stop using short code. If you have other ideas I'm very open to it!</p>
<h2>How does it work?</h2>
<p>Thanks to <a href="https://data.gov.uk/">UK Open Data Portal</a> and very well done <a href="https://tfl.gov.uk/info-for/open-data-users/data-feeds?intcmp=29422">Transport For London API</a>.</p>
<p>Server is written in python using <a href="https://github.com/johnwheeler/flask-ask">flask-ask</a>. It's very nice unofficial library of decorators for flask. Code looks very concise and decorators make it looks like it's java annotations :)</p>
<p><code lang="python"><br />
@ask.intent(&quot;ConfigureIntent&quot;)<br />
def configure(is_repeat = False):<br />
msg = render_template(&quot;configure&quot; if not is_repeat else &quot;configure_repeat&quot; )<br />
session.attributes[&#039;mode&#039;] = &quot;configuration&quot;<br />
return question(msg)<br />
</code></p>
<p>I have found and prepared database with shortcode, longcode and busstop name which is used for search and real time updates queries. Every time user ask for update skill find associated longcode stop id and make query to TFL API, process response and reads the result</p>
<h2>Why did I create it?</h2>
<p>Even I don't have Alexa at the moment I hope Londoners will find it useful in daily life :) I might publish it to open source as it free anyways</p>The post <a href="https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/">Amazon Alexa Skill: London Bus Stop</a> first appeared on <a href="https://rux.vc">Hey, ruX is here.</a>.]]></content:encoded>
					
					<wfw:commentRss>https://rux.vc/2017.03/amazon-alexa-skill-london-bus-stop/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2869</post-id>	</item>
	</channel>
</rss>
