<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace V5 Site Server v5.13.156 (http://www.squarespace.com) on Sun, 19 May 2013 23:24:16 GMT--><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><title>kdbfaq</title><link>http://www.kdbfaq.com/kdb-faq/</link><description>Answers. Fast.</description><lastBuildDate>Fri, 08 Mar 2013 17:41:58 +0000</lastBuildDate><copyright>This work is licensed under a Creative Commons License.</copyright><language>en-US</language><generator>Squarespace V5 Site Server v5.13.156 (http://www.squarespace.com)</generator><itunes:author>kdbfaq</itunes:author><itunes:subtitle>Answers. Fast.</itunes:subtitle><itunes:summary>kdb book online</itunes:summary><itunes:keywords>kdb,kdbfaq,q,kdb/q,kdb+,kdb,book,online</itunes:keywords><itunes:owner><itunes:name>kdbfaq</itunes:name><itunes:email>feedback@kdbfaq.com</itunes:email></itunes:owner><itunes:category text="Technology"><itunes:category text="Software How-To"/></itunes:category><item><title>How does fby work?</title><category>SQL HAVING</category><category>Syntax</category><category>amend</category><category>fby</category><category>flilter-by</category><dc:creator>kdbfaq</dc:creator><pubDate>Wed, 21 Nov 2012 20:17:26 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-does-fby-work.html</link><guid isPermaLink="false">817816:9603847:30749085</guid><description><![CDATA[<p>According to code.kx.com, <a href="http://code.kx.com/wiki/Reference/fby" title="code.kx.com" class="offsite-link-inline">fby</a> is short for filter-by, and it is commonly used as the q equivalent to <span class="caps">SQL'</span>s <span class="caps">HAVING </span>clause (though, like <a href="http://code.kx.com/wiki/Reference/where" title="code.kx.com" class="offsite-link-inline">where</a>, <code>fby</code> is a q function, and its use is not limited to where clauses).</p>

<p>What fby does is aggregate values from one list based on groups defined in another, parallel, list.  For example, suppose we have one list of cities and another list with a few temperature samples for each.  We can use fby to calculate the minimum temperature sample for each city, and then replicate those values at each position for each corresponding city:</p>



<pre class='pre'>
q)city:`NY`NY`LA`SF`LA`SF`NY
q)temp:32 31 75 69 70 68 12
q)(min;temp) fby city
12 12 70 68 70 68 12
q)
</pre>



<p>Thus, <span class="caps">NY'</span>s minimum temperature, 12, appears at every index in <code>fby</code>'s output where <code>`NY</code> appears in <code>city</code>.</p>

<p>At the core of fby (like by) is <a href='http://code.kx.com/wiki/Reference/group' class='offsite-link-inline'>group</a>, which organizes the distinct values in a list into a dictionary mapping those values to their indices:</p>



<pre class='pre'>
q)city:`NY`NY`LA`SF`LA`SF`NY
q)group city
NY| 0 1 6
LA| 2 4
SF| 3 5
q)
</pre>



<p>We can group the temperatures for each city together by indexing <code>temp</code> with the value of the grouped city dictionary:</p>



<pre class='pre'>
q)grouped: value group city
q)temp[grouped]
32 31 12
75 70
69 68
q)
</pre>



<p>Note that the result of indexing <code>temp</code> with <code>grouped</code> is a nested list with the same shape as <code>grouped</code>.  This is a general principle: the result of an indexing operation has the shape of the index.</p>

<p>Now we can apply an aggregation function to each of the temperature groups:</p>



<pre class='pre'>
q)min each temp[grouped]
12 70 68
q)
</pre>



<p>We're almost there.  The real trick of <code>fby</code> is placing each aggregation result into a new list so that each element has the correct value per the grouping list.  We can use <a href='http://code.kx.com/wiki/Reference/AtSymbol' class='offsite-link-inline'>@ (functional amend)</a> to get the job done (see also <a href='http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-forms-of-apply-and-amend.html'>the functional apply/amend faq</a>):</p>



<pre class='pre'>
q)@[temp; grouped; :; min each temp[grouped] ]
12 12 70 68 70 68 12
q)
</pre>



<p>The real fby is just slightly more complicated to ensure that the first argument to @ has the correct type.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-30749085.xml</wfw:commentRss></item><item><title>What does it mean for a table to be a flipped dictionary?</title><category>K object structure</category><category>Tables</category><category>dictionary</category><category>dictionary to table</category><category>dictionary type</category><category>flip</category><category>k.h</category><category>key</category><category>keyed table</category><category>keys</category><category>list to table</category><category>table</category><category>type number</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 29 Oct 2012 01:52:39 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/what-does-it-mean-for-a-table-to-be-a-flipped-dictionary.html</link><guid isPermaLink="false">817816:9603847:12561136</guid><description><![CDATA[<p>Short answer:</p>

<p>A table is a reference to a (column) dictionary.</p>

<p><hr/></p>

<p>The internal representation of a table is nearly identical to that of a dictionary.  We can use the <a href="http://code.kx.com/trac/wiki/Reference/flip" title="code.kx.com" class="offsite-link-inline">flip</a> command to create a table from a dictionary:</p>



<pre class='pre'>
q)t: ([] a: 1 2 3; b: 4 5 6; c: 7 8 9)
q)d: `a`b`c ! (1 2 3; 4 5 6; 7 8 9)
q)t ~ flip d
1b
q)
</pre>



<p>In fact, when a dictionary is <code>flip</code>'ed, the underlying core data structure remains untouched.  The table itself is a simple, small object that refers to the original dictionary.  Using <a href='http://code.kx.com/wiki/DotQ/DotQDotw' class='offsite-link-inline'>.Q.w</a>, we can measure how much more memory a table takes than the corresponding dictionary:</p>



<pre class='pre'>
q).Q.w[]`used         // memory usage baseline
112992j
q)x:`a`b`c!3 3#til 9  // create a small dictionary
q).Q.w[]`used
113424j
q)x:flip x
q).Q.w[]`used         // memory usage delta is
113456j               // just 32 more bytes
q)
</pre>



<p>No matter how large the underlying dictionary is, creating a table is fast and still takes only 32 bytes:</p>



<pre class='pre'>
q)x:`a`b`c!3 100000#til 10
q).Q.w[]`used
1686192j
q)x:flip x
q).Q.w[]`used
1686224j          // 32 = 1686224 - 1686192
q)
</pre>



<p><hr/></p>

<p>Now, Let's examine how a <strong>keyed table</strong> is related to a dictionary.  We start by creating a simple keyed table:</p>



<pre class='pre'>
q)t: ([] a: 1 2 3; b: 4 5 6; c: 7 8 9)
q)keyedTable: `a`b xkey t
q)keyedTable
a b| c
---| -
1 4| 7
2 5| 8
3 6| 9
q)keys keyedTable
`a`b
q)
</pre>



<p>Since <code>keyedTable</code> is a table, one might expect it to have the same type as t but instead, q presents the following surprise:</p>



<pre class='pre'>
q)type t              
98h                  // type table as expected
q)type keyedTable
99h                  // *NOT* 98h
q)
</pre>



<p>Type 99h is the <a href="http://code.kx.com/wiki/Reference/Datatypes#Dict_and_Table" title="code.kx.com" class="offsite-link-inline">type number</a> for dictionaries.  If <code>keyedTable</code> really is a dictionary, we should be able to extract its <code>key</code> and <code>value</code>:</p>



<pre class='pre'>
q)key keyedTable
a b
---
1 4
2 5
3 6
q)value keyedTable
c
-
7
8
9
q)
</pre>



<p>Indeed, <code>keyedTable</code> is a dictionary - one that holds <strong>unkeyed</strong> tables for both its key and its value:</p>



<pre class='pre'>
q)type key keyedTable
98h
q)type value keyedTable
98h
q)
</pre>



<p>This suggests that we can create a keyed table by using the <a class='offsite-link-inline' href='http://code.kx.com/wiki/Reference/BangSymbol#dict'>! (dict)</a> operator with two unkeyed tables:</p>



<pre class='pre'>
q)(key keyedTable)!(value keyedTable)
a b| c
---| -
1 4| 7
2 5| 8
3 6| 9
q)
</pre>



<p>Lastly, joining the two flipped tables brings us back to the original dict.  </p>



<pre class='pre'>
q)(flip key keyedTable),(flip value keyedTable)
a| 1 2 3
b| 4 5 6
c| 7 8 9
q)
</pre>



<p>For more information, see <a href=' http://code.kx.com/wiki/Cookbook/InterfacingWithC#Creating_dictionaries_and_tables' class='offsite-link-inline'>Creating dictionaries and tables from C</a>.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12561136.xml</wfw:commentRss></item><item><title>How do I execute a q function call with parameters over IPC?</title><category>::</category><category>IPC</category><category>RPC</category><category>Syntax</category><category>`length</category><category>arguments</category><category>enlist</category><category>parameterized IPC</category><category>plist</category><category>remote</category><category>synchronous</category><dc:creator>kdbfaq</dc:creator><pubDate>Wed, 10 Oct 2012 00:03:16 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-execute-a-q-function-call-with-parameters-over-ipc.html</link><guid isPermaLink="false">817816:9603847:17318533</guid><description><![CDATA[<p>Short answer:</p>



<pre class='pre'>
q)phandle: hopen `:serverhost:5012
q)phandle (function; arg1; arg2 ..)
..
q)hclose phandle
q)
</pre>



<p><hr/></p>

<p>To invoke a function in another q process (i.e., a function that already exists in that q process), you need the following:</p>

<ol>
<li>a <a href='http://code.kx.com/wiki/Reference/hopen' class='offsite-link-inline'>process handle</a> to the other q process,</li>
<li>the name of the pre-existing function in the other process, and</li>
<li>the parameters you want to pass.</li>
</ol>

<p>Then all you need to do is to apply the process handle to a <strong>list</strong> whose first element is the function name (as a symbol) and whose remaining elements are the arguments.</p>

<p>For example, let's start one q process, which will be our server, listening on <span class="caps">TCP </span>port 5012.  In our server, we'll define a function square (we'll make the background color different for the server to make it easier to distinguish from the client):</p>



<pre class='preOrange'>
$ q -p 5012             // server
..
q)\p                    // display the listening port
5012
q)square: {x * x}
q)square 3
9
q)
</pre>



<p>Next, we'll start up another q process (the client), create a process handle connected to the first q process (the server), and request the first process to compute <span class="inline">square 5</span>:</p>



<pre class='pre'>
$ q                     // client
..
q)phandle: hopen `:localhost:5012
q)phandle (`square; 5)  // remote execution
25
q)
</pre>



<p>To call a function with more parameters, simply add them to the end of the list.  We'll demonstrate by defining a 2-argument function on the server that calculates the length of a right triangle's hypotenuse:</p>



<pre class='preOrange'>
q)hypotenuse: {sqrt sum square x,y}
q)hypotenuse[3;4]
5f
q)
</pre>





<pre class='pre'>
q)phandle (`hypotenuse; 5; 12)
13f
q)
</pre>



