<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>emre şahin's digital garden 🍃 - programming</title>
    <link>https://emresahin.net/categories/programming/</link>
    <description>Posts in the programming category</description>
    <language>en</language>
    <managingEditor>contact@emresahin.net (Emre Şahin)</managingEditor>
    <lastBuildDate>Tue, 15 Sep 2026 19:46:32 +0000</lastBuildDate>
    <atom:link href="https://emresahin.net/categories/programming/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>bits 21</title>
      <published>2025-09-28T18:00:14+00:00</published>
      <updated>2025-09-28T18:00:14+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sun, 28 Sep 2025 18:00:14 +0000</pubDate>
      <link>https://emresahin.net/bits-21/</link>
      <guid isPermaLink="true">https://emresahin.net/bits-21/</guid>
      <description>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini. Gemini proposed this: git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length What I ended up ...</description>
      <category>bits</category>
      <category>programming</category>
      <category>Gemini</category>
      <category>nushell</category>
      <category>git</category>
      <category>regex</category>
      <category>LLM</category>
      <content:encoded><![CDATA[<p>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini.</p>
<p>Gemini proposed this:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length
</code></pre>
<p>What I ended up doing:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -a "{+" "" | str replace -a "+}" "" | str replace -a ' ' "\n" | lines | length
</code></pre>
<p>I notice LLMs tend to err on the side of complexity. I don’t know if this is due to their training to spit out as many tokens as possible, but using regular expressions when a simple string replacement may suffice is a good sign that they may be adding more complexity than necessary.</p>]]></content:encoded>
    </item>
    <item>
      <title>bits 20</title>
      <published>2025-09-28T17:52:31+00:00</published>
      <updated>2025-09-28T17:52:31+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sun, 28 Sep 2025 17:52:31 +0000</pubDate>
      <link>https://emresahin.net/bits-20/</link>
      <guid isPermaLink="true">https://emresahin.net/bits-20/</guid>
      <description>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini. Gemini proposed this: git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length What I ended up ...</description>
      <category>bits</category>
      <category>programming</category>
      <category>Gemini</category>
      <category>nushell</category>
      <category>git</category>
      <category>regex</category>
      <category>LLM</category>
      <content:encoded><![CDATA[<p>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini.</p>
<p>Gemini proposed this:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length
</code></pre>
<p>What I ended up doing:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -a "{+" "" | str replace -a "+}" "" | str replace -a ' ' "\n" | lines | length
</code></pre>
<p>I notice LLMs tend to err on the side of complexity. I don’t know if this is due to their training to spit out as many tokens as possible, but using regular expressions when a simple string replacement may suffice is a good sign that they may be adding more complexity than necessary.</p>]]></content:encoded>
    </item>
    <item>
      <title>bits 19</title>
      <published>2025-09-28T17:42:11+00:00</published>
      <updated>2025-09-28T17:42:11+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sun, 28 Sep 2025 17:42:11 +0000</pubDate>
      <link>https://emresahin.net/bits-19/</link>
      <guid isPermaLink="true">https://emresahin.net/bits-19/</guid>
      <description>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini. Gemini proposed this: git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length What I ended up ...</description>
      <category>bits</category>
      <category>programming</category>
      <category>Gemini</category>
      <category>nushell</category>
      <category>git</category>
      <category>regex</category>
      <category>LLM</category>
      <content:encoded><![CDATA[<p>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini.</p>
<p>Gemini proposed this:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length
</code></pre>
<p>What I ended up doing:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -a "{+" "" | str replace -a "+}" "" | str replace -a ' ' "\n" | lines | length
</code></pre>
<p>I notice LLMs tend to err on the side of complexity. I don’t know if this is due to their training to spit out as many tokens as possible, but using regular expressions when a simple string replacement may suffice is a good sign that they may be adding more complexity than necessary.</p>]]></content:encoded>
    </item>
    <item>
      <title>bits 18</title>
      <published>2025-09-28T17:22:48+00:00</published>
      <updated>2025-09-28T17:22:48+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sun, 28 Sep 2025 17:22:48 +0000</pubDate>
      <link>https://emresahin.net/bits-18/</link>
      <guid isPermaLink="true">https://emresahin.net/bits-18/</guid>
      <description>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini. Gemini proposed this: git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length What I ended up ...</description>
      <category>bits</category>
      <category>programming</category>
      <category>Gemini</category>
      <category>nushell</category>
      <category>git</category>
      <category>regex</category>
      <category>LLM</category>
      <content:encoded><![CDATA[<p>I wanted to get the number of word changes between commits in my blog. I asked for a git-diff-based Nushell pipeline from Gemini.</p>
<p>Gemini proposed this:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -r '\{\+|\+\}' '' | str join " " | str words | length
</code></pre>
<p>What I ended up doing:</p>
<pre><code class="language-nushell">git diff --word-diff=plain -- "*.md" | rg -o '\{\+(.*?)\+\}' | str replace -a "{+" "" | str replace -a "+}" "" | str replace -a ' ' "\n" | lines | length
</code></pre>
<p>I notice LLMs tend to err on the side of complexity. I don’t know if this is due to their training to spit out as many tokens as possible, but using regular expressions when a simple string replacement may suffice is a good sign that they may be adding more complexity than necessary.</p>]]></content:encoded>
    </item>
    <item>
      <title>Rust `ends_with` and `strip_prefix` behavior differences in `Path` and `str`</title>
      <published>2022-07-06T16:03:51+00:00</published>
      <updated>2022-07-06T16:03:51+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Wed, 06 Jul 2022 16:03:51 +0000</pubDate>
      <link>https://emresahin.net/Rust--ends_with--and--strip_prefix--behavior-differences-in--Path--and--str-/</link>
      <guid isPermaLink="true">https://emresahin.net/Rust--ends_with--and--strip_prefix--behavior-differences-in--Path--and--str-/</guid>
      <description>While writing an ignore library, I encountered subtle bugs caused by Rust’s Path behavior. ends_with in Path is different from ends_with in str : If you try to check whether a Path is a directory by its final character, you’ll find that path.ends_with("/") returns false . Path::strip_prefix also ...</description>
      <category>development</category>
      <category>rust</category>
      <category>programming</category>
      <category>rust</category>
      <category>Path</category>
      <category>str</category>
      <category>std</category>
      <category>debugging</category>
      <content:encoded><![CDATA[<p>While writing an ignore library, I encountered subtle bugs caused by Rust’s <code>Path</code> behavior.</p>
<ul>
<li>
<p><strong><code>ends_with</code> in <code>Path</code> is different from <code>ends_with</code> in <code>str</code></strong>:
If you try to check whether a <code>Path</code> is a directory by its final character, you’ll find that <code>path.ends_with("/")</code> returns <code>false</code>.</p>
</li>
<li>
<p><strong><code>Path::strip_prefix</code> also consumes the final slash</strong>:
If you have a directory marker at the end, such as <code>/Users/emre/mydir/</code>, and pass it to <code>strip_prefix("/Users/emre")</code>, you’ll get <code>mydir</code> instead of <code>mydir/</code>.</p>
</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Creating OS-dependent temporary directories in Rust</title>
      <published>2022-06-11T06:02:43+00:00</published>
      <updated>2022-06-11T06:02:43+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sat, 11 Jun 2022 06:02:43 +0000</pubDate>
      <link>https://emresahin.net/Creating-OS-dependent-temporary-directories-in-Rust/</link>
      <guid isPermaLink="true">https://emresahin.net/Creating-OS-dependent-temporary-directories-in-Rust/</guid>
      <description>There are a few crates in Rust for retrieving system-dependent directories, such as the user’s home or the system configuration directory. The one I prefer is directories-next . Recently, I needed a standard way to get the temporary directory. I checked the crate documentation but couldn’t find a...</description>
      <category>Rust</category>
      <category>Programming</category>
      <category>temporary directory</category>
      <category>crates</category>
      <category>standard library</category>
      <category>PathBuf</category>
      <content:encoded><![CDATA[<p>There are a few crates in Rust for retrieving system-dependent directories, such as the user’s home or the system configuration directory. The one I prefer is <a href="https://crates.io/crates/directories-next">directories-next</a>.</p>
<p>Recently, I needed a standard way to get the temporary directory. I checked the crate documentation but couldn’t find a proper function for this.</p>
<p>Then I noticed that <a href="https://doc.rust-lang.org/std/env/fn.temp_dir.html"><code>std::env::temp_dir()</code></a> returns a <code>PathBuf</code> pointing to the system’s temporary directory. This is a reminder to myself that we don’t always need extra packages for basic functionality.</p>]]></content:encoded>
    </item>
    <item>
      <title>Factory Constructors in Dart</title>
      <published>2020-12-26T01:03:56+00:00</published>
      <updated>2020-12-26T01:03:56+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sat, 26 Dec 2020 01:03:56 +0000</pubDate>
      <link>https://emresahin.net/factory-constructors-in-dart/</link>
      <guid isPermaLink="true">https://emresahin.net/factory-constructors-in-dart/</guid>
      <description>Dart supports factory constructors, which can return an instance of a subtype or even a cached instance. To create a factory constructor, use the factory keyword: class Square extends Shape {} class Circle extends Shape {} class Shape { Shape(); factory Shape.fromTypeName(String typeName) { if (t...</description>
      <category>Dart</category>
      <category>Programming</category>
      <category>Software Development</category>
      <category>oop</category>
      <category>factory-pattern</category>
      <category>constructors</category>
      <category>dart-lang</category>
      <category>design-patterns</category>
      <content:encoded><![CDATA[<p>Dart supports factory constructors, which can return an instance of a subtype or even a cached instance.
To create a factory constructor, use the <code>factory</code> keyword:</p>
<pre><code class="language-dart">class Square extends Shape {}

class Circle extends Shape {}

class Shape {
  Shape();

  factory Shape.fromTypeName(String typeName) {
    if (typeName == 'square') return Square();
    if (typeName == 'circle') return Circle();

    throw ArgumentError('I don\'t recognize $typeName');
  }
}
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Anonymous functions in Dart</title>
      <published>2020-03-12T13:06:26+00:00</published>
      <updated>2020-03-12T13:06:26+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Thu, 12 Mar 2020 13:06:26 +0000</pubDate>
      <link>https://emresahin.net/anonymous-functions-in-dart-32304/</link>
      <guid isPermaLink="true">https://emresahin.net/anonymous-functions-in-dart-32304/</guid>
      <description>Sometimes we need anonymous functions for one-off tasks. Dart allows two similar syntaxes for writing these. The first one is used when there is a single expression to write: (a, b) =&gt; a + b The other is used when you need to write multiple statements in an anonymous function: (a, b) { return a +...</description>
      <category>development</category>
      <category>programming</category>
      <category>dart</category>
      <category>lambda</category>
      <category>anonymous-functions</category>
      <category>syntax</category>
      <content:encoded><![CDATA[<p>Sometimes we need anonymous functions for one-off tasks. Dart allows two similar syntaxes for writing these.</p>
<p>The first one is used when there is a single expression to write:</p>
<pre><code class="language-dart">(a, b) =&gt; a + b
</code></pre>
<p>The other is used when you need to write multiple statements in an anonymous function:</p>
<pre><code class="language-dart">(a, b) { 
  return a + b; 
}
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Static Variables in Python</title>
      <published>2018-10-24T21:31:06+00:00</published>
      <updated>2018-10-24T21:31:06+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Wed, 24 Oct 2018 21:31:06 +0000</pubDate>
      <link>https://emresahin.net/static-variables-in-python-14346-27102/</link>
      <guid isPermaLink="true">https://emresahin.net/static-variables-in-python-14346-27102/</guid>
      <description>I use this pattern frequently across different projects and would like to keep it here for reference. Python doesn’t have C-style static variables natively. (Although it supports class variables , which can be used for a similar purpose in OOP.) However, since functions are also objects in Python...</description>
      <category>Python</category>
      <category>Programming</category>
      <category>Static Variables</category>
      <category>Decorators</category>
      <category>Snippets</category>
      <content:encoded><![CDATA[<p>I use this pattern frequently across different projects and would like to keep it here for reference.</p>
<p>Python doesn’t have C-style <em>static</em> variables natively. (Although it supports
<em>class variables</em>, which can be used for a similar purpose in OOP.) However, since
functions are also objects in Python, it’s possible to <em>embed</em> variables inside
the function. An elegant solution on
<a href="https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/28401932">Stack Overflow</a>
creates a decorator for static variables.</p>
<pre><code class="language-python">def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate

@static_vars(counter=0)
def foo():
    foo.counter += 1
    print(f"Counter is {foo.counter}")
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>R Notes</title>
      <published>2013-03-12T14:00:00+00:00</published>
      <updated>2013-03-12T14:00:00+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Tue, 12 Mar 2013 14:00:00 +0000</pubDate>
      <link>https://emresahin.net/r-notes/</link>
      <guid isPermaLink="true">https://emresahin.net/r-notes/</guid>
      <description>These are notes I took from various sources, including the Coursera Data Analysis course and R’s online help via help.start() . Basics R objects have attributes which can be observed using the attributes() function. &lt;- is the assignment operator. : is used to create integer sequences. For example...</description>
      <category>Data Science</category>
      <category>Programming</category>
      <category>r</category>
      <category>statistics</category>
      <category>data-analysis</category>
      <category>notes</category>
      <content:encoded><![CDATA[<p>These are notes I took from various sources, including the <a href="https://class.coursera.org/compdata-002/">Coursera Data Analysis</a> course and R’s online help via <code>help.start()</code>.</p>
<h1 id="basics">Basics</h1>
<p>R objects have attributes which can be observed using the <code>attributes()</code> function.</p>
<p><code>&lt;-</code> is the assignment operator.</p>
<p><code>:</code> is used to create integer sequences. For example, <code>1:4</code> results in <code>1 2 3 4</code>.</p>
<p>The <code>c()</code> function (concatenate) can be used to create vectors from different kinds of objects:</p>
<ul>
<li><code>c(TRUE, FALSE)</code> creates a logical vector.</li>
<li><code>c(1+3i, 4+8i, 3-5i)</code> creates a complex vector.</li>
</ul>
<p>Type coercion happens if different kinds of objects are mixed.</p>
<p><code>as.*</code> functions can be used to coerce data types. For example, <code>as.numeric(TRUE)</code> returns <code>1</code>.</p>
<p><code>matrix(ncol = 3, nrow = 4)</code> creates a matrix.</p>
<p><code>cbind()</code> and <code>rbind()</code> are other options to create a matrix from vectors by binding them as columns or rows.</p>
<p><code>factor</code>s are categorized data, like <code>male/female</code>. They are created using the <code>factor()</code> function. The <code>table()</code> and <code>unclass()</code> functions can also be used to get information or change the factor into a numeric table.</p>
<p>The <code>levels</code> parameter in the <code>factor()</code> function can be used to determine the factor-to-number correspondence.</p>
<p><code>is.nan()</code> and <code>is.na()</code> functions are used to check whether vector values are <code>NaN</code> or <code>NA</code>.</p>
<p><code>data.frame</code>s are used to store tabular data like matrices. Unlike matrices, they can store different types of data in each column (e.g., the first column can be numeric, the second a factor, and the third logical).</p>
<p><code>data.frame</code>s are usually created using the <code>read.table()</code> or <code>read.csv()</code> functions. Each row has a name which can be accessed by <code>row.names()</code>. A data frame can be converted to a matrix with <code>data.matrix()</code>.</p>
<p><code>nrow()</code> and <code>ncol()</code> functions can be used to get the number of rows and columns.</p>
<p><code>str()</code> and <code>summary()</code> functions provide concise information about a data structure.</p>
<p>Use <code>getwd()</code> to report the current working directory, and <code>setwd()</code> to change it.</p>
<p>The <code>ls()</code> function displays the names of objects in your workspace:</p>
<pre><code class="language-r">&gt; x &lt;- 10
&gt; y &lt;- 50
&gt; z &lt;- c("three", "blind", "mice")
&gt; f &lt;- function(n, p) sqrt(p * (1 - p) / n)
&gt; ls()
[1] "f" "x" "y" "z"
</code></pre>
<p>The <code>rm()</code> function permanently removes one or more objects from the workspace.</p>
<h1 id="scripts">Scripts</h1>
<p>R executes the <code>.Rprofile</code> script when it starts. The location of <code>.Rprofile</code> depends on your platform; on Linux/Unix, it is typically in your home directory: <code>~/.Rprofile</code>.</p>
<p>The <code>source()</code> function instructs R to read a text file and execute its contents:</p>
<pre><code class="language-r">source("myScript.R")
</code></pre>
<p>On the command line, this can be run as:</p>
<pre><code class="language-bash">$ R CMD BATCH /home/jim/psych/adoldrug/partyuse1.R
</code></pre>
<p>Managing various objects used in R can be challenging. Sorting objects into sensible directory structures can help. You may wish to keep a directory of R scripts that change the working directory to suit the task they perform.</p>
<p><code>par(ask=TRUE)</code> requires you to hit Enter before each plot is displayed.</p>
<p><code>readline("Press &lt;Enter&gt; to continue")</code> presents a prompt to the user.</p>
<h1 id="vectors">Vectors</h1>
<p>Vectors are created like <code>v &lt;- c(1.1, 2.2, 3.3)</code>. Vectors can be used in arithmetic expressions, such as <code>x &lt;- v + 2 * w</code>. A shorter vector is <em>cycled</em> until it reaches the length of the longer vector in arithmetic expressions.</p>
<p><code>range()</code> returns the minimum and maximum elements of a vector.</p>
<p><code>sort()</code> sorts a vector in increasing order.</p>
<p><code>sqrt(-17)</code> returns <code>NaN</code>, but <code>sqrt(-17+0i)</code> returns a complex result.</p>
<p>Regular sequences are generated by the <code>:</code> operator. <code>4:10</code> returns <code>[4, 5, 6, 7, 8, 9, 10]</code>. This is syntactic sugar for the <code>seq()</code> function, which can also specify step size and length.</p>
<p>The <code>rep()</code> function repeats supplied elements to create a vector.</p>
<h1 id="arrays">Arrays</h1>
<p>If <code>z</code> is a vector with 1500 elements (e.g., <code>z &lt;- 1:1500</code>), then <code>dim(z) &lt;- c(3, 5, 100)</code> makes it a 3D array with those dimensions.</p>
<p>Another way to create an array is <code>x &lt;- array(1:20, dim=c(4, 5))</code>.</p>
<h1 id="matrices">Matrices</h1>
<p>Two matrices <code>A</code> and <code>B</code> can be multiplied using <code>A %*% B</code>.</p>
<p>A linear equation of the form <code>b &lt;- A %*% x</code> can be solved using <code>solve(A, b)</code>.</p>
<h1 id="lists">Lists</h1>
<p>A list can be created using the <code>list()</code> function. List elements don’t have to be of the same type; they can be anything from characters to vectors.</p>
<pre><code class="language-r">&gt; mylist &lt;- list(name="Fred", no.children=3, child.ages=c(4, 7, 9))
</code></pre>
<p>Components can be accessed by index like <code>mylist[[1]]</code> or by component name like <code>mylist$no.children</code> or <code>mylist[["no.children"]]</code>.</p>
<p>Lists are similar to structs in other languages. The <code>c()</code> function can be used to concatenate lists.</p>
<h1 id="arbitrary-functions">Arbitrary Functions</h1>
<p>An arbitrary function (similar to a lambda) can be created as <code>f &lt;- function(x, y) x + y</code>.</p>
<h1 id="statistical-functions-for-discrete-distributions">Statistical Functions for Discrete Distributions</h1>
<p>The <code>library(distrEx)</code> provides functions <code>E()</code>, <code>var()</code>, and <code>sd()</code> to calculate mean, variance, and standard deviation.</p>
<p>Uniform random events can be emulated with the <code>sample()</code> function. It has three parameters:</p>
<ol>
<li>The range of values to select from.</li>
<li><code>size</code>: the number of events.</li>
<li><code>replace</code>: whether to sample with replacement.</li>
</ol>
<p>Examples:</p>
<ul>
<li>1000 dice rolls: <code>sample(6, size=1000, replace=TRUE)</code></li>
<li>50 random numbers from 1000 to 2000: <code>sample(1000:2000, size=50, replace=TRUE)</code></li>
<li>Flip a fair coin 100 times: <code>sample(c("H", "T"), size=100, replace=TRUE)</code></li>
</ul>
<h1 id="reading-and-writing-data">Reading and Writing Data</h1>
<p><code>read.table()</code> and <code>read.csv()</code> read tabular data from text files.</p>
<p><code>readLines()</code> reads lines of text.</p>
<p><code>source()</code> and <code>dget()</code> read R code files.</p>
<p><code>load()</code> and <code>unserialize()</code> are used to read binary objects.</p>
<p><code>dump()</code> and <code>dput()</code> are the inverses of <code>source()</code> and <code>dget()</code>. They include the object’s metadata in the output.</p>
<p><code>file()</code> is used to open file connections. <code>gzfile()</code> opens gzipped files, and <code>bzfile()</code> opens bzip2 files. The <code>url()</code> command opens a connection to a web page.</p>
<h2 id="readtable"><code>read.table</code></h2>
<p><code>read.table()</code> is the primary function for importing data.</p>
<ul>
<li><code>file</code>: name of the file or connection.</li>
<li><code>header</code>: boolean indicating if the file has a header row.</li>
<li><code>sep</code>: the field separator (comma, tab, etc.).</li>
<li><code>colClasses</code>: a vector of column data types. Specifying this can make R significantly faster.</li>
<li><code>nrows</code>: the number of rows in the dataset.</li>
<li><code>comment.char</code>: character that starts a comment.</li>
<li><code>skip</code>: number of lines to skip from the beginning.</li>
</ul>
<p><code>read.csv()</code> is a wrapper for <code>read.table()</code> with the default separator set to a comma.</p>
<pre><code class="language-r">initial &lt;- read.table("datatable.txt", nrows = 100)
classes &lt;- sapply(initial, class)
tabAll &lt;- read.table("datatable.txt", colClasses = classes)
</code></pre>
<h1 id="plotting">Plotting</h1>
<p><code>plot(x, y)</code> plots the values in <code>x</code> against <code>y</code>. Additional parameters can configure visual settings.</p>
<p>Use the <code>density()</code> function to approximate sample density, and <code>lines()</code> to draw it:</p>
<pre><code class="language-r">hist(x, prob=T)
lines(density(x))
</code></pre>
<h1 id="installing-r-packages">Installing R packages</h1>
<h2 id="method-1-install-from-source">Method 1: Install from source</h2>
<p>Download the package (e.g., <code>mypkg</code>) and run this in the shell:</p>
<pre><code class="language-bash">$ R CMD INSTALL mypkg -l /my/own/R-packages/
</code></pre>
<h2 id="method-2-install-from-cran">Method 2: Install from CRAN</h2>
<p>Run this in the R console:</p>
<pre><code class="language-r">&gt; install.packages("mypkg", lib="/my/own/R-packages/")
</code></pre>
<h2 id="load-the-library">Load the library</h2>
<pre><code class="language-r">&gt; library("mypkg", lib.loc="/my/own/R-packages/")
</code></pre>
<h1 id="statistics">Statistics</h1>
<h2 id="density">Density</h2>
<p>Approximate sample density and draw it:</p>
<pre><code class="language-r">&gt; hist(x, prob=T)
&gt; lines(density(x))
</code></pre>
<h2 id="-notation-for-relations-between-variables"><code>~</code> notation for relations between variables</h2>
<p>R uses a special notation for describing relationships between variables. Suppose you assume a linear model for a variable $y$, predicted from variables $x_1, x_2, \dots, x_n$:</p>
<p>$y \sim x_1 + x_2 + \dots + x_n$</p>
<p>Statisticians refer to $y$ as the dependent variable and $x_i$ as the independent variables. In R, this is represented as a formula object.</p>
<h1 id="working-with-data">Working with data</h1>
<h2 id="creating-a-data-frame">Creating a Data Frame</h2>
<pre><code class="language-r">&gt; points &lt;- data.frame(label=c("Low", "Mid", "High"),
                       lbound=c(0, 0.67, 1.64),
                       ubound=c(0.674, 1.64, 2.33))
</code></pre>
<h2 id="the-print-function">The <code>print()</code> function</h2>
<p>Allows you to specify the number of printed digits:</p>
<pre><code class="language-r">&gt; print(pi, digits=4)
</code></pre>
<h2 id="the-cat-function">The <code>cat()</code> function</h2>
<p>Does not provide direct control over formatting. Use <code>format()</code> before calling <code>cat()</code>:</p>
<pre><code class="language-r">&gt; cat(format(pi, digits=4), "\n")
</code></pre>
<h2 id="the-listfiles-function">The <code>list.files()</code> function</h2>
<p>Shows the contents of your working directory.</p>
<h2 id="the-writecsv-function">The <code>write.csv()</code> function</h2>
<pre><code class="language-r">&gt; write.csv(x, file="filename.csv", row.names=FALSE)
</code></pre>
<h2 id="factor-analysis">Factor analysis</h2>
<p>Available via <code>factanal()</code> in the <code>stats</code> package:</p>
<pre><code class="language-r">factanal(x, factors, data = NULL, covmat = NULL, n.obs = NA,
          subset, na.action, start = NULL,
          scores = c("none", "regression", "Bartlett"),
          rotation = "varimax", control = NULL, ...)
</code></pre>
<h2 id="pca">PCA</h2>
<p>Principal Components Analysis (PCA) breaks a set of correlated variables into uncorrelated variables. Available via <code>prcomp()</code>.</p>
<h2 id="distributions-in-r">Distributions in R</h2>
<ul>
<li><em>Binomial</em>: <code>binom</code> (n = trials, p = probability)</li>
<li><em>Geometric</em>: <code>geom</code> (p = probability)</li>
<li><em>Hypergeometric</em>: <code>hyper</code> (m = white balls, n = black balls, k = balls drawn)</li>
<li><em>Negative Binomial</em>: <code>nbinom</code></li>
<li><em>Poisson</em>: <code>pois</code> (lambda = mean)</li>
<li><em>Beta</em>: <code>beta</code></li>
<li><em>Cauchy</em>: <code>cauchy</code></li>
<li><em>Chi-squared</em>: <code>chisq</code> (df = degrees of freedom)</li>
<li><em>Exponential</em>: <code>exp</code></li>
<li><em>F</em>: <code>f</code></li>
<li><em>Gamma</em>: <code>gamma</code></li>
<li><em>Log-normal</em>: <code>lnorm</code></li>
<li><em>Logistic</em>: <code>logis</code></li>
<li><em>Normal</em>: <code>norm</code></li>
<li><em>Student’s t</em>: <code>t</code></li>
<li><em>Uniform</em>: <code>unif</code></li>
<li><em>Weibull</em>: <code>weibull</code></li>
<li><em>Wilcoxon</em>: <code>wilcox</code></li>
</ul>
<h2 id="combination-calculation">Combination calculation</h2>
<p>Calculating combinations (n choose k) is done via the <code>choose()</code> function:</p>
<pre><code class="language-r">&gt; choose(5, 3)
[1] 10
</code></pre>
<h2 id="generating-combinations">Generating combinations</h2>
<p>Use the <code>combn()</code> function to generate all combinations:</p>
<pre><code class="language-r">&gt; combn(items, k)
</code></pre>
<h2 id="selecting-n-items-from-a-vector">Selecting $n$ items from a vector</h2>
<pre><code class="language-r">&gt; sample(vec, n)
</code></pre>
<h2 id="dotplot-in-lattice"><code>dotplot()</code> in lattice</h2>
<p>The <code>dotplot()</code> function in <code>library(lattice)</code> is useful for displaying labeled quantitative values.</p>
<h2 id="correlation">Correlation</h2>
<p>Correlation ranges between -1 and 1:</p>
<ul>
<li>1: perfect positive linear relationship.</li>
<li>0: no correlation.</li>
<li>-1: perfect negative linear relationship.</li>
</ul>
<h2 id="bootstrapping">Bootstrapping</h2>
<p>Bootstrapping is a technique for estimating the bias/variance of an estimator by repeatedly resampling with replacement. In R, use the <code>boot()</code> function in the <code>boot</code> package.</p>
<h2 id="paste"><code>paste()</code></h2>
<p>The <code>paste()</code> function concatenates multiple character vectors into a single vector.</p>
<h2 id="chi-squared-test">Chi-squared test</h2>
<p>Used for statistical tests of categorical data, such as goodness of fit and independence.</p>
<h2 id="plotting-the-regression-line">Plotting the regression line</h2>
<pre><code class="language-r">&gt; plot(x, y)
&gt; abline(lm.result)
</code></pre>
<h2 id="coefficients-of-regression">Coefficients of regression</h2>
<p>The <code>coef()</code> function returns a vector of coefficients:</p>
<pre><code class="language-r">&gt; coef(lm.result)
</code></pre>
<h2 id="anova">ANOVA</h2>
<p>Analysis of Variance (ANOVA) compares means for more than two independent samples.</p>
<h2 id="regression-analysis">Regression analysis</h2>
<p>Used for modeling the relationship between a response variable ($y$) and one or more predictors ($x$).</p>
<ul>
<li>$p=1$: simple regression.</li>
<li>$p&gt;1$: multiple regression.</li>
</ul>
<h2 id="iid">i.i.d.</h2>
<p>Independent and identically distributed.</p>
<h2 id="linear-models">Linear models</h2>
<p>Despite the name, linear models are flexible and can model curved relationships if predictors are transformed.</p>
<h2 id="failing-to-reject-the-null-hypothesis">Failing to reject the null hypothesis</h2>
<p>Failing to reject the null hypothesis doesn’t mean you “accept” it; it may just mean there is insufficient data or obscured relationships (e.g., due to outliers).</p>
<h2 id="lurking-variables">Lurking variables</h2>
<p>A lurking variable $Z$ might be the real driver behind an observed relationship between $x$ and $y$.</p>
<h2 id="statistical-inference-assumptions">Statistical inference assumptions</h2>
<p>Data must be independent and identically distributed (i.i.d.).</p>]]></content:encoded>
    </item>
    <item>
      <title>Using a Single Threaded Functor in Multiple Threads with Futures in C++</title>
      <published>2013-01-13T14:00:00+00:00</published>
      <updated>2013-01-13T14:00:00+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Sun, 13 Jan 2013 14:00:00 +0000</pubDate>
      <link>https://emresahin.net/12236-21-1527/</link>
      <guid isPermaLink="true">https://emresahin.net/12236-21-1527/</guid>
      <description>Multithreaded programming requires a paradigm shift when it comes to the return values of functions. C++11 provides std::async to run functions asynchronously, but this is not available in older versions. My current project on word spotting in historical documents is fairly complete in functional...</description>
      <category>C++</category>
      <category>Programming</category>
      <category>multithreading</category>
      <category>boost</category>
      <category>c++11</category>
      <category>futures</category>
      <category>concurrency</category>
      <content:encoded><![CDATA[<p>Multithreaded programming requires a paradigm shift when it comes to the return
values of functions. C++11 provides
<a href="http://en.cppreference.com/w/cpp/thread/async"><code>std::async</code></a> to run functions
asynchronously, but this is not available in older versions.</p>
<p>My current project on word spotting in historical documents is fairly
complete in functionality, but I decided that searching for word images on
page images <em>concurrently</em> would be better for speeding it up. I’m already using
<a href="http://boost.org">Boost</a> for much of the functionality, and instead of
creating a dependency on the not-yet-mature C++11 support in various
compilers, I decided to use <code>boost::thread</code>.</p>
<p>Suppose we have a functor such as:</p>
<pre><code class="language-c++">class Search_t
{
   public:
       Search_t(Document d) { ... };
       SearchResult operator()(SearchItem i) { ... };
};
</code></pre>
<p>And we want to use this functor in multiple threads. We can’t simply do the following:</p>
<pre><code class="language-c++">std::vector&lt;SearchResult&gt; results;
Search_t search(document);
// search_items is a vector&lt;SearchItem&gt; and si is an iterator over it.
for (si = search_items.begin(); si != search_items.end(); ++si)
{
   boost::thread task(boost::bind(search, *si));
   results.push_back(task); // ERROR!
}
</code></pre>
<p>This is because <code>task</code> does not return a <code>SearchResult</code>.</p>
<p>Instead, we need to store results within the object and retrieve them
after they are generated.</p>
<p>I didn’t want to change the interface of <code>Search_t</code> because
multithreading should be optional, and other parts of the program may
depend on this interface. Instead, a wrapper class that runs these
threads with a similar interface seemed like a better solution.</p>
<pre><code class="language-c++">class SearchMT_t
{
   boost::shared_ptr&lt;std::vector&lt;boost::unique_future&lt;SearchResult&gt; &gt; &gt; futures_;

   public:
   SearchMT_t(Document d) :
   /* The most important assumption here is that Search_t does not alter
      the Document object's state in any way. Otherwise, we need to ensure that 
      document_ is accessed by only a single thread at a time using mutexes. */
   document_(d),
   futures_(new std::vector&lt;boost::unique_future&lt;SearchResult&gt; &gt;)
   {};

   void operator()(SearchItem si)
   {
       /* If you are sure that there won't be any race conditions
       between Search_t threads during search, you can move the following line
       to the constructor and use a single object for all searches. */
       Search_t search(document_);

       boost::packaged_task&lt;SearchResult&gt; search_task(std::bind(search, si));
       futures_-&gt;push_back(search_task.get_future());
       boost::thread task(boost::move(search_task));
   };

   std::vector&lt;SearchResult&gt; results()
   {
      std::vector&lt;SearchResult&gt; results;

      /* Wait for all threads to complete their work. */
      boost::wait_for_all(futures_-&gt;begin(), futures_-&gt;end());

      for(int i = 0; i &lt; futures_-&gt;size(); ++i)
      {
          results.push_back((*futures_)[i].get());
      }

      return results;
   }
};
</code></pre>
<p>This way, it becomes much more straightforward to use multithreading in
a loop:</p>
<pre><code class="language-c++">std::vector&lt;SearchResult&gt; results;
SearchMT_t search(document);
// search_items is a vector&lt;SearchItem&gt; and si is an iterator over it.
for (si = search_items.begin(); si != search_items.end(); ++si)
{
    search(*si);
}

results = search.results();
</code></pre>
<p>We kept the <code>Search_t</code> class intact and used a much simpler
approach in the loop.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
