text stringlengths 1.46k 56.1k |
|---|
The .j
namespace¶
JSON serialization
The .j
namespace contains functions for converting between JSON and q dictionaries.
The .j
namespace is reserved for use by KX, as are all single-letter namespaces.
Consider all undocumented functions in the namespace as its private API – and do not use them.
Prior to V3.2, JSON par... |
// @kind function
// @category preprocessing
// @desc Remove columns/keys with zero variance
// @param data {table|dictionary} Data in various formats
// @return {table|dictionary} All columns/keys with zero variance are removed
dropConstant:{[data]
typeData:type data;
if[not typeData in 98 99h;
'"Data must be ... |
runners:()!()
runners[`perf]:{[expec];}
runners[`test]:{[expec];
expec[`code][];
/ We use just a dab of state to communicate with the assertions
expec[`failures]:.tst.assertState.failures;
expec[`assertsRun]:.tst.assertState.assertsRun;
expec[`result]: $[count expec`failures;`testFail;`pass];
expec
}
=========... |
// set.q - Callable functions for the publishing of items to local file system
// Copyright (c) 2021 Kx Systems Inc
//
// @overview
// Publish items to local file system
//
// @category Model-Registry
// @subcategory Functionality
//
// @end
\d .ml
// @kind function
// @category local
// @subcategory set
//
// @ov... |
// @private
// @kind function
// @category utilitiesUtility
// @desc Apply function to data of various types
// @param func {fn} Function to apply to data
// @param data {any} Data of various types
// @return {fn} function to apply to data
i.ap:{[func;data]
$[0=type data;
func each data;
98=type data;
... |
The application of foreign keys and linked columns in kdb+¶
Tables in a database define a relationship between different types of data, whether that relationship is static, dynamic (i.e. fluctuating as part of a time series) or a mixture of both. In general, it is regularly the case that database queries will require d... |
hdbtypes:@[value;`hdbtypes;`hdb]; //list of hdb types to look for and call in hdb reload
hdbnames:@[value;`hdbnames;()]; //list of hdb names to search for and call in hdb reload
tickerplanttypes:@[value;`tickerplanttypes;`tickerplant]; //list of tickerplant types ... |
'
Signal¶
Signal an error
'x
where x
is a symbol atom or string, aborts evaluation and passes x
to the interpreter as a string.
q)0N!0;'`err;0N!1
0
'err
Signal is part of q syntax. It is not an operator and cannot be iterated or projected.
The only way to detect a signal is to use Trap.
q)f:{@[{'x};x;{"trap:",x}]}
q)f`... |
Mass ingestion through data loaders¶
Receiving a large amount of data in various file formats and from multiple different sources that need to be ingested, processed, persisted, and reported upon within a certain time period is a challenging task.
One way of dealing with this is to use a batch-processing model, the req... |
// add to cache
add:{[function;id;status]
// Don't trap the error here - if it throws an error, we want it to be propagated out
res:value function;
$[(maxindividual*MB)>size:-22!res;
// check if we need more space to store this item
[now:.proc.cp[];
if[0>requiredsize:(maxsize*MB) - size+sum exec size from cach... |
// find function
// s = search string
// p = public flag (1b or 0b)
// c = context sensitive
find:{[s;p;c]
// Check the input type
if[-11h=type s;$[null s; s:enlist"*";s:"*",(string s),"*"]];
if[not 10h=abs type s:s,(); '"input type must be a symbol or string (character array)"];
// select from the fullapi on th... |
// @kind function
// @category private
// @fileoverview Generate boundary marker
// @param x {any} Unused
// @return {string} Boundary marker
gb:{(24#"-"),16?.Q.an}
// @kind function
// @category private
// @fileoverview Build multi-part object
// @param b {string} boundary marker
// @param d {dict} headers (incl. file... |
Get started with q and kdb+¶
kdb+ is a database. You can use it through interfaces such as ODBC, or from Python, but its power and performance are best accessed through its own language, q.
Q is a general-purpose programming language. You can write programs for anything in q.
You do not need prior programming experienc... |
// function to determine the date (in rolltimezone) from UTC timestamp, p
getday:{[p]
p+:adjtime[p]; // convert date from UTC to rolltimezone
"d"$p-rolltimeoffset // adjust day according to rolltimeoffset
};
d:getday[.z.p]; ... |
div
¶
Integer division
x div y div[x;y]
Returns the greatest whole number that does not exceed x%y
.
q)7 div 3
2
q)7 div 2 3 4
3 2 1
q)-7 7 div/:\:-2.5 -2 2 2.5
2 3 -4 -3
-3 -4 3 2
Except for char, byte, short, and real, preserves the type of the first argument.
q)7f div 2
3f
q)6i div 4
1i
q)2014.10.13 div 365
2000.01.... |
// function to correctly reduce two tables to one
mapreduceres:{[options;res]
// raze the result sets together
res:$[all 99h=type each res;
(){x,0!y}/res;
(),/res];
aggs:options`aggregations;
aggs:flip(key[aggs]where count each value aggs;raze aggs);
// distinct may be present as onl... |
vpw:{[x;y] $[defaultuser x;validhost .z.a;0b]}
vpg:{validcmd[.z.u;x]}
/ vps:{$[0=.z.w;1b;poweruser .z.u;validcmd[.z.u;x];0b]}
vps:{$[0=.z.w;1b;validcmd[.z.u;x]]}
vpi:{$[0=.z.w;1b;superuser .z.u]}
vph:{superuser .z.u}
vpp:{superuser .z.u}
vws:{defaultuser .z.u} / not clear what/how to restrict yet
\d .
.lg.o[`access;"... |
Precision¶
Float precision¶
Precision of floats is a complex issue because floats (known as doubles in other programming languages) are actually binary rational approximations of real numbers. If you are concerned with precision, make sure to set \P 0
before proceeding with anything else. This helps you understand what... |
_
Drop¶
Drop items from a list, entries from a dictionary or columns from a table.
x _ y _[x;y]
_
(drop) is a multithreaded primitive.
Drop leading or trailing items¶
Where
x
is an int atomy
a list or dictionary
returns y
without the first or last x
items.
q)5_0 1 2 3 4 5 6 7 8 /drop the first 5 items
5 6 7 8
q)-5_0 1 ... |
// ### qclone
// NOTE: offloadHttp doesn't work properly until the
// hclose fix of 2.8.20120420.
.finos.sys.errorTrapAt:@[;;]
// Add help.
.help.DIR[`qclone]:`$"offload clients/tasks to clone process(es)"
.finos.qclone.priv.help: enlist "Support for offloading work to clone processes."
// Select which kind of se... |
// return the details of the current process
getdetails:{(.z.f;.z.h;system"p";@[value;`.proc.procname;`];@[value;`.proc.proctype;`];@[value;(`.proc.getattributes;`);()!()])}
/ add session behind a handle
addhw:{[hpuP;W]
// Get the information around a process
info:`f`h`port`procname`proctype`attributes!(@[W;({$... |
gwConnected:{
-1"GW connected";
.finos.init.provide`gwConnected;
};
doProcess:{
-1"Doing something with both tp and gw...";
};
.finos.init.add[`tpConnected`gwConnected;`doProcess;()];
connectToTp:{
//simulate connecting to an external service
.finos.timer.addRelativeTimer[{tpConnected[]};0... |
// @private
// @kind function
// @category savingUtility
// @fileoverview Save data as a splayed table
// @param config {dict} Any configuration information about the dataset being
// saved
// @param data {tab} Data which is to be saved
// @return {null} Data is saved as a splayed table
i.saveFunc.splay:{[config;da... |
insert
¶
Insert or append records to a table
x insert y insert[x;y]
Where
x
is a symbol atom naming a non-splayed tabley
is one or more records that match the columns ofx
; or ifx
is undefined, a table
inserts y
into the table named by x
and returns the new row indexes.
The left argument is the name of a table as a sym... |
Unit tests¶
The goal of unit tests is to check that the individual parts of a program are correct.
Unit tests provide a written contract that a piece of code must satisfy.
Unit testing
Q supports unit testing with the script k4unit.q
, which loads test descriptions from CSV files, runs the tests, and writes results to ... |
// @kind function
// @category main
// @subcategory update
//
// @overview
// Update the psi details of a saved model
//
// @param folderPath {dict|string|null} Registry location, can be:
// 1. A dictionary containing the vendor and location as a string, e.g.
// ```enlist[`local]!enlist"myReg"``` or
// ```e... |
Syntax¶
It is a privilege to learn a language,
a journey into the immediate
– Marilyn Hacker, “Learning Distances”
The q-SQL query templates select
, exec
, update
, and delete
have their own syntax.
Elements¶
The elements of q are
- functions: operators, keywords, lambdas, and extensions
- data structures: atoms, list... |
Q by examples¶
Simple arithmetic¶
q)2+2 / comment is ' /': left of /: whitespace or nothing
4
q)2-3 / negative numbers
-1
q)2*3+4 / no precedence, right to left
14
q)(2*3)+4 / parentheses change order
10
q)3%4 / division
0.75
q){x*x}4 / square
16
q)sqrt 4 / square root
2.0
q)reciprocal 4 / 1/x
0.25
Operations using lis... |
// @kind function
// @category node
// @desc Save all metadata information needed to predict on new data
// @param params {dictionary} All data generated during the preprocessing and
// prediction stages
// @return {dictionary} All metadata information needed to generate predict
// function
saveMeta.node.function:{... |
.
@
Amend, Amend At¶
Modify one or more items in a list, dictionary or datafile.
Amend Amend At values (d . i) or (d @ i)
.[d; i; u] @[d; i; u] u[d . i] u'[d @ i]
.[d; i; v; vy] @[d; i; v; vy] v[d . i;vy] v'[d @ i;vy]
Where
d
is an atom, list, or a dictionary (value); or a handle to a list, dictionary or datafilei
inde... |
writedownadvanced:{
if[0=count .dqe.tosavedown`.dqe.advancedres;:()];
dbprocs:exec distinct procname from raze .servers.getservers[`proctype;;()!();0b;1b]each .dqe.hdbtypes,`dqedb`dqcdb; // Get a list of all databases.
advtemp1:select from .dqe.advancedres where procs in dbprocs;
advtemp2:select from .dqe.adva... |
// set up the usage information
.proc.extrausage:"Log Replay:\n
This process is used to replay tickerplant log files.
There are multiple options which can be set either in the config files or via the standard command line switches e.g. -.replay.firstmessage 20
\n
It can be used to replay full files and partial fil... |
Skip to content
kdb+ and q documentation
or – Reference – kdb+ and q documentation
Initializing search
Ask a question
Home
kdb+ and q
kdb Insights SDK
kdb Insights Enterprise
KDB.AI
PyKX
APIs
Help
kdb+ and q documentation
Home
kdb+ and q
kdb+ and q
About
Getting Started
Getting Started
Install
Licenses
Learn
Learn
Over... |
Socket sharding with kdb+ and Linux¶
When creating a new TCP socket on a Linux server several options can be set which affect the behavior of the newly-created socket. One of these options, SO_REUSEPORT
, allows multiple sockets to bind to the same local IP address and port. Incoming connection requests to this port nu... |
// @kind function
// @category nlp
// @desc Parse URLs into dictionaries containing the
// constituent components
// @param url {string} The URL to decompose into its components
// @returns {dictionary} Contains information about the scheme, domain name
// and other URL information
parseURLs:{[url]
urlKeys:`sche... |
C API Reference¶
Overview¶
K object¶
The C API provides access to the fundamental data K
object of kdb+ and methods of manipulating it. The K
object is a pointer to a k0
struct, a tagged union, and most of the API manipulates this pointer.
It is defined as
typedef struct k0 *K;
More detailed information can be found in... |
// @kind function
// @category metric
// @desc True/false positives and true/false negatives
// @param pred {int[]|boolean[]|string[]} A vector of predicted labels
// @param true {int[]|boolean[]|string[]} A vector of true labels
// @param posClass {number|boolean} The positive class
// @returns {dictionary} The count... |
Intel Optane Persistent Memory and kdb+¶
Intel® Optane™ persistent memory, herein called Intel Optane PMem, is a new hardware technology from Intel.
Intel Optane PMem is based on a new silicon technology, 3D XPoint, which has low latency (memory like) attributes and is more durable than traditional NAND Flash.
Intel Op... |
/ @returns (FolderPath) The current working directory using the OS specific command
/ @throws OsNotSupportedForCwdException If the operating system is not supported
.require.i.getCwd:{
os:first string .z.o;
if["w"~os;
:hsym first `$trim system "echo %cd%";
];
if[os in "lms";
:hsym firs... |
Views¶
A view is a calculation that is re-evaluated only if the values of the underlying dependencies have changed since its last evaluation.
Why use a view?¶
Views can help avoid expensive calculations by delaying propagation of change until a result is demanded.
How is a view defined?¶
Views and their dependencies ca... |
NASA Frontier Development Lab Space Weather Challenge¶
The NASA Frontier Development Lab (FDL) is an applied artificial intelligence (AI) research accelerator, hosted by the SETI Institute in partnership with NASA Ames Research Centre. The programme brings commercial and private partners together with researchers to so... |
Server calling client¶
This demonstrates how to simulate a C client handling a get call from a kdb+ server.
The Java interface allows you to emulate a kdb+ server. The C interface does not provide the ability to respond to a sync call from the server, however, async responses (message type 0) can be sent using k(-c,...... |
FDL Europe: Analyzing social media data for disaster management¶
Frontier Development Lab (FDL) Europe is an applied artificial-intelligence (AI) research accelerator, in partnership with the European Space Agency (ESA) and Oxford University and leaders in commercial AI. The overall goal of the program is to solve chal... |
Datatypes¶
Basic datatypes
n c name sz literal null inf SQL
----------------------------------------------------------
0 * list
1 b boolean 1 0b
2 g guid 16 0Ng
4 x byte 1 0x00
5 h short 2 0h 0Nh 0Wh smallint
6 i int 4 0i 0Ni 0Wi int
7 j long 8 0j 0Nj 0Wj bigint
0 0N 0W
8 e real 4 0e 0Ne 0We real
9 f float 8 0.0 0n 0w ... |
Cost/risk analysis¶
To determine how much cost savings our cluster of RDBs can make we will deploy the stack and simulate a day in the market.
t3
instances were used here for simplicity.
Their small sizes meant the clusters could scale in and out to demonstrate cost savings without using a huge amount of data.
In reali... |
Regular expressions¶
Keywords like
, ss
, and ssr
interpret their second arguments as a limited form of Regular Expression (regex).
In a q regex pattern certain characters have special meaning:
? wildcard: matches any character
* matches any sequence of characters
[] embraces a list of alternatives, any of which matche... |
Machine Learning in kdb+:
k-Nearest Neighbor classification and pattern recognition with q¶
Amongst the numerous algorithms used in machine learning, k-Nearest Neighbors (k-NN) is often used in pattern recognition due to its easy implementation and non-parametric nature. A k-NN classifier aims to predict the class of a... |
xbar
¶
Round down
x xbar y xbar[x;y]
Where
x
is a non-negative numeric atomy
is numeric or temporal
returns y
rounded down to the nearest multiple of x
. xbar
is a multithreaded primitive.
q)3 xbar til 16
0 0 0 3 3 3 6 6 6 9 9 9 12 12 12 15
q)2.5 xbar til 16
0 0 0 2.5 2.5 2.5 5 5 5 7.5 7.5 7.5 10 10 10 12.5
q)5 xbar 11... |
// @kind function
// @category automl
// @desc The application of AutoML on training and testing data,
// applying cross validation and hyperparameter searching methods across a
// range of machine learning models, with the option to save outputs.
// @param graph {dictionary} Fully connected graph nodes and edges ... |
-1"[down]loading citibike data";
b:"http://s3.amazonaws.com/tripdata/"
m1:.ut.sseq[1] . 2014.09 2016.12m
m1:m1 where m1 within (sd;ed)
f1:,[;"-citibike-tripdata"] each string[m1] except\: "."
.ut.download[b;;".zip";.ut.unzip] f1;
m2:.ut.sseq[1] . 2017.01 2017.12m
m2:m2 where m2 within (sd;ed)
f2:,[;"-citibike-tripdata... |
Streaming analytics with kdb+:
Detecting card counters in Blackjack¶
With the growth and acceleration of the Internet of Things, data collection is increasingly being performed by sensors and smart devices. Sensors are able to detect just about any physical element from a multitude of machines, including mobile phones,... |
/- open handle to log file
openlog:{[lgfile]
lgfileexists:type key lgfile;
/- check if log file is present on disk
.lg.o[`openlog;
$[lgfileexists;
"opening log file : ";
"creating new log file : "],string lgfile];
/- create log file
if[not lgfileexists;
.[set;(lgfile;());{[lgf;err] .lg.e[`... |
bind:{[sess;customDict]
defaultKeys:`dn`cred`mech;
defaultVals:```;
defaultDict:defaultKeys!defaultVals;
if[customDict~(::);customDict:()!()];
if[99h<>type customDict;'"customDict must be (::) or a dictionary"];
updDict:defaultDict,customDict;
bindSession:.ldap.bind_s[sess;;;]. updDict defaultKeys;
bind... |
max
, maxs
, mmax
¶
max
¶
Maximum
max x max[x]
Where x
is a non-symbol sortable list, returns the maximum of its items.
The maximum of an atom is itself.
Nulls are ignored, except that if the items of x
are all nulls, the result is negative infinity.
q)max 2 5 7 1 3
7
q)max "genie"
"n"
q)max 0N 5 0N 1 3 / nulls are ign... |
List programs¶
From GeeksforGeeks Python Programming Examples
Follow links to the originals for more details on the problem and Python solutions.
Interchange first and last elements in a list¶
>>> lis = [12, 35, 9, 56, 24]
>>> lis[0], lis[-1] = lis[-1], lis[0]
>>> lis
[24, 35, 9, 56, 12]
-1
is not an index in q, so we ... |
// @private
// @kind function
// @category hyperparameterUtility
// @desc Uniform number generator
// @param randomType {symbol} Type of random search, denoting the namespace
// to use
// @param low {long} Lower bound
// @param high {long} Higher bound
// @param paramType {char} Type of parameter, e.g. "i", "f", et... |
Alternative in-memory layouts¶
Prior to kdb+, as veterans will remember, some schemas used nested data per symbol. The `g#
attribute allowed us to move away from those more complicated designs and queries to long flat tables with fast access via the group attribute.
There is however a third layout for in-memory data, u... |
\d .u
jcounts:(`symbol$())!0#0,();
icounts:(`symbol$())!0#0,(); / set up dictionary for per table counts
ld:{if[not type key L::`$(-10_string L),string x;.[L;();:;()]];i::j::@[-11!;L;i::-11!(-2;L)];jcounts::icounts;if[0 < type i;-2 (string L)," is a corrupt log. Truncate to length ",(string last i)," and restart";exit... |
/ Converts a timestamp in the specified timezone into another specified timezone
/ NOTE: This conversion is done via UTC so will be slower than converting to/from UTC
/ @param timestamp (Timestamp|TimestampList) The timestamps to convert
/ @param sourceTimezone (Symbol) The timezone that the specified timestamps are ... |
///
// Cut a path into a list of directory names and file name
// @param path as a string.
// @return A list in the form (dir1;dir2;...;file). E.g. "aa/bb/cc" -> ("aa";"bb";"cc")
.finos.dep.splitPath:{[path]
path:"",path;
if[0=count path; :()];
match:path ss .finos.dep.pathSeparators;
enlist[first[match... |
Permissions with kdb+¶
kdb+ processes often contain sensitive, proprietary information in the form of data or proprietary code. Thus, it is important to restrict the access to this information.
kdb+ offers a number of in-built access functions. This paper discusses various methods in which a permissioning and entitleme... |
Appendix E - Goofys¶
Goofys is an open-source Linux client distribution. It uses an AWS S3 storage backend, behind a running and a normal Linux AWS EC2 instance. It presents a POSIX file system layer to kdb+ using the FUSE layer. It is distributed in binary form for RHEL/CentOS and others, or can be built from source.
... |
//replace callback function
.finos.timer.replaceCallback:{[tid;func]
if[not type[tid] in -6 -7h; '"Expecting a integer id in .finos.timer.replaceCallback."];
if[not tid in exec id from .finos.timer.priv.timers; '"invalid timer ID"];
.finos.timer.priv.validateCallback[func];
.finos.timer.priv.timers[tid;... |
/ help.q 2011.06.07T13:44:00.971
\d .help
DIR:TXT:()!()
display:{if[not 10h=abs type x;x:string x];$[1=count i:where(key DIR)like x,"*";-1 each TXT[(key DIR)[i]];show DIR];}
fetch:{if[not 10h=abs type x;x:string x];$[1=count i:where(key DIR)like x,"*";1_raze"\n",'TXT[(key DIR)[first i]];DIR]}
TXT,:(enlist`adverb)!enlis... |
// Test trade batches
batch1:(10?`4;10?100.0;10?100i;10#0b;10?.Q.A;10?.Q.A;10#`buy);
batch2:(1?`4;1?100.0;1?100i;1#0b;1?.Q.A;1?.Q.A;1#`buy);
// Local trade table schema
trade:flip `time`sym`price`size`stop`cond`ex`side!"PSFIBCCS" $\: ();
// Local upd function
upd:{[t;x] t insert x};
=================================... |
// @private
// @kind function
// @category optimizationUtility
// @desc Calculate the vector norm, used in calculation of the gradient
// norm at position k. Default behaviour is to use the maximum value of the
// gradient, this can be overwritten by a user, this is in line with the
// default python implementat... |
Reference card¶
Keywords¶
By category¶
.Q.id
(sanitize),
.Q.res
(reserved words)
Operators¶
. |
Apply, Index, Trap, Amend | @ |
Apply At, Index At, Trap At, Amend At | ||||
$ |
Cast, Tok, Enumerate, Pad, mmu |
||||||
! |
Dict, Enkey, Unkey, Enumeration, Flip Splayed, Display, internal, Update, Delete, lsq |
||||||
? |
... |
// Reset and try to load in a file while in segmented mode
segfile:{[logfile]
.replay.segmentedmode:1b;
.replay.tplogfile:logfile;
.replay.tplogdir:`;
.replay.initandrun[];
};
// Reset and try to load in a file and a directory at the same time
dirandfile:{[logfile]
.replay.tplogfile:logfile;
.replay.tplog... |
// @private
//
// @overview
// Copy a file from one location to another, ensuring that the file exists
// at the source location
//
// @todo
// Update this to use the axfs OS agnostic functionality provided by Analyst
// this should ensure that the functionality will operate on Windows/MacOS/Linux
//
// @param src {#... |
Historical database¶
A historical database (HDB) holds data before today, and its tables would be stored on disk, being much too large to fit in memory. Each new day’s records would be added to the HDB at the end of day.
Typically, large tables in the HDB (such as daily tick data) are stored splayed, i.e. each column i... |
// Check if required process names all connected
reqprocnamesnotconn:reqprocsnotconn[;`procname];
// Block process until all required processes are connected
startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles]
n:1; ... |
// @kind function
// @category fresh
// @desc K-best features: choose the K features which have the lowest
// p-values and thus have been determined to be the most important features
// to allow us to predict the target vector.
// @param k {long} Number of features to select
// @param pValues {dictionary} Output o... |
//- get default time from tickerplant or table
getdefaulttime:{[dict]
// go to the tableproperties table
if[not ` ~ configure:.checkinputs.tablepropertiesconfig[(dict`tablename),.proc.proctype;`primarytimecolumn];:configure];
timestamp:(exec from meta (dict`tablename) where t in "p")`c;
if[1 < count timestamp;... |
Sample aggregation engine for market depth¶
Throughout the past decade the volume of data in the financial markets has increased substantially due to a variety of factors, including access to technology, decimalization and increased volatility. As these volumes increase it can pose significant problems for applications... |
Play Klondike¶
Problem Play Klondike in the q session.
The last thing the world needs is another program to implement Solitaire, a.k.a. Klondike. But here it is, as a case study for writing q programs. A well-understood problem domain, small but non-trivial, is a good subject for close code reading.
Techniques¶
- Worki... |
/- compares the attribute of given table to expectation given in csv
attrcheck:{[tab;attribute;col]
.lg.o[`dqe;"checking attributes on table ",string tab];
dictmeta:exec c!a from meta tab where c in col;
dictcheck:(f col)!(f:{$[0>type x;enlist x;x]})attribute;
$[dictmeta~dictcheck;
(1b;"attribute of ",(","s... |
Loading from large files¶
The Load CSV form of the File Text operator loads a CSV file into a table in memory, from which it can be serialized in various ways.
If the data in the CSV file is too large to fit into memory, we need to break the large CSV file into manageable chunks and process them in sequence.
Function .... |
Q client for ODBC¶
In Windows and Linux, you can use ODBC to connect to a non-kdb+ database from q.
Installation¶
To install, download
- KxSystems/kdb/c/odbc.k into the q directory
- the appropriate
odbc.so
orodbc.dll
:
| q | q/l32 | q/l64 | q/w32 | q/w64 |
|---|---|---|---|---|
| ≥V3.0 | odbc.so |
odbc.so | odbc.dll |... |
Reference architecture for AWS¶
kdb+ is the technology of choice for many of the world’s top financial institutions when implementing a tick-capture system for timeseries analysis. kdb+ is capable of processing large amounts of data in a very short space of time, making it the ideal technology for dealing with the ever... |
\c 20 77
\l funq.q
\l zoo.q
\l iris.q
-1"computing the silhouette demonstrates cluster quality";
-1"by generating a statistic that varies between -1 and 1";
-1"where 1 indicates a point is very close to all the items";
-1"within its own cluster and very far from all the items";
-1"in the next-best cluster while -1 ind... |
// check that ordering parameter contains only symbols and is paired in the format
// (direction;column).
checkordering:{[dict;parameter]
if[11h=type dict parameter;dict[parameter]:enlist dict parameter];
input:dict parameter;
if[11h<>type raze input;
'`$.schema.errors[`checkorderingpair;`errormessa... |
// @kind function
// @category main
// @subcategory set
//
// @overview
// Save parameter information for a model
//
// @param folderPath {dict|string|null} Registry location, can be:
// 1. A dictionary containing the vendor and location as a string, e.g.
// ```enlist[`local]!enlist"myReg"``` or
// ```enlis... |
QSQL query templates¶
delete delete rows or columns from a table exec return columns from a table, possibly with new columns select return part of a table, possibly with new columns update add rows or columns to a table
The query templates of qSQL share a query syntax that varies from the syntax of q and closely resemb... |
/ see e.g. https://unix.stackexchange.com/a/14727 for info about xat
r:update
{("i"$first x)%10}ver,
{("i"$first x)%10}vrr,
.finos.unzip.priv.flags!.finos.unzip.priv.parseBits flg,
.finos.unzip.priv.parseNum cmp,
{"v"$24 60 60 sv 1 1 2*2 sv'0 5 11 cut reverse .finos.unzip.priv.parseBits ... |
if[any[null h`w]|any null r[;1];
.lg.e[`runcheck;"unable to compare as process down or missing handle"];
.dqe.updresultstab[runtype;idnum;0Np;0b;"error:unable to compare as process down or missing handle";`failed;params;params`compresproc];
:()];
]
/- check if any handles exist, if not exit funct... |
extrapolate:{[F;v]
v[`z2]:cubicextrapolation . v`f2`f3`d2`d3`z3;
v[`z2]:$[$[0>v`z2;1b;0w=v`z2];$[.5>=v`limit;v[`z1]*EXT-1;.5*v[`limit]-v`z1];
/ extrapolation beyond max? -> bisect
$[-.5<v`limit;v[`limit]<v[`z2]+v`z1;0b];.5*v[`limit]-v`z1;
/ extrapolation beyond limit? -> set to limit
$[-.5>v`limit;(EXT*v`z1)<... |
NASA Frontier Development Lab Exoplanets Challenge¶
The NASA Frontier Development Lab (FDL) is an applied artificial intelligence (AI) research accelerator, hosted by the SETI Institute in partnership with NASA Ames Research Centre. The programme brings commercial and private partners together with researchers to solve... |
// @kind function
// @category fresh
// @desc Extract features using FRESH
// @param data {table} Input data
// @param idCol {symbol[]} ID column(s) name
// @param cols2Extract {symbol[]} Columns on which extracted features will
// be calculated (these columns must be numerical)
// @param params {table|symbol|symbol[... |
sv
¶
“Scalar from vector”
- join strings, symbols, or filepath elements
- decode a vector to an atom
x sv y sv[x;y]
Join¶
Strings¶
Where
y
is a list of stringsx
is a char atom, string, or the empty symbol
returns as a string the strings in y
joined by x
.
Where x
is the empty symbol `
, the strings are separated by the... |
Using log files: logging, recovery and replication¶
Overview¶
Software or hardware problems can cause a kdb+ server process to fail, possibly resulting in loss of data if not saved to disk at the time of the failure. A kdb+ server can use logging updates to avoid data loss when failures occur.
This should not be confus... |
reciprocal
¶
Reciprocal of a number
reciprocal x reciprocal[x]
Returns the reciprocal of numeric x
as a float.
q)reciprocal 0 0w 0n 3 10
0w 0 0n 0.3333333 0.1
q)reciprocal 1b
1f
reciprocal
is a multithreaded primitive.
Implicit iteration¶
reciprocal
is an atomic function.
q)reciprocal (12;13 14)
0.08333333
0.07692308 0... |
key
¶
key x key[x]
Key of a dictionary¶
Where x
is a dictionary (or the name of one), returns its key.
q)D:`q`w`e!(1 2;3 4;5 6)
q)key D
`q`w`e
q)key `D
`q`w`e
A namespace is a dictionary.
q)key `.
`D`daily`depth`mas`sym`date`nbbo...
q)key `.q
``neg`not`null`string`reciprocal`floor`ceiling`signum`mod`xbar`xlog`and`or`ea... |
Application, projection, and indexing¶
Values¶
Everything in q is a value, and almost all values can be applied.
- A list can be applied to its indexes to get its items.
- A list with an elided item or items can be applied to a fill item or list of items
- A dictionary can be applied to its keys to get its values.
- A ... |
Multithreaded primitives¶
To complement existing explicit parallel computation facilities (peach
), kdb+ 4.0 introduces implicit, within-primitive parallelism. It is able to exploit internal parallelism of the hardware – in-memory, with modern multi-channel memory architectures, and on-disk, e.g. making use of SSD inte... |
Errors¶
Runtime errors¶
- {directory}/q.k. OS reports: No such file or directory
-
Using the environment variable
QHOME
(or<HOME DIRECTORY>/q
if not set),q.k
was not found in the directory specified. Check that theQHOME
environment variable is correctly set to the directory containingq.k
, which is provided in the kdb+... |
Data recovery for kdb+tick¶
KX freely offers a complete tick-capture product which allows for the processing, analysis and historical storage of huge volumes of tick data in real time. This product, known as kdb+tick, is extremely powerful, lightweight and forms the core of most kdb+ architectures.
The tickerplant lies... |
Reference architecture for Google Cloud¶
kdb+ is the technology of choice for many of the world’s top financial institutions when implementing a tick-capture system. kdb+ is capable of processing large amounts of data in a very short space of time, making it the ideal technology for dealing with the ever-increasing vol... |
psz:{[s;x]
if[0=n:count x;:0];t*:11h<>t:.Q.tx each value .Q.V x;if[0h<(&/)t;:n*(+/)tw t]; / Exit if table empty or materialized types all fixed-width
j:1+(c:(+\)k:(|).Q.pn s)binr i:cs n; / Find number of trailing partitions required to obtain statistical sample
p:(neg[j]#.Q.pv)(j-1)-m:where 0<k:j#k; / From these, ge... |
// @kind function
// @category featureCreate
// @desc Apply word2vec on string data for NLP problems
// @param features {table} Feature data as a table
// @param config {dictionary} Information related to the current run of AutoML
// @return {table} Features created in accordance with the NLP feature creation
// pr... |
/- Take the average symfile count from the past n days, then check that todays
/- sym file count hasn't grown more than pct%. Third argument (weekends) is a
/- boolean flagging if you should consider weekends (1b) or not (0b).
symfilegrowth:{[ndays;pct;weekends]
.lg.o[`symfilegrowth;"Checking sym file has not grown m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.