<p>What if the function you're calling doesn't take any parameters?  For example, we'll define a function in the server called <span class="inline">serverTime</span> that returns the local time according to the server:</p>



<pre class='preOrange'>
q)serverTime: {[] .z.T}
q)serverTime[]
11:51:34.762
q)
</pre>



<p>You can't pass zero parameters over <span class="caps">IPC</span>:</p>



<pre class='pre'>
q)phandle enlist `serverTime  // a list with just
'length                       // the function name
q)                            // is not allowed
</pre>



<p>However, you can pass whatever you like, and it won't matter:</p>



<pre class='pre'>
q)phandle `serverTime`ignored
11:52:28.537
q)phandle (`serverTime; ())    // () is often used
11:52:40.923
q)phandle (`serverTime; ::)    // so is ::
11:52:47.338
q)
</pre>



<p>See <a href='http://code.kx.com/wiki/Reference/ColonColon' class='offsite-link-inline'>:: (generic null)</a>.</p>

<p>So far, all of our examples involved a client invoking a predefined function on the server.  You can also pass a function defined on the client to be executed on the server.  To see this, let's define a global variable on the server:</p>



<pre class='preOrange'>
q)SERVERGLOBAL: 47
q)
</pre>



<p>Now, on the client, we'll define a function called getSERVERGLOBAL to retrieve the value of <span class="caps">SERVERGLOBAL </span>on the server.  Instead of passing the name of the function (i.e., `getSERVERGLOBAL), we pass the function's value:</p>



<pre class='pre'>
q)getSERVERGLOBAL: {[] SERVERGLOBAL}
q)getSERVERGLOBAL[]
'SERVERGLOBAL                   // not defined here
q)phandle (getSERVERGLOBAL; ::) // note the missing `
47
q)
</pre>



<p>Notice that this operation does not cause getSERVERGLOBAL to become defined on the server:</p>



<pre class='preOrange'>
q)getSERVERGLOBAL
'getSERVERGLOBAL
q)
</pre>



<p>This technique can be used to run built-in functions and anonymous functions (aka lambdas) on the server as well:</p>



<pre class='pre'>
q)phandle (+; 2; 4)
6
q)phandle ({til SERVERGLOBAL - x}; 42)
0 1 2 3 4
q)
</pre>



<p>There is one more way to convey code to the server to run: you can pass the code in a string.</p>



<pre class='pre'>
q)phandle &quot;SERVERGLOBAL + 4&quot;
51
q)
</pre>



<p>We prefer passing a function over a string, because - especially as the expression to be passed gets more complex - it's easier to read.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-17318533.xml</wfw:commentRss></item><item><title>How do I use the functional forms of apply and amend?</title><category>.</category><category>@</category><category>Functions</category><category>amend</category><category>apply</category><category>functional form amend</category><category>functional form apply</category><category>protected execution</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 27 Feb 2012 03:27:37 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-forms-of-apply-and-amend.html</link><guid isPermaLink="false">817816:9603847:12386134</guid><description><![CDATA[<p>Typical <span class="inline">q</span> code operates on all of the elements of a container at once:</p>



<pre class='pre'>
q)container: 1 2 3
q)100 * container
100 200 300
q)
</pre>



<p>Sometimes we are interested in only a subset of elements from a container:</p>



<pre class='pre'>
q)container: til 10
q)container
0 1 2 3 4 5 6 7 8 9
q)container[where 0 = container mod 2]
0 2 4 6 8
q)                                                                                                         
</pre>



<p>Sometimes, however, you need to update particular elements of a structure while leaving the remaining elements unchanged.  That's what functional apply and amend are for; they transform specific elements of a container without touching the others.  The variations are distinguished by 3 choices:</p>

<p>1. <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> or <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a></p>

<p>Which operator is used, <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> or <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a>, determines the interpretation of the <b>indices</b> used to select the elements to transform.</p>

<p>2. container or name</p>

<p>The first argument is either the value of a container or the name of a global variable referring to a container.  In the former case, a new object is returned; in the latter, the global variable is modified and its name is returned.</p>

<p>3. monadic or dyadic function</p>

<p>If the transformation requires additional information beyond that contained in each element itself, that is accomplished by using a dyadic function and supplying the additional information in a fourth argument to the operator.</p>

<p>For a detailed discussion, please see the following faqs:</p>

<p><a href='http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-form-of-at-apply.html'>Functional @ (apply)</a><br />
<a href='http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-form-of-dot-apply.html'>Functional . (apply)</a></p>

<p>Lastly, note that there is another pair of overloads for <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> and <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a> - each with three arguments - called protected execution, which are invoked when the first argument to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> or <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a> is a function or projection; protected execution is discussed in another <a href='http://www.kdbfaq.com/kdb-faq/how-does-protected-execution-or-exception-handling-work-in-q.html'>faq</a>.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12386134.xml</wfw:commentRss></item><item><title>How do I use the functional form of @ (at) apply?</title><category>@</category><category>Functions</category><category>amend</category><category>apply</category><category>functional form apply</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 27 Feb 2012 03:26:40 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-form-of-at-apply.html</link><guid isPermaLink="false">817816:9603847:12582965</guid><description><![CDATA[<p>Short answer:</p>



<pre class='pre'>
1. @[container; indices; function]
2. @[container; indices; function; second_args]
</pre>



<p>(Note that there is another overload for <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> with three arguments, called protected execution, which is invoked when the first argument to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> is a function or projection; protected execution is discussed in another <a href='http://www.kdbfaq.com/kdb-faq/how-does-protected-execution-or-exception-handling-work-in-q.html'>faq</a>.)</p>

<p><hr/></p>

<p>In the 3-argument case, <span class="inline">q</span> applies <span class="inline">function</span> to those elements of <span class="inline">container</span> specified by <span class="inline">indices</span>, leaving the rest of <span class="inline">container</span> alone.  In other words, the behavior of 3-argument <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> resembles that of the following function:</p>

<script src="https://gist.github.com/1920831.js?file=apply.q"></script>

<p>Although this model breaks down when the first argument is a global variable name, it is very helpful in understanding what is going on even in that case.  Let's look at a couple of simple examples to clarify this:</p>



<pre class='pre'>
q)list: 1 + til 8
q)list
1 2 3 4 5 6 7 8
q)@[list; 0; neg]         / negate element 0
-1 2 3 4 5 6 7 8
q)list                    / list remains unmodified
1 2 3 4 5 6 7 8
q)@[list; 1 3 4; {x * x}] / square elements 1, 3, and 4
1 4 3 16 25 6 7 8
q)
</pre>



<p>The diagram below illustrates the last example above:</p>

<p><center><br />
<span class="full-image-block ssNonEditable" style='margin-top: -1em'><span><img width='95%' src="http://www.kdbfaq.com/storage/post-images/functional_at.jpg?__SQUARESPACE_CACHEVERSION=1313955294889" alt=""/></span></span>
</center></p>

<p>Because the new container has the same type and shape as the original, <span class="inline">function</span> must return the same type as its argument, unless the container is a mixed list (i.e., type 0):</p>



<pre class='pre'>
q)@[list; 4 5 6 7; {x div 2}] / list is an int list
1 2 3 4 2 3 3 4
q)@[list; 4 5 6 7; {x % 2}]   / but % returns float
'type
q)mixed_list: 1 2, `3`4
q)type mixed_list
0h
q)@[mixed_list; 0 3; string] / anything goes with type 0
,&quot;1&quot;
2
`3
,&quot;4&quot;
q)
</pre>



<p>Next, we'll consider the second case listed at the top of this faq.  When <span class="inline">function</span> is dyadic and a fourth argument is supplied, <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> behaves like the following function:</p>

<script src="https://gist.github.com/1920833.js?file=apply_dyadic.q"></script>

<p>The basic idea is still the same, i.e., to transform selected elements while leaving the rest of the container intact.  The difference is that, instead of <span class="inline">function</span> being modified by <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/each'><span class="inline">each</span></a>, it is modified by <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/Apostrophe'><span class="inline">'(each-both)</span></a> (also see this <a href='http://www.kdbfaq.com/kdb-faq/how-does-each-both-aka-multivalent-each-work.html'>faq on each-both and multivalent each</a>), so that the selected elements of <span class="inline">container</span> are paired up with the corresponding elements from <span class="inline">second_args</span>:</p>



<pre class='pre'>
q)@[list; 1 3 5 7; +; 10 20 30 40]
1 12 3 24 5 36 7 48
q)@[list; (1 3 5 7; 0 2 4 6); *; 2 -2]
-2 4 -6 8 -10 12 -14 16
q)
</pre>



<p>One function often used with 4-argument <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a>, is <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a>.  We can replace selected elements with a certain value (or values) as follows:</p>



<pre class='pre'>
q)list: 1 + til 8
q)@[list; 1 3 5 7; :; 47]
1 47 3 47 5 47 7 47
q)@[list; 1 3 5 7; :; 10 20 30 40]
1 10 3 20 5 30 7 40
q)
</pre>



<p>It might appear that the above example exposes a flaw in our model, <span class="inline">apply_dyadic</span>, of <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a>.  However, recall that, <a href='http://www.kdbfaq.com/kdb-faq/when-does-amend-not-modify-its-first-argument.html'><span class="inline">when modified by an adverb, : (amend)</span> does not modify its first argument:</a></p>



<pre class='pre'>
q):'[list 1 2 3; 20 30 40]
20 30 40                     / :' returns its 2nd argument
q)list                       / without modifying its 1st
1 2 3 4 5 6 7 8
q)
</pre>



<p>Where our models do break down is when, as alluded to earlier, the first argument is the name of global variable referring to a container, rather than the value of a container.  In that case, the mechanics of the operation are the same, but original container is modified, and the return value is the name:</p>



<pre class='pre'>
q)list: 1 + til 8
q)@[`list; 0; neg]
`list
q)list
-1 2 3 4 5 6 7 8
q)
</pre>



<p>This behavior is handy for writing functions of your own that work in both scenarios - either creating a new value or modifying one in place - like the following:</p>

<script src="https://gist.github.com/1920838.js?file=negate_first_item.q"></script>

<p><hr/></p>

<p>We can also use <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@</span></a> to apply a function to selected entries in a dictionary:</p>



<pre class='pre'>
q)dictionary: `a`b`c`d ! `1`2, 3 4
q)dictionary
a| `1
b| `2
c| 3
d| 4
q)@[dictionary; `a`b; {&quot;I&quot;$ string x}]
a| 1
b| 2
c| 3
d| 4
q)
</pre>



<p>Tables can be transformed as well.  Consider the following table:</p>



<pre class='pre'>
q)t: ([] col1: `foo`bar`baz; col2: 5 10 15f)
q)t
col1 col2
---------
foo  5   
bar  10  
baz  15  
q)
</pre>



<p>Recall that each row of a table is a dictionary:</p>



<pre class='pre'>
q)t 0
col1| `foo
col2| 5f
q)
</pre>



<p>Thus, we can use <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> to accomplish an <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/update'><span class="inline">update</span></a> in the following manner:</p>



<pre class='pre'>
q)update col2 - 4 from t where i &gt; 0
col1 col2
---------
foo  5   
bar  6  
baz  11  
q)@[t; 1 2; {[row] row[`col2] -: 4; row}]
col1 col2
---------
foo  5   
bar  6  
baz  11  
q)
</pre>



<p>We could also obtain the previous result using nested calls to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a>:</p>



<pre class='pre'>
q)@[t; 1 2; @[; `col2; -[; 4]]]
col1 col2 
---------
foo  5 
bar  6
baz  11
q)
</pre>



<p>Since we can index tables using column names, we can double all of the entries in <span class="inline">col2</span> as follows:</p>



<pre class='pre'>
q)@[t; `col2; 2*]
col1 col2
---------
foo  10  
bar  20  
baz  30  
q)
</pre>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12582965.xml</wfw:commentRss></item><item><title>How do I use the functional form of . (dot) apply?</title><category>.</category><category>Functions</category><category>apply</category><category>dot</category><category>functional form</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 27 Feb 2012 03:20:00 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-form-of-dot-apply.html</link><guid isPermaLink="false">817816:9603847:12584888</guid><description><![CDATA[<p>Short answer:</p>



<pre class='pre'>
1. .[container; indices; function]
2. .[container; indices; function; second_args]
</pre>



<p>(Note that there is another overload for <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a> with three arguments, called protected execution, which is invoked when the first argument to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a> is a function or projection; protected execution is discussed in another <a href='http://www.kdbfaq.com/kdb-faq/how-does-protected-execution-or-exception-handling-work-in-q.html'>faq</a>.)</p>

<p><hr/></p>

<p>In the 3-argument case, <span class="inline">q</span> applies <span class="inline">function</span> to those elements of <span class="inline">container</span> specified by <span class="inline">indices</span>, leaving the rest of <span class="inline">container</span> alone.</p>

<p>The behavior of <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> is very similar to that of <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> (which is described in <a href='http://www.kdbfaq.com/kdb-faq/how-do-i-use-the-functional-form-of-at-apply.html'>another faq</a>).  The only difference between <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> and <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> is that the indices, in the case of <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a>, are applied at depth along the dimensions of the container.  The following code behaves like <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> for a two-dimensional container:</p>

<script src="https://gist.github.com/1920851.js?file=apply_2d.q"></script>

<p>To explore the different treatment of the <span class="inline">indices</span> argument between <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (apply)</span></a> and <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a>, we'll consider the simplest, multi-dimensional container: a two-dimensional list, aka a matrix.</p>



<pre class='pre'>
q)matrix: 0N 4 # til 16
q)matrix
0  1  2  3 
4  5  6  7 
8  9  10 11
12 13 14 15
q)
</pre>



<p>We can use simple indexing of <span class="inline">matrix</span> with both <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">@ (index)</span></a> and <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (index)</span></a> to illustrate the difference:</p>



<pre class='pre'>
q)@[matrix; 0]           // fetch row 0
0 1 2 3
q)@[matrix; 0 0]         // fetch matrix[0;0] fails.  why?
0 1 2 3                  // @ cannot index more
0 1 2 3                  // than one dimension
q)
q).[matrix; 0 0]         // dot indexes &quot;at depth&quot;
0
</pre>



<p>Now let's apply a function to selected elements from <span class="inline">matrix</span> using <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a>:</p>



<pre class='pre'>
q).[matrix; (0; ::); 100+]
100 101 102 103
4   5   6   7  
8   9   10  11 
12  13  14  15 
q).[matrix; 0 0; 100+]
100 1  2  3 
4   5  6  7 
8   9  10 11
12  13 14 15
q).[matrix; (::; 0); 100+]
100 1  2  3 
104 5  6  7 
108 9  10 11
112 13 14 15
q)
</pre>



<p>Notice that we used <a class='offsite-link-inline'href='http://code.kx.com/trac/wiki/Reference/ColonColon'><span class="inline">::</span></a> in order to elide a dimension from the indices.</p>

<p>We can also use <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> with dictionaries of lists:</p>



<pre class='pre'>
q)dict: `a`b ! (1 2 3; 4 5 6)
q).[dict; (`a; 0); 50*]
a| 50 2 3
b| 4  5 6
q).[dict; (::; 1); 50*]
a| 1 100 3
b| 4 250 6
q)
</pre>



<p>The general case of applying a function at depth via functional <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> is not implemented for tables:</p>



<pre class='pre'>
q)t: ([] a: `foo`bar; b: 5 10f)
q).[t; (0; `b); %[; 5]]
'nyi
q).[t; (`b; 0); %[; 5]]
'nyi
q)
</pre>



<p>The <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">.</span></a> form of apply has another trick up its sleeve: the empty list index.  When the second parameter to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> is <span class="inline">()</span>, the entire container is passed to <span class="inline">function</span> in a single invocation, as the following example demonstrates:</p>



<pre class='pre'>
q).[matrix; (); 0N!]
(0 1 2 3;4 25 36 7;8 81 100 11;12 13 14 15)
0  1  2   3 
4  25 36  7 
8  81 100 11
12 13 14  15
q)
</pre>



<p>When using <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DotSymbol'><span class="inline">. (apply)</span></a> in this manner, we can return anything from <span class="inline">function</span>; the type and shape do not matter:</p>



<pre class='pre'>
q).[matrix; (); {&quot;hello&quot;}]
&quot;hello&quot;
q)
</pre>



<p><hr/></p>

<p>Returning to the second case, when <span class="inline">function</span> is dyadic, <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/AtSymbol'><span class="inline">. (apply)</span></a> takes a fourth argument (named <span class="inline">second_args</span> in our example), and each indexed element of <span class="inline">container</span> is paired with the corresponding element of <span class="inline">second_args</span>.  This means that <span class="inline">second_args</span> must conform to <span class="inline">indices</span> (or be an atom).  The following function expresses this behavior:</p>

<script src="https://gist.github.com/1920854.js?file=apply_dyadic.q"></script>

<p>(Also see this <a href='http://www.kdbfaq.com/kdb-faq/how-does-each-both-aka-multivalent-each-work.html'>faq on each-both and multivalent each</a>.)</p>

<p>We can demonstrate how this works by altering the center square of <span class="inline">matrix</span>:</p>



<pre class='pre'>
q).[matrix; (1 2; 1 2); *; (10 20; 100 200)]
0  1   2    3 
4  50  120  7 
8  900 2000 11
12 13  14   15
q)
</pre>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12584888.xml</wfw:commentRss></item><item><title>How does each-both (aka multivalent each) work?</title><category>Operators</category><category>apply function for each table row</category><category>each both</category><category>multivalent each</category><dc:creator>kdbfaq</dc:creator><pubDate>Sun, 26 Feb 2012 21:34:00 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-does-each-both-aka-multivalent-each-work.html</link><guid isPermaLink="false">817816:9603847:14777066</guid><description><![CDATA[<p>Short answer: It takes a function of N operands and creates a new function that applies the original to each set of corresponding elements from N same-length vectors.</p>

<p><hr /></p>

<p>We can categorize the ways in which <span class="inline">q</span> handles vectors into the following three groups:</p>

<p>1) Treat the vector as a single entity.<br />
2) Perform an operation on each element of a vector.<br />
3) Perform an operation on each set of corresponding elements from <strong>multiple</strong> vectors of the <strong>same length</strong>.</p>

<p>We use <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> to ask <span class="inline">q</span> to apply a function in the third manner.</p>

<p>Let's review a few examples to distinguish the three forms of vector handling described above.  Consider the <a href='http://code.kx.com/trac/wiki/Reference/Comma' class='offsite-link-inline'><span class="inline">, (join)</span></a> operator, which takes two arguments and concatenates them.  When used by itself, <a href='http://code.kx.com/trac/wiki/Reference/Comma' class='offsite-link-inline'><span class="inline">, (join)</span></a> treats a vector as a single entity:</p>



<pre class='pre'>
q)1 , 2
1 2
q)1 2 3 , 10
1 2 3 10
q)1 , 10 20 30
1 10 20 30
q)1 2 , 10 20 30
1 2 10 20 30
q)
</pre>



<p>Notice that the lengths of the two vectors to be joined doesn't matter; in fact, they don't have to be vectors.</p>

<p>Next, as an example of applying the same operation to each element of a vector, we can use <a href='http://code.kx.com/wiki/Reference/BackSlashColon' class='offsite-link-inline'><span class="inline">\: (each-left)</span></a> to append the letter "e" to each element in a vector of strings:</p>



<pre class='pre'>
q)(&quot;car&quot;; &quot;far&quot;; &quot;mar&quot;) ,\: &quot;e&quot;
&quot;care&quot;
&quot;fare&quot;
&quot;mare&quot;
q)
</pre>



<p>Lastly, we'll use <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> to join corresponding elements from two vectors of the same length (like zip from <a href='http://docs.python.org/library/functions.html#zip' class='offsite-link-inline'>Python</a> or <a class='offsite-link-inline' href='http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#g:19'>Haskell</a>):</p>



<pre class='pre'>
q)1 2 3 ,' 10 20 30
1 10
2 20
3 30
q)
</pre>



<p>As an aside, the use of <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> is not needed for many built-in functions in <span class="inline">q</span>, because those functions (sometimes referred to as atomic functions in kx documentation) automatically assume that this is the desired behavior when presented with same-length vectors as arguments.  The <span class="inline">+</span> operator is a good example:</p>



<pre class='pre'>
q)1 2 3 + 10 20 30
11 22 33
q)
</pre>



<p>Even a user defined function, if that function's body is exclusively made up of applications of atomic functions, does not require the use of <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> to display this behavior:</p>



<pre class='pre'>
q)atomic: {[x; y] (x * x) + y * y}
q)atomic'[1 2 3; 10 20 30]
101 404 909
q)atomic[1 2 3; 10 20 30]  // ' not required
101 404 909
q){[x; y] atomic[x; y]}[1 2 3; 10 20 30]
101 404 909
q)
</pre>



<p>The last example shows that such user defined atomic functions are truly atomic in the eyes of <span class="inline">q</span>.</p>

<p>The following code simulates the behavior of <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> - on functions of two arguments - by creating a new function (that acts on vectors) from the function passed as an argument:</p>

<script src="https://gist.github.com/1881349.js?file=each_both.q"></script>

<p>However, <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each-both)</span></a> doesn't stop at two lists, which is why it is sometimes called multivalent each.  Suppose we need to generate a bunch of <a href='http://www.w3schools.com/tags/tag_a.asp' class='offsite-link-inline'>html hyperlinks</a> for a web page we are creating on-the-fly (perhaps in a <a class='offsite-link-inline' href='http://code.kx.com/wiki/Reference/dotzdotpp'>custom http <span class="caps">POST </span>handler</a>).  Each link needs to have its own styling, so we want to add a distinct <a href='http://www.w3schools.com/tags/att_standard_class.asp' class='offsite-link-inline'>class attribute</a> to each anchor tag.</p>

<p>The <a href='http://code.kx.com/wiki/Doth' class='offsite-link-inline'>.h namespace</a> includes numerous functions for generating <span class="caps">HTML. </span> The one we need is the <a href='http://code.kx.com/wiki/Doth' class='offsite-link-inline'>.h.htac (html tag with attributes and closing tag)</a> function:</p>



<pre class='pre'>
q).h.htac[`a; `class`href ! (&quot;myclass&quot;; &quot;kdbfaq.com&quot;); &quot;kdbfaq&quot;]
&quot;&lt;a class=\&quot;myclass\&quot; href=\&quot;kdbfaq.com\&quot;&gt;kdbfaq&lt;/a&gt;&quot;
q)
</pre>



<p>Let's wrap <a href='http://code.kx.com/wiki/Doth' class='offsite-link-inline'>.h.htac (html tag with attributes and closing tag)</a> up in a function to create a styled link:</p>

<script src="https://gist.github.com/1881326.js?file=styled_link.q"></script>

<p>We'll store the information we need to generate the links in a table:</p>

<script src="https://gist.github.com/1881310.js?file=links.q"></script>



<pre class='pre'>
q)links
name        url                    class
----------------------------------------
&quot;kx&quot;        &quot;http://kx.com&quot;        &quot;c1&quot; 
&quot;Wikipedia&quot; &quot;http://wikipedia.com&quot; &quot;c2&quot; 
&quot;kdbfaq&quot;    &quot;http://kdbfaq.com&quot;    &quot;c3&quot;
q)
</pre>



<p>Now we can use <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (multivalent each)</span></a> to generate all the links easily:</p>



<pre class='pre'>
q)styled_link'[links `name; links `url; links `class]
&quot;&lt;a class=\&quot;c1\&quot; href=\&quot;http://kx.com\&quot;&gt;kx&lt;/a&gt;&quot;
&quot;&lt;a class=\&quot;c2\&quot; href=\&quot;http://wikipedia.com\&quot;&gt;Wikipedia&lt;/a&gt;&quot;
&quot;&lt;a class=\&quot;c3\&quot; href=\&quot;http://kdbfaq.com\&quot;&gt;kdbfaq&lt;/a&gt;&quot;
q)
</pre>



<p>Or, alternately, we can combine <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (multivalent each)</span></a> with <a href='http://code.kx.com/trac/wiki/Reference/DotSymbol' class='offsite-link-inline'><span class="inline">. (apply)</span></a> for a shorter, more general approach to applying a function to each row in a table:</p>



<pre class='pre'>
q)styled_link .' flip value flip links
&quot;&lt;a class=\&quot;c1\&quot; href=\&quot;http://kx.com\&quot;&gt;kx&lt;/a&gt;&quot;
&quot;&lt;a class=\&quot;c2\&quot; href=\&quot;http://wikipedia.com\&quot;&gt;Wikipedia&lt;/a&gt;&quot;
&quot;&lt;a class=\&quot;c3\&quot; href=\&quot;http://kdbfaq.com\&quot;&gt;kdbfaq&lt;/a&gt;&quot;
q)           
</pre>



<p>On more wrinkle: sometimes <a href='http://code.kx.com/trac/wiki/Reference/Apostrophe' class='offsite-link-inline'><span class="inline">' (each)</span></a> is used where <a href='http://code.kx.com/trac/wiki/Reference/BackSlashColon' class='offsite-link-inline'><span class="inline">\: (each-left)</span></a> or <a href='http://code.kx.com/trac/wiki/Reference/SlashColon' class='offsite-link-inline'><span class="inline">/: (each-right)</span></a> would be more explicit.  For instance, our earlier example in which we appended the letter <span class="inline">"e"</span> to each element of a list of strings could have been written as follows:</p>



<pre class='pre'>
q)(&quot;car&quot;; &quot;far&quot;; &quot;mar&quot;) ,' &quot;e&quot;
&quot;care&quot;
&quot;fare&quot;
&quot;mare&quot;
q)
</pre>



<p>We find the original, more explicit form, quicker and easier to read.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-14777066.xml</wfw:commentRss></item><item><title>How can I capture STDOUT, STDERR and the exit status of a system command invoked from q?</title><category>'os</category><category>2&gt;&amp;1</category><category>Tricks</category><category>amend</category><category>shell command</category><category>stderr</category><category>stderr redirection</category><category>stdout</category><category>try-catch</category><category>unix shell</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 23 Jan 2012 01:26:15 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-can-i-capture-stdout-stderr-and-the-exit-status-of-a-sys.html</link><guid isPermaLink="false">817816:9603847:12783271</guid><description><![CDATA[<p>Short answer: <span class="inline">2&gt;&amp;1</span> (i.e., redirect <span class="inline"><span class="caps">STDERR</span></span> to <span class="inline"><span class="caps">STDOUT</span></span>), <span class="inline">echo $?</span>, and <strong>add parentheses</strong>.</p>

<p>Note: This applies to bash, and has not been tested in csh, ksh, etc.</p>

<p><hr/></p>

<p>We can invoke arbitrary external programs from <span class="inline">q</span> using the <a class='offsite-link-inline' href='http://code.kx.com/wiki/Reference/system'>system</a> command.  For example:</p>



<pre class='pre'>
q)system &quot;echo Hello, world!&quot;
&quot;Hello, world!&quot;
q)
</pre>



<p>External programs often signal errors by returning a non-zero exit code, which is stored in the shell variable <span class="inline">?</span>:</p>



<pre class='pre'>
$ ls nonexistent_file
ls: nonexistent_file: No such file or directory
$ echo $?
1
$ foo
-bash: foo: command not found
$ echo $?
127
</pre>



<p>When an external program called from <a class='offsite-link-inline' href='http://code.kx.com/wiki/Reference/system'>system</a> in <span class="inline">q</span> runs into a situation like this, <span class="inline">q</span> detects the non-zero exit code from the child process and raises a signal, <span class="inline">'os</span>:</p>



<pre class='pre'>
q)system &quot;ls nonexistent_file&quot;
ls: nonexistent_file: No such file or directory
'os
q)
</pre>



<p>When trying out ideas at the console as in the above example, the full details of the error are available on the screen.  Getting those error details programmatically is a bit trickier, however.  Consider the following function, in which we use <a href="http://www.kdbfaq.com/kdb-faq/how-does-protected-execution-or-exception-handling-work-in-q.html">protected execution</a> to invoke an error handler when the <span class="inline">'os</span> signal is raised:</p>



<pre class='pre'>
use_protected_execution: {[]
    : @[system;
        &quot;ls nonexistent_file&quot;;
        {[error_info] -1 &quot;error is &quot;, error_info;}];
    }
</pre>



<p>The error handler in <span class="inline">use_protected_execution</span> knows only that an operating system error occurred.  None of the error details are available within the code:</p>



<pre class='pre'>
q)use_protected_execution[]
ls: nonexistent_file: No such file or directory  // invisible
error is os
q)
</pre>



<p>We can improve the situation somewhat by appending <span class="inline">"; echo $?"</span> to the command:</p>



<pre class='pre'>
q)result: system &quot;ls nonexistent_file; echo $?&quot;
q)result
,&quot;1&quot;    // actually a list of strings
q)
</pre>



<p>This enables us to distinguish error codes as follows:</p>



<pre class='pre'>
distinguish_error_codes: {[]
    result: system &quot;ls nonexistent_file; echo $?&quot;;
    exit_code: &quot;I&quot; $ last result;
    $[0   = exit_code;
        ; // everything's alright
      1   = exit_code;
        ; // minor problem
      2   = exit_code;
        ; // major problem
      127 = exit_code;
        ; // command not found
    / else
        // unhandled exit code
      ]}
</pre>



<p>What we really want, though, is to capture the output sent by the failed command to <span class="inline"><span class="caps">STDERR</span></span>.  You might expect <a href='http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html' class='offsite-link-inline'>the usual shell redirection syntax</a> to do the job:</p>



<pre class='pre'>
q)result: system &quot;ls nonexistent_file 2&gt;&amp;1; echo $?&quot;
ls: nonexistent_file: No such file or directory
q)result
,&quot;1&quot;
q)
</pre>



<p>No such luck.  The trick is to put parentheses around the whole thing:</p>



<pre class='pre'>
q)result: system &quot;(ls nonexistent_file 2&gt;&amp;1; echo $?)&quot;
q)result
&quot;ls: nonexistent_file: No such file or directory&quot;
,&quot;1&quot;
q)
</pre>



<p>We can wrap all this up in a handy function that, instead of raising <span class="inline">os</span>, raises the descriptive message output to <span class="inline"><span class="caps">STDERR</span></span> by the child process:</p>



<pre class='pre'>
call_external: {[command]
    result: system &quot;(&quot;, command, &quot; 2&gt;&amp;1; echo $?)&quot;;
    exit_code: &quot;I&quot; $ last result;
    if [0 &lt; exit_code;
        ' raze -1 _ result];
    -1 _ result}
</pre>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12783271.xml</wfw:commentRss></item><item><title>Why can't I index some elements of a dictionary?</title><category>Syntax</category><category>broken dictionary key lookup</category><category>dictionary indexing</category><category>dictionary key</category><category>dictionary null type</category><dc:creator>kdbfaq</dc:creator><pubDate>Sun, 23 Oct 2011 21:57:56 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/why-cant-i-index-some-elements-of-a-dictionary.html</link><guid isPermaLink="false">817816:9603847:12644101</guid><description><![CDATA[<p>Short answer: Check that the keys of your dictionary are uniformly atoms or lists, not both.</p>

<p><hr/></p>

<p>To experiment, let's construct two dictionaries, one with atomic keys and one with list keys.</p>



<pre class='pre'>
q)dict1: `keya`keyb`keyc ! 10 20 30
q)dict1                // dictionary with atomic keys
keya| 10
keyb| 20
keyc| 30
q)dict2: (`keya1`keya2; `keyb1`keyb2; `keyc1`keyc2) ! 1 2 3
q)dict2                // dictionary with list keys
keya1 keya2| 1
keyb1 keyb2| 2
keyc1 keyc2| 3
q)dict1[`keya]         // index by atom key
10
q)dict2[`keya1`keya2]  // index by list key
1
q)
</pre>



<p>Note how <span class="inline">dict1</span> contains a keys made of exclusively of atoms, and <span class="inline">dict2</span> contains keys that are lists.  </p>

<p>Now let's consider a dictionary whose keys are both atoms and lists:</p>



<pre class='pre'>
q)dict3: (`keya1; `keyb1`keyb2; `keyc1`keyc2) ! 1 2 3
q)key dict3
`keya1                // The first key is an atomic symbol,
`keyb1`keyb2          // while the rest of the keys are
`keyc1`keyc2          // lists of symbols.
q)dict3[`keya1]       // The first key indexes fine,
1
q)dict3[`keyb1`keyb2] // but the remaining keys are broken;
0N 0N
q)dict3[`keyc1`keyc2] // they are treated as multiple keys.
0N 0N
q)
</pre>



<p>Even though the keys are present they cannot be found by a dictionary lookup.  Reverse lookup does work:</p>



<pre class='pre'>
q)dict3
`keya1      | 1    // ok
`keyb1`keyb2| 2    // broken
`keyc1`keyc2| 3    // broken
q)dict3 ? 2
`keyb1`keyb2
q)dict3 ? 3
`keyc1`keyc2
q)
</pre>



<p>Analogous behavior can be observed when searching a list that contains both atoms and lists:</p>



<pre class='pre'>
q)list: key dict3
q)list ? `keya1
0
q)list ? `keyb1`keyb2
3 3
q)
</pre>



<p>Always remember that a dictionary lookup is essentially the following:</p>



<pre class='pre'>
q)lookup: {[dict; thekey] value[dict] @ key[dict] ? thekey}
q)
</pre>



<p>Sometimes types in <span class="inline">q</span> behave differently depending on the data contained within.  Take a look at <a href="http://www.kdbfaq.com/kdb-faq/why-does-the-type-of-null-returned-by-a-failed-dictionary-ke.html">this related faq</a> to read more.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12644101.xml</wfw:commentRss></item><item><title>Why does the type of null returned by a failed dictionary key lookup vary?</title><category>Syntax</category><category>dictionary</category><category>key type</category><category>null type</category><dc:creator>kdbfaq</dc:creator><pubDate>Sun, 23 Oct 2011 21:57:25 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/why-does-the-type-of-null-returned-by-a-failed-dictionary-ke.html</link><guid isPermaLink="false">817816:9603847:11149658</guid><description><![CDATA[<p>Short answer:  A failed dictionary search returns the null corresponding to the first dictionary entry's value.</p>

<p><hr/></p>

<p>Let's test with the following two dictionaries, <span class="inline">sfdict</span> and <span class="inline">fsdict</span>:</p>



<pre class='pre'>
q)sfdict: `symbol`float ! (`abc; 123.4)  // type sym is first
q)fsdict: `float`symbol ! (123.4; `abc)  // type float is first
q)sfdict
symbol| `abc
float | 123.4
q)fsdict
float | 123.4
symbol| `abc
q)
</pre>



<p>Note that while both dictionaries contain the same key-value pairs, because dictionaries are an <strong>ordered</strong> list of key value pairs, the above two dictionaries do not match.</p>



<pre class='pre'>
q)sfdict = fsdict
symbol| 1
float | 1
q)sfdict ~ fsdict
0b
q)
</pre>



<p>A dictionary search returns a null value when the key sought is not found:</p>



<pre class='pre'>
q)null sfdict[`badkey]
1b
q)null fsdict[`badkey]
1b
q)
</pre>



<p>Getting a null back from a failed lookup is expected.  On the other hand, many are surprised to find that the two nulls returned for the above two lookups differ:</p>



<pre class='pre'>
q)sfdict[`badkey] ~ fsdict[`badkey]
0b
q)sfdict[`badkey]
`                    // null symbol
q)fsdict[`badkey]
0n                   // null float
q)
</pre>



<p>The types of the returned nulls are different according to the types of the first values in <span class="inline">sfdict</span> and <span class="inline">fsdict</span>.  This is the same behavior observed when indexing a mixed list with an out-of-range index:</p>



<pre class='pre'>
q)(`a; `b; 1f; 2f)[5]
`
q)(1f; 2f; `a; `b)[5]
0n
q)
</pre>



<p>There's a similar "first element wins" behavior with the atomicity of dictionary keys.  see this faq on <a href="http://www.kdbfaq.com/kdb-faq/why-cant-i-index-some-elements-of-a-dictionary.html"> dictionary indexing</a> to learn more.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-11149658.xml</wfw:commentRss></item><item><title>When does : (amend) not modify its first argument?</title><category>:</category><category>Operators</category><category>amend</category><category>colon</category><category>l-value</category><dc:creator>kdbfaq</dc:creator><pubDate>Mon, 22 Aug 2011 02:06:57 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/when-does-amend-not-modify-its-first-argument.html</link><guid isPermaLink="false">817816:9603847:12585799</guid><description><![CDATA[<p>Short answer: When 1) projected or 2) modified by an adverb, e.g., :/: :\: or :'</p>

<p><hr/></p>

<p>Normally, the <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> function is used to assign a value to a name:</p>



<pre class='pre'>
q)foo: 47
q)foo
47
q)
</pre>



<p>Like other built-in functions that take two arguments, <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> can be called using either infix notation (as above) or function call notation:</p>



<pre class='pre'>
q):[foo; 747]
q)foo
747
q)
</pre>



<p>Note that <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> displays its special semantics (which it shares with assignments in all strict languages) of not evaluating its first argument when that argument is simply a name, regardless of whether <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> is invoked infix or functionally.</p>



<pre class='pre'>
q)delete bar from `.    / make sure bar is not defined
q):[bar; 42]
q)bar
42
q)
</pre>



<p>On the other hand, <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> does evaluate its first argument when that argument is an expression, but <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> still produces <a class='offsite-link-inline' href='http://en.wikipedia.org/wiki/Value_(computer_science)'>l-values</a> when it does so:</p>



<pre class='pre'>
q)list: 0 1 2 3
q)list[0]: 47
q)list
47 1 2 3
q):[list 1 2 3; 10 20 30]
q)list
47 10 20 30
q)
</pre>



<p>Based on the previous examples, you might be tempted create a projection from <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> and a left-hand side, but it turns out you can't:</p>



<pre class='pre'>
q):[foo]
'foo
q)
</pre>



<p>It is possible to close the first argument to <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a>, but the resulting projection is no longer an assignment; it is an identity function:</p>



<pre class='pre'>
q)foo: 42
q)(:[foo])[47]
47
q)foo
42
q)
</pre>



<p>In fact, the value attached to the first argument of <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> is irrelevant:</p>



<pre class='pre'>
q)(:[`xyzzy])[47]
47
q)
</pre>



<p>Closing the second argument will cause <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> to return the same value always:</p>



<pre class='pre'>
q)f: :[; 3]     / bind the 2nd argument
q)f 18          / no matter what we pass
3
q)f &quot;hello&quot;     / f will always return 3
3
q)
</pre>



<p>The other case when <a class='offsite-link-inline' href='https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/Colon'><span class="inline">: (amend)</span></a> does not perform assignment is when it is modified by an adverb:</p>



<pre class='pre'>
q)list1: 0 1 2 3
q)list2: 4 5 6 7
q)(list1; list2) :\: 10 20 30 40   / we get the rhs
10 20 30 40                        / once for each list
10 20 30 40
q)list1                            / neither list
0 1 2 3
q)list2                            / has been modified
4 5 6 7
q)list2 :/: 0 1 2 3
0 1 2 3
q)list1[0 1 2 3] :' 10 20 30 40
10 20 30 40
q)
</pre>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12585799.xml</wfw:commentRss></item><item><title>What is q's equivalent to sql's ORDER BY?</title><category>ORDER BY ASC</category><category>ORDER BY DESC</category><category>Tables</category><category>asc</category><category>desc</category><category>order by</category><category>sort</category><category>xasc</category><category>xdesc</category><dc:creator>kdbfaq</dc:creator><pubDate>Sun, 07 Aug 2011 18:29:03 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/what-is-qs-equivalent-to-sqls-order-by.html</link><guid isPermaLink="false">817816:9603847:12425392</guid><description><![CDATA[<p><a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xasc'><span class="inline">xasc</span></a> and <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xdesc'><span class="inline">xdesc</span></a>.  Consider the following table:</p>

<blockquote class="code"><p>q)table: ([] x: 10 ? "abc"; y: 10 ? til 10)<br />
q)table<br />
x y<br />
---<br />
a 7<br />
a 7<br />
b 1<br />
b 9<br />
a 1<br />
a 0<br />
c 8<br />
b 8<br />
c 3<br />
c 1<br />
q)</p></blockquote>

<p>To sort by column <span class="inline">x</span>, instead of <span class="inline">"ORDER BY x"</span>, we write <span class="inline">`x xasc table</span>:</p>

<blockquote class="code"><p>q)`x xasc table     // sort by column x<br />
x y<br />
---<br />
a 7<br />
a 7<br />
a 1<br />
a 0<br />
b 1<br />
b 9<br />
b 8<br />
c 8<br />
c 3<br />
c 1<br />
q)</p></blockquote>

<p>The application of <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xdesc'><span class="inline">xdesc</span></a> is similar.</p>

<p>In addition, to sort by multiple columns, instead of <span class="inline">"ORDER BY y, x"</span> or <span class="inline">"ORDER BY y, x <span class="caps">DESC</span>"</span>, we pass the list of column names as the left argument to <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xasc'><span class="inline">xasc</span></a> or <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xdesc'><span class="inline">xdesc</span></a>, respectively.  For example,</p>

<blockquote class="code"><p>q)`y`x xdesc select from table where y &gt; 5<br />
x y<br />
---<br />
b 9<br />
c 8<br />
b 8<br />
a 7<br />
a 7<br />
q)</p></blockquote>


<p>Don't confuse <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xasc'><span class="inline">xasc</span></a> and <a class='offsite-link-inline' href='http://anonymous:anonymous@code.kx.com/trac/wiki/Reference/xdesc'><span class="inline">xdesc</span></a> with <a href="https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/asc" title="code.kx.com" class="offsite-link-inline">asc</a> and <a href="https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/desc" title="code.kx.com" class="offsite-link-inline">desc</a>, which operate on a vector instead of a table.   Read more about sorting vectors in this <a href="http://www.kdbfaq.com/kdb-faq/how-do-i-sort.html">related faq</a>.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12425392.xml</wfw:commentRss></item><item><title>How do I extract hours, minutes, or seconds from a time?</title><category>.z.T</category><category>General</category><category>milliseconds</category><category>mod</category><category>ms</category><category>time</category><dc:creator>kdbfaq</dc:creator><pubDate>Sat, 30 Jul 2011 21:35:38 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-extract-hours-minutes-or-seconds-from-a-time.html</link><guid isPermaLink="false">817816:9603847:12346808</guid><description><![CDATA[<p>Short answer: Times are integers (think milliseconds).</p>



<pre class='pre'>
q)(`hh`mm`ss $ .z.T), `int $ .z.T mod 1000
16 49 2 233
q)
</pre>



<p><hr/></p>

<p>You can extract the hours, minutes, and seconds from a time by passing <span class="inline">`hh, `mm, and `ss</span>, respectively, as left arguments to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DollarSign'><span class="inline">$ (cast)</span></a>: </p>



<pre class='pre'>
q)now: .z.T
q)now
16:49:02.233
q)`hh $ now
16
q)`mm $ now
49
q)`ss $ now
2
q)`hh`mm`ss $ now
16 49 2
q)
</pre>



<p>Getting the milliseconds from a time is slightly less obvious.  Times (type -19) are represented internally by <span class="inline">q</span> as 32-bit integers; typically the value counts the number of milliseconds since midnight, but it can also represent a span of time.  We can cast freely back and forth between the two types and the values are preserved:</p>



<pre class='pre'>
q)`time $ 0
00:00:00.000
q)`int $ 00:00:00.000
0
q)`time $ 24 * 60 * 60 * 1000
24:00:00.000
q)`int $ 24:00:00.000
86400000
q)`int $ now
60542233
q)`time $ 60542233
16:49:02.233
q)
</pre>



<p>Not only is the internal representation of time simply an integer, we can mix integers and times in integer arithmetic operations, and the result is always a time:</p>



<pre class='pre'>
q)01:00:00.000 + 00:01:00.000
01:01:00.000
q)01:00:00.000 + 60000
01:01:00.000
q)01:00:00.000 * 4
04:00:00.000
q)now - 01:30:20.123
15:18:42.110
q)
</pre>



<p>By using <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/div'><span class="inline">div</span></a> and <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/mod'><span class="inline">mod</span></a>, then, we have an alternative means to calculate the components of a time:</p>



<pre class='pre'>
q)now div 3600000 // milliseconds per hour
00:00:00.016
q)now mod 1000    // just the milliseconds, please
00:00:00.233
q)
</pre>



<p>Although extracting milliseconds from a time while keeping the time type (as in the second example above) is sometimes useful, we normally want to get back these components of a time as integers, so let's cast it:</p>



<pre class='pre'>
q)`int $ now mod 1000
233
q)
</pre>



<p><hr/></p>

<p>By the way, there is a shortcut for getting hours, minutes, and seconds from global variables that hold times: dot notation.</p>



<pre class='pre'>
q)x: .z.T
q)x.hh, x.mm, x.ss
16 49 2
q)
</pre>



<p>However, we rarely use global variables to hold time values.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12346808.xml</wfw:commentRss></item><item><title>How do I parse a date and time?</title><category>.z.D</category><category>.z.Z</category><category>Functions</category><category>parse date</category><category>parse time</category><category>timespan</category><category>timestamp</category><category>unix epoch</category><category>unix time</category><dc:creator>kdbfaq</dc:creator><pubDate>Sun, 24 Jul 2011 23:46:12 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-parse-a-date-and-time.html</link><guid isPermaLink="false">817816:9603847:12252279</guid><description><![CDATA[<p>Short answer: <span class="inline">"D"$</span>, <span class="inline">"T"$</span>, and <span class="inline">"Z"$</span></p>

<p><hr/></p>

<p>In general you can parse strings to some particular type by passing the uppercase form of the corresponding <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/Datatypes'>type character</a> as the left argument to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/DollarSign'><span class="inline">$ (cast)</span></a>.</p>

<p><span class="inline">q</span> can parse dates in <span class="caps">YYYYMMDD, YYYY</span>-MM-DD, or <span class="caps">YYYY.MM.DD </span>format:</p>

<blockquote class="code"><p>q)"D"$ ("20070809"; "2007-08-09"; "2007.08.09")<br />
2007.08.09 2007.08.09 2007.08.09<br />
q)</p></blockquote>

<p>Times must have the form HH:MM:SS.mmm, but you can shorten them:</p>

<blockquote class="code"><p>q)"T"$ ("07:08:09.010"; "07:08:09"; "07:08"; "07")<br />
07:08:09.010 07:08:09.000 07:08:00.000 07:00:00.000<br />
q)</p></blockquote>

<p>In addition, <span class="inline">"T"$</span> will tolerate a missing zero for hours (and hours only) less than 10:</p>

<blockquote class="code"><p>q)"T"$ "7:08:09"<br />
07:08:09.000<br />
q)</p></blockquote>

<p><span class="inline">"Z"$</span> expects (<a class='offsite-link-inline' href='http://www.w3.org/TR/xmlschema-2/#dateTime'>as in <span class="caps">XML</span></a>) that dates and times are joined with a <span class="inline">T</span>:</p>

<blockquote class="code"><p>q)"Z"$ "2007-08-09T07:08:09.101"<br />
2007.08.09T07:08:09.101<br />
q)</p></blockquote>

<p><span class="inline">"Z"$</span> usually treats the text analogously to <span class="inline">"D"$</span> and <span class="inline">"T"$</span>; that is, the date must be complete, but the time may have its finer points elided:</p>

<blockquote class="code"><p>q)"Z"$ "2007"<br />
0Nz<br />
q)"Z"$ "20070809"<br />
2007.08.09T00:00:00.000<br />
q)</p></blockquote>

<p>Note, however, the <span class="inline">"Z"$</span> - unlike <span class="inline">"T"$</span> - requires that hours less than 10 be prepended with zero:</p>

<blockquote class="code"><p>q)"Z"$ "20070809T7:08:09"<br />
0Nz<br />
q)</p></blockquote>

<p>You can also parse months with <span class="inline">"M"$</span>, minutes with <span class="inline">"U"$</span>, and seconds with <span class="inline">"V"$</span>:</p>

<blockquote class="code"><p>q)"M"$ ("2007-08"; "2007.08"; "200708")<br />
2007.08 2007.08 2007.08m<br />
q)"U"$ "07:08:09.010"<br />
07:08<br />
q)"V"$ "07:08:09.010"<br />
07:08:09<br />
q)</p></blockquote>

<p>Make sure you don't pass any extra text to <span class="inline">"M"$</span>, though:</p>

<blockquote class="code"><p>q)"M"$ "2007.08.01"<br />
2007.01m<br />
q)</p></blockquote>

<p>There are two more type characters for parsing temporal values.  <span class="inline">"N"$</span> and <span class="inline">"P"$</span> are for parsing nanosecond-precise time spans and datetimes, respectively:</p>

<blockquote class="code"><p>q)"N"$ "12D07:08:09.123456789"<br />
12D07:08:09.123456789<br />
q)"P"$ "2007-08-09T07:08:09.123456789"<br />
2007.08.09D07:08:09.123456789<br />
q)</p></blockquote>

<p>You may have discovered that <span class="inline">"N"$</span> can parse floating point numbers, as well, but beware - depending on the range of the input, you might not get what you expect:</p>

<blockquote class="code"><p>q)"N"$ "0.123456789"<br />
0D00:00:00.123456789<br />
q)"N"$ "1.123456789"<br />
0D01:00:00.123456789<br />
q)"N"$ "12.123456789"<br />
0D12:00:00.123456789<br />
q)"N"$ "24.123456789"<br />
1D00:00:00.123456789<br />
q)"N"$ "48.123456789"<br />
2D00:00:00.123456789<br />
q)"N"$ "4800.123456789"<br />
2D00:00:00.123456789</p></blockquote>

<p>Stick with strings that represent durations in the way <span class="inline">q</span> does, and you'll steer clear of surprises.</p>

<p>Lastly, if you find yourself with a text full of times expressed as seconds (and, optionally, fractions thereof) since the <a href='http://en.wikipedia.org/wiki/Unix_time' class='offsite-link-inline'>Unix epoch</a>, "P"$, and "Z"$ can parse them, too:</p>

<blockquote class="code"><p>q)unix_time: first system "date +%s"<br />
q)unix_time<br />
"1311635286"<br />
q)"Z"$ unix_time<br />
2011.07.25T23:08:06.000<br />
q)"P"$ unix_time , ".123456789"<br />
2011.07.25D23:08:06.123456789</p></blockquote>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12252279.xml</wfw:commentRss></item><item><title>How do I get the length of a list?</title><category>Operators</category><category>length</category><category>where clause</category><category>where function</category><dc:creator>kdbfaq</dc:creator><pubDate>Tue, 19 Jul 2011 02:02:41 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-get-the-length-of-a-list.html</link><guid isPermaLink="false">817816:9603847:12157396</guid><description><![CDATA[<p>Short answer: </p>

<p><span class="inline">count list</span><br />
<span class="indent">or</span><br />
<span class="inline">count each column_name</span><br />
<span class="indent">to get the length of a list-valued field in a query.</span></p>

<p><hr/></p>

<p>The length of any list can be found using the <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a> function; the only complication occurs with certain applications of <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a> in queries.  We'll illustrate with a table of simulated trade data:</p>



<pre class='pre'>
q)trade
time         sym price size
---------------------------
09:30:17.623 glo 26.79 3200
09:30:26.602 ojb 28.17 1600
09:30:33.657 fjc 91.31 5400
09:30:40.884 knb 59.7  2900
09:31:19.256 apl 1.26  7900
..
q)
</pre>



<p>The following query uses <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a> to return the number of rows that satisfy the <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/where'><span class="inline">where</span></a> clause:</p>



<pre class='pre'>
q)exec count i from trade where sym = `aif
6
q)
</pre>



<p>This is usually what you want.</p>

<p>However, suppose we created another table (perhaps to improve the performance of certain queries) that grouped prices for each symbol:</p>



<pre class='pre'>
q)grouped: select price by sym from trade
q)grouped
sym| price                                                   ..
---| --------------------------------------------------------..
acl| 18.1 85.5 86.31 45.65 10.91 31.25 5.49 51.66 1.02 31.82 ..
aif| 44.02 47.74 11.83 14.28 85.11 99.09                     ..
alk| 51.12 16.7 78.71 96.56 26.55 32.09 33.66 30.01 83.24 30...
amg| 59.25 56.18 92.63 46.57 57.25 14.58 69.21 88.25 94.1 28...
aog| 92.59 51.52 96.95 83.2 6.21 59.77 44.19 94.19 3.13 41.94..
..
q)
</pre>



<p>In table <span class="inline">grouped</span>, the <span class="inline">price</span> column is of type list-of-float - note the <strong>uppercase</strong> type letter <span class="inline">F</span>:</p>



<pre class='pre'>
q)meta grouped
c    | t f a
-----| -----
sym  | s    
price| F    
</pre>



<p>It appears that we can retrieve the prices for a given symbol easily enough:</p>



<pre class='pre'>
q)exec price from grouped where sym = `aif
44.02 47.74 11.83 14.28 85.11 99.09
q)
</pre>



<p>Suppose, however, that we want to know how many trades occurred for a particular symbol:</p>



<pre class='pre'>
q)exec count price from grouped where sym = `aif
1    
q)
</pre>



<p>What went wrong?  A <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/where'><span class="inline">where</span></a> function yields a list of row indexes that meet the constraints, and then each projection (i.e., the column names between <span class="inline">exec</span> and <span class="inline">from</span> &mdash; in this case, <span class="inline">price</span>) yields a list of corresponding field values.  Since the number of rows that met our sole constraint is 1, the result of the projection is an untyped list with a single element:</p>



<pre class='pre'>
q)type exec price from grouped where sym = `aif
0h
q)count exec price from grouped where sym = `aif
1
q)
</pre>



<p>Projection results are the arguments to aggregation functions in queries.  In other words, the untyped list in our example is the same as the one passed to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a>.  Since the projection's single element contains the list of prices we want to count, the way out is to combine <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a> with <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/first'><span class="inline">first</span></a>:</p>



<pre class='pre'>
q)exec count first price from grouped where sum = `aif
6
q)
</pre>



<p>Applying the same logic when counting the trades for every symbol, we need to use <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/count'><span class="inline">count</span></a> <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/each'><span class="inline">each</span></a>:</p>



<pre class='pre'>
q)select count price by sym from grouped
sym| price
---| -----
acl| 1    
aif| 1    
alk| 1    
amg| 1    
aog| 1    
..
q)select count each price by sym from grouped
sym| price
---| -----
acl| 14   
aif| 6    
alk| 10   
amg| 12   
aog| 13   
..
q)
</pre>



<p>Constraints in <a class='offsite-link-inline' href='http://code.kx.com/Reference/where'><span class="inline">where</span></a> clauses behave the same as well.  Consider the following <a class='offsite-link-inline' href='http://code.kx.com/Reference/select'><span class="inline">select</span></a> statement:</p>

<blockquote class="code"><p>q)t<br />
x y z        <br />
-------------<br />
a 1 "xyzzy"  <br />
b 2 "grue"   <br />
c 3 "frobozz"<br />
q)select from t where 5 &lt; count z<br />
x y z<br />
-----<br />
q)</p></blockquote>

<p>Newcomers to q often expect the above query to return the rows from <span class="inline">t</span> whose <span class="inline">z</span> column has more than 5 characters (i.e., <span class="inline">c 3 frobozz</span>).  Rather than counting the contents of each <span class="inline">z</span> field, however, <a class='offsite-link-inline' href='http://code.kx.com/Reference/count'><span class="inline">count</span></a> is actually counting the list <span class="inline">t `z</span>:</p>

<blockquote class="code"><p>q)count t `z<br />
3<br />
q)t `z<br />
"xyzzy"<br />
"foobar"<br />
"frobozz"<br />
q)</p></blockquote>

<p>This insight suggests the solution:</p>

<blockquote class="code"><p>q)count each t `z<br />
5 6 7<br />
q)select from t where 5 &lt; count each z<br />
x y z        <br />
-------------<br />
c 3 "frobozz"<br />
q)</p></blockquote>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-12157396.xml</wfw:commentRss></item><item><title>select sum size from a large table unexpectedly returns a negative number. Why?</title><category>Syntax</category><category>cast column</category><category>integer overflow</category><category>negative sum value</category><category>type integer</category><category>type long</category><dc:creator>kdbfaq</dc:creator><pubDate>Fri, 24 Jun 2011 03:47:45 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/select-sum-size-from-a-large-table-unexpectedly-returns-a-ne.html</link><guid isPermaLink="false">817816:9603847:11162651</guid><description><![CDATA[<p>Short answer: cast the column to <span class="inline">long</span> <strong>before</strong> applying <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/sum'><span class="inline">sum</span></a>:</p>



<pre class='pre'>
select sum `long $ size from large_table
</pre>



<p>In many programming languages, including q, anytime you add integers (unless you somehow know for sure that the sum will fit in - roughly - 31 bits) you risk <a href="http://en.wikipedia.org/wiki/Integer_overflow" title="" class="offsite-link-inline">integer overflow</a>.  If you're lucky, the error will be obvious (e.g., you'll get a negative number when you expected a positive one).  Casting the arguments to <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/Reference/sum'><span class="inline">sum</span></a> to <span class="inline">long</span> will give you (almost) 63 bits of breathing room.</p>

<p>If your sum won't fit in 63 bits, you'll need to explore other options:</p>

<ul>
<li>Switch to floats.  Although overflow is still possible, it's rare.  However, you lose some precision.</li>
<li>Use a bignum library such as <a href='http://gmplib.org/' class='offsite-link-inline'>gmp</a>.</li>
<li>Use a language (e.g., <a href='http://haskell.org' class='offsite-link-inline'>haskell</a> or <a href='http://clojure.org' class='offsite-link-inline'>clojure</a>) that has built-in support for arbitrary-precision arithmetic.</li>
</ul>

<p>Lastly, keep in mind that literal values that cannot fit into an <span class="inline">int</span> must be suffixed with <span class="inline">j</span> - even if the context suggests that a <span class="inline">long</span> is expected:</p>



<pre class='pre'>
q)select from meta large_table where c = `id
c | t f a
--| -----
id| j
q)count select from large_table where id = 84066472837652480
'84066472837652480
q)count select from large_table where id = 84066472837652480j
1
q)
</pre>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-11162651.xml</wfw:commentRss></item><item><title>Does the order of field constraints matter in the performance of a select query?</title><category>Performance</category><category>evaluation order</category><category>hdb</category><category>optimal where clause construction</category><category>query optimization</category><category>where clause</category><category>where function</category><dc:creator>kdbfaq</dc:creator><pubDate>Sat, 04 Jun 2011 06:00:06 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/does-the-order-of-field-constraints-matter-in-the-performanc.html</link><guid isPermaLink="false">817816:9603847:10645693</guid><description><![CDATA[<p>Short answer:  Yes, put the most restrictive constraint first.</p>

<p>Although expressions in q are usually evaluated from right to left, there is one exception: the constraints in a <span class="inline">where</span> clause are evaluated from left to right.  Consider the following example:</p>

<blockquote class="code"><p>q)t: ([] x: `a`b`c; y: 1 2 3)<br />
q)select from t where x &lt; `c, y &gt; 1<br />
x y<br />
---<br />
b 2<br />
q)</p></blockquote>

<p>The comma separating <span class="inline">x &lt; `c</span> from <span class="inline">y &gt; 1</span> is not <a href='http://code.kx.com/trac/wiki/Reference/Comma' class='offsite-link-inline'>the join operator</a>; instead, it delimits the constraints of the <span class="inline">where</span> clause.  If you need to use the join operator in a <span class="inline">where</span> clause, use parentheses:</p>

<blockquote class="code"><p>q)select from t where x in (`a, `b), y &gt; 1<br />
x y<br />
---<br />
b 2<br />
q)</p></blockquote>

<p>Each constraint is evaluated in the usual order, i.e., right-to-left:</p>

<blockquote class="code"><p>q)select from t where x &lt; first -1 # `p`c, y &gt; 1<br />
x y<br />
---<br />
b 2<br />
q)</p></blockquote>

<p>Because constraints are evaluated from left to right, putting the most restrictive constraint first will speed up queries on large tables.  On a date partitioned database, for example, the placement of a constraint on the virtual date column will make a marked performance difference:</p>



<pre class='pre'>
select from large_table where date = 2011.02.25, name = `JOE
</pre>



<p>is significantly faster than</p>



<pre class='pre'>
select from large_table where name = `JOE, date = 2011.02.25
</pre>



<p>The latter query will attempt to load the entire contents of table for rows matching name `JOE prior to narrowing the result set down to a single date.  kdb does not provide behind-the-scenes optimization in cases like these.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-10645693.xml</wfw:commentRss></item><item><title>How do I set a breakpoint inside a q function?</title><category>:</category><category>::</category><category>Debugging</category><category>breakpoint</category><category>command line arguments</category><category>resume execution</category><dc:creator>kdbfaq</dc:creator><pubDate>Thu, 02 Jun 2011 05:47:01 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-set-a-breakpoint-inside-a-q-function.html</link><guid isPermaLink="false">817816:9603847:10634490</guid><description><![CDATA[<p>Consider the following function, <span class="inline">testfunc</span>:</p>

<blockquote class="code"><p>testfunc: {[]<br />
<span class="indent">x: `aaa;</span><br />
<span class="indent">y: `bbb;</span><br />
<span class="indent">z:: `ccc;</span><br />
<span class="indent">-1 "finished!";</span><br />
<span class="indent">}</span></p></blockquote>

<p>Let's demonstrate the placement of a breakpoint prior to the assignment of global variable <span class="inline">z</span>.  Although there is no explicit support for breakpoints in q, insertion of non-compliant code, such as <span class="inline">breakhere;</span> shown below, does the job (don't forget the trailing semicolon):</p>

<blockquote class="code"><p>testfunc: {[]<br />
<span class="indent">x: `aaa;</span><br />
<span class="indent">y: `bbb;</span><br />
<span class="indent" style="color: #e48">breakhere;</span><br />
<span class="indent">z:: `ccc;</span><br />
<span class="indent">-1 "finished!"</span><br />
<span class="indent">}</span></p></blockquote>

<p>We are tricking q into throwing a signal <span class="inline">'breakhere</span>.</p>

<blockquote class="code"><p>q)testfunc[]<br />
{[]<br />
<span class="indent">x: `aaa;</span><br />
<span class="indent">y: `bbb;</span><br />
<span class="indent">breakhere;</span><br />
<span class="indent">z:: `ccc;</span><br />
<span class="indent">-1 "finished!"</span><br />
<span class="indent">}</span><br />
'breakhere<br />
q))</p></blockquote>

<p>At this point, we can examine the local stack.</p>

<blockquote class="code"><p>q))x<br />
`aaa<br />
q))y<br />
`bbb<br />
q))z<br />
()<br />
q))</p></blockquote>

<p>kdb has suspended execution, leaving the remaining two lines of function <span class="inline">testfunc</span> unexecuted.  <a href='http://code.kx.com/trac/wiki/Reference/Colon' class='offsite-link-inline'><span class="inline">: (colon)</span></a> resumes execution.</p>

<blockquote class="code"><p>q)):<br />
finished!<br />
-1<br />
q)x<br />
'x<br />
q)y<br />
'y<br />
<span style="color: #e48">q)z </span><br />
<span style="color: #e48">`ccc </span><br />
q)</p></blockquote>

<p>See: <a href="http://code.kx.com/trac/wiki/Reference/ColonColon"> global amend (::)</a></p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-10634490.xml</wfw:commentRss></item><item><title>How do I expose a subset of partitions and remove the rest from view?</title><category>.Q.PV</category><category>.Q.cn</category><category>.Q.pf</category><category>.Q.pn</category><category>.Q.view</category><category>Tricks</category><category>partition subset</category><category>partitions</category><dc:creator>kdbfaq</dc:creator><pubDate>Thu, 02 Jun 2011 01:55:55 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/how-do-i-expose-a-subset-of-partitions-and-remove-the-rest-f.html</link><guid isPermaLink="false">817816:9603847:11136363</guid><description><![CDATA[<p>Short answer: <span class="inline">.Q.view partition_list</span></p>

<p>By default, all partitions of a given historical kdb database are available.  The <a href='http://code.kx.com/trac/wiki/Reference/DotQDotview' class='offsite-link-inline'><span class="inline">.Q.view</span></a> function enables a given kdb process instance to selectively expose an arbitrary set of partitions into view.</p>

<p>The following example restricts all operations of the database instance to the most recent partition date (typically the previous business day):</p>



<pre class='pre'>
q)yesterday: last date
q).Q.view yesterday
q)count date
1
q)yesterday ~ value exec from select distinct date from trade
1b
q)
</pre>



<p>Here is a more realistic example of a date partitioned historical database where viewable partitions are limited to those year-to-date:</p>



<pre class='pre'>
q)start_date: &quot;D&quot; $ string[`year $ .z.D], &quot;.01.01&quot;
q)end_date: last date
q).Q.view date where date within (start_date; end_date)
q)count select from trade where not date within (start_date;
end_date)
0
q)
</pre>



<p>See also: <a class='offsite-link-inline' href='http://code.kx.com/trac/wiki/DotQ/DotQDotcn'><span class="inline">.Q.pn</span></a></p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-11136363.xml</wfw:commentRss></item><item><title>I have a very large file to uncompress. zip and gzip do not work!</title><category>7-zip</category><category>7za</category><category>Utilities</category><category>compress</category><category>compression</category><category>file size limit exceeded</category><category>file too large</category><category>gunzip</category><category>uncompress</category><category>zip</category><dc:creator>kdbfaq</dc:creator><pubDate>Thu, 02 Jun 2011 01:46:54 +0000</pubDate><link>http://www.kdbfaq.com/kdb-faq/i-have-a-very-large-file-to-uncompress-zip-and-gzip-do-not-w.html</link><guid isPermaLink="false">817816:9603847:11014062</guid><description><![CDATA[<p>Short answer: Use <a href="http://www.7-zip.org/download.html" class="offsite-link-inline">7-zip</a>.  It contains large-file support.</p>

<blockquote class="code"><p>$ unzip verylargefile.zip /destination_dir/<br />
I/O error: File too large</p></blockquote>

<p>Make sure your file system can handle <a href="http://en.wikipedia.org/wiki/Large_file_support" title="wikipedia" class="offsite-link-inline"><span class="caps">LFS</span></a>. </p>


<blockquote class="code"><p>$ 7za e -o /destination_dir/ verylargefile.zip</p></blockquote>

<p>See also:  <a href="http://www.dotnetperls.com/7-zip-examples" title="" class="offsite-link-inline">7-zip usage examples</a>.</p>
]]></description><wfw:commentRss>http://www.kdbfaq.com/kdb-faq/rss-comments-entry-11014062.xml</wfw:commentRss></item></channel></rss>