Using Clojure With CFML
This is the upcoming (3.5 – clojure) documentation – for the current stable release, read the 3.0 master documentation.
Clojure and CFML Sitting in a tree
Back in 2010, I started to learn Clojure. It’s a Lisp that runs on the JVM. It’s a mostly pure functional programming language. It’s very simple — very little syntax — but very powerful and expressive. It has a thriving community and ecosystem. Being a functional programming language it favors immutable data structures and higher order functions (map, filter, reduce, etc) which makes programs easy to reason about and it also makes concurrent programming pretty easy. No more thread safety issues!
Although Clojure can be compiled to JVM bytecode and deployed as a JAR or WAR file, it can also be treated like a dynamic scripting language and compiled on-the-fly to JVM bytecode, just like CFML, giving you that very fast edit-reload-test cycle that you’re used to with CFML. In fact, if you use the REPL (Read-Eval-Print-Loop) you can pretty much reduce that to just edit-test since Clojure code is compiled as you type it in and can be evaluated immediately.
Because I was still writing a lot of CFML back in 2010, I figured out an easy way to allow you, as a CFML developer, to load and run Clojure code within your CFML application. That functionality has been available via the standalone cfmljure library for several years, and it has become core to how the Internet dating platform works at my company (World Singles Networks). We’ve had cfmljure in production since Spring 2011 and, in 2014, we declared Clojure to be our primary language and nearly all new development happens in Clojure, hosted within three ColdBox applications and two FW/1 applications. Clojure powers all of our standalone processes as well.
As we’ve come to depend on FW/1 more and more, I’ve wanted to streamline the integration between FW/1 and cfmljure so that we can write services in Clojure and have them autowired into our controllers, just like our CFML services are, as well as have the option to write controllers in Clojure (where all the code they call is Clojure, not CFML).
That’s why, in FW/1 3.5, I’ve made cfmljure part of the standard distribution and provided an extenion to DI/1 to allow Clojure code to be discovered and autowired into your CFML code, as well as a way to write FW/1 controllers in pure Clojure.
Some Important Caveats (and System Requirements)
Before you get started, there are a couple of things you need to be aware of:
- The Clojure integration works best on Lucee (4.5 or later) or Railo (4.2). ColdFusion 11 is supported too but interop between CFML and Clojure can get pretty ugly (see the ColdFusion-specific examples in the cfmljure project repo for more details). I doubt it will run on ColdFusion 10 or earlier. I developed exclusively on Railo from 2009 to 2015 and now I develop on Lucee. Thank Andrew Myers for the ColdFusion 11 support!
- You should be running Java 8 at this point. The Clojure integration will not work on Java 6. It has not been tested on Java 7. The Java 6 EOL notice was February 2011 and public updates stopped in February 2011. The Java 7 EOL notice was March 2014 and public updates stopped in April 2015.
- Clojure developers are pretty comfortable at the command line, so the build tool you’ll need to install for this is a command line tool: be prepared to work in Terminal / Console quite a bit!
- Clojure developers use editors that auto-close parentheses, brackets, and braces. Most of those editors also support “structural editing” which means they understand expressions enclosed in matched pairs of parentheses (or brackets or braces) and let you easily manipulate expressions rather than just text. There are plugins for Eclipse, Sublime Text, IntelliJ and several others. Most Clojure developers use Emacs or Vim. I use Emacs for all my editing, CFML included.
- In order to use Clojure with CFML, you must not run your CFML server under the root account (on Mac or Linux). It’s something you should never do in production anyway for security reasons, and there’s really no reason to do it on your development machine either. cfmljure checks this for you and refuses to initialize (and throws a helpful exception).
- For ease of debugging any problems that may occur, I strongly recommend you always keep a Terminal / Console window open
containing a tail of the console output from your CFML server. If you’re using Lucee or a Railo installation based on Tomcat,
you’ll want to find the
catalina.out
log file and tail that. If you’re using ColdFusion 11, even tho’ it is notionally based on Tomcat, it’s completely non-standard and you’ll want to tailcfusion/logs/coldfusion-out.log
. - Finally, cfmljure uses a lock file to ensure that a couple of things it does during initialization are single-threaded
across the whole server, no matter how your CFML server and application instances are configured. On Mac and Linux, it
creates (and deletes)
/tmp/cfmljure.lock
. On Windows, it creates (and deletes)cfmljure.lock
in yourTEMP
folder which is normally in theAppData
folder off your local accounts home folder — check yourTEMP
environment variable for the exact location. cfmljure tries really hard to clean up after itself but if something goes badly wrong during initialization, it’s possible the lock file will be left behind and you will need to manually delete it. cfmljure will try its best to let you know if it needs you to delete the lock file — but if you’re tailing the logs, you’ll see messages as the initialization proceeds.
Getting Started with Clojure and CFML
Clojure has a standard build tool called Leiningen. This manages all of your project dependencies (e.g., automatically downloading and installing any libraries you need) as well as providing a REPL for interactive development, running your tests, packaging applications into JAR files, deploying them to standard repositories and so on.
cfmljure leverages Leiningen to figure out the complete classpath that your Clojure code needs — including any libraries you use — so that it can easily load all the JAR files (and Clojure source code) into your CFML server.
Leiningen
That means the first step to using FW/1 and Clojure together is to install Leiningen and make sure it is working.
If you’re on Mac or Linux, follow the Leiningen Install steps for the lein
shell script.
If you’re on Windows, I recommend using the Installer for Windows users mentioned near the end of that Install section.
Once you have it installed, open up a new Terminal / Console window and navigate to directory where you can create a project to test that it is working properly, then do this:
lein new app myapp
It will probably download a bunch of libraries the first time you run it, but it should (eventually) respond:
Generating a project called myapp based on the 'app' template.
Now go into that project and run it:
cd myapp
lein run
It should say:
Hello, World!
Congratulations! Leiningen is installed and working!
BTW, Leiningen supports unit testing out of the box, so in addition to creating an application skeleton for myapp
,
it also generates a test skeleton which you can run like this:
lein test
Because the test skeleton doesn’t have any valid tests — just one deliberate failure — you should see:
lein test myapp.core-test
lein test :only myapp.core-test/a-test
FAIL in (a-test) (core_test.clj:7)
FIXME, I fail.
expected: (= 0 1)
actual: (not (= 0 1))
Ran 1 tests containing 1 assertions.
1 failures, 0 errors.
Tests failed.
When you start developing services and controllers in Clojure, you’ll find it handy to write unit tests as you go and run
them with lein test
!
Testing FW/1 3.5 and Clojure
At this point you should be able to start your CFML server (remember: not under the root account!) and, with FW/1 3.5
installed (and possibly with a /framework
mapping set up, or with the framework
folder moved into your webroot), you
should be able to run all of the FW/1 examples. Make sure examples 1-5 work, then try 6helloclojure
.
If it doesn’t seem to run correctly, and there’s no obvious exception information in the browser or useful information in the
log file, you can try to re-run the 6helloclojure
example with ?cfmljure=abortOnFailure
added to the URL. This should
dump a whole bunch of information to the browser as well as any exception encountered.
If that doesn’t help, add diConfig : { debug : true }
to the variables.framework
configuration in Application.cfc
for
that example and try again. This will output more information to the CFML server’s console log (which you’re tailing, right?).
If you can’t figure out the problem from all this extra debugging information, at least you’ll have it all available when you post to the FW/1 mailing list, asking for help!
At this point, however, I hope you got the example to run and you were able to try out the various links and see what it was doing in the trace output in the browser, and perhaps by looking at the code, which we’ll go over next.
The 6helloclojure Example Explained
If you look in the 6helloclojure
folder, you’ll see a combination of things you expect to see in a FW/1 application and
files and folders that would see in your myapp
Clojure test project above:
Application.cfc index.cfm views
.gitignore LICENSE README.md doc resources target
project.clj src test
The files shown in the first line are for FW/1. You might later add a controllers
folder and a model
folder if you
write any of those pieces in CFML.
The files shown in the second line are generated by Leiningen and you can pretty much ignore them. You’ll see that by
default a Leiningen-generated Clojure project is assumed to live under version control with git
, have an open source
software license (Eclipse Public License 1.0 by default), have a readme file that explains what the project is for and
how to use it, a documentation folder, possibly some non-source code resource files (configuration files or perhaps
assets for a web application), and you may see a target
folder which is used by Leiningen for compiling code and
generating JAR files etc.
The files shown in the third line are the important parts of the Clojure code:
* project.clj
defines the dependencies of
your project (the libraries it needs), as well as any development or test tooling (as plugins) and several other
important aspects of how to run, test, and package your code. You’ll notice that it also has a description, a URL for
where to find the project (e.g., on GitHub), and details of the license.
* src
is where your Clojure source code lives. Clojure itself places very few restrictions on the structure of this
(beyond assuming that the file structure matches the namespace structure within the Clojure source files, much the
same way Java’s file structure matches its package structure). If you have a Clojure namespace with -
in its name,
the corresponding folder will have _
in its name.
* test
is where your Clojure test code lives. It’s a common convention that if your source file is foo/bar/baz.clj
which will have a namespace of foo.bar.baz
, then the tests for that code will live in foo/bar/baz_test.clj
with
a namespace of foo.bar.baz-test
. We have hello/controllers/main_test.clj
which contains tests for the source code
in hello/controllers/main.clj
.
If you run lein test
in the 6helloclojure
folder, you’ll see:
lein test hello.controllers.main-test
lein test hello.services.greeter-test
Ran 2 tests containing 3 assertions.
0 failures, 0 errors.
We’ll take a look at that in a minute.
Let’s start with the CFML files and look at Application.cfc
first, then the views
folder. As usual index.cfm
is an empty file.
Application.cfc
There are a few items of note here, and the first is that we specify diComponent
as "framework.ioclj"
to tell FW/1 that we want to use ioclj.cfc
rather than the default ioc.cfc
for the Dependency Injection component (the bean factory). ioclj.cfc
extends DI/1 and
provides the Clojure-specific magic.
Next we specify diLocations
as the full filesystem path of the current folder. In a CFML / Clojure application, you need to tell the bean factory
about two things: where to find your project.clj
file and where to look for your CFML beans (if any). Locations are specified as
either a comma-separated list of file paths, or an array of paths, and one of them must specify the exact file path to where project.clj
lives. That will also be
searched (recursively) for CFCs so you can store both your Clojure code and your CFML beans in the same tree structure if you wish, or
you can store them separately and provide both file paths in diLocations
.
The other code of note is that setupRequest()
reloads the Clojure code whenever the framework itself is reloaded.
Normally, in
a FW/1 app, you can specify an application reload and your bean factory is recreated. Because of the way Clojure code is compiled and loaded
into the JVM, reloading your bean factory is not sufficient to force a reload of those parts of the JVM, so you need to do this programmatically
somehow. Note that this will only reload the namespaces that follow the FW/1 conventions to be discovered. See below for more on this.
views
This is a regular FW/1 views folder, containing a subfolder for each section of the app (just main
in this case) and a file for each item (there are
three views here). As expected we have a main.default
view and a main.error
view which are basic defaults for FW/1 applications. We also have
a main.stopped
view. We’ll see how each of these is used when we look at the main
controller.
The default
view references rc.greeting
which we’ll see being set up in the main.clj
controller below, and it also gets a greeterService
from
the bean factory and calls a function in that. We’ll see where greeterService
comes from below as well.
src/hello/controllers
In this folder we have a single Clojure file, main.clj
. As you might guess from the file path, this is our application controller. Inside you’ll
see a namespace declaration (the ns
expression) and four functions which represent our handlers.
As with CFML controller functions, each function is passed an argument called rc
which is the request context. Unlike CFML controllers
which might modify elements of the rc
struct directly,
Clojure controllers return an updated version of the rc
data structure to the framework.
In the default
handler, we get the :name
element of the rc
and we return rc
with an additional element called :greeting
. In Clojure,
(:foo bar)
is roughly equivalent to CFML’s bar.foo
, and (:foo bar "baz")
is similar to:
structKeyExists( bar, "foo" ) ? bar.foo : "baz"
So default
passes rc.name
(or "anonymous"
if name
isn’t present in rc
) to the greet/hello
function and then stores the result in
the greeting
element of rc
. Note that the assoc
function (pronounced assosh like the word associate) return a new struct with the
key added — it does not modify the original struct. This seems very strange at first but you’ll get used to it and it’s very powerful (and
very safe) since rc
is immutable. We’ll look at where greet/hello
comes from in a minute.
Next we have the do-redirect
handler. Yes, Clojure functions can have -
in their names. The standard naming convention in Clojure is words-like-this
rather than wordsLikeThis or WordsLikeThis. It’s a long-standing Lisp tradition. Yes, it’s strange but you’ll get used to it and you’ll
soon find it more readable than CamelCase. Anyway, this handler tells FW/1 to redirect to main.default
with the specified query string.
Adding a key called :redirect
to rc
is the equivalent of calling variables.fw.redirect()
in a pure CFML FW/1 app. All four arguments
to the redirect()
function can be specified as keys in the :redirect
struct (:append
, :preserve
, :queryString
, :statusCode
).
Then we have the stop-it
handler. By the way, the URL actions that correspond to do-redirect
and stop-it
are do_redirect
and
stop_it
respectively, following the filesystem convention of swapping _
for -
in Clojure. This handler tells FW/1 it wants to
abort the controller cycle and also set the view to the main.stopped
action. Adding a key called :abort
with a value of :controller
is equivalent to calling variables.fw.abortController()
. Adding a key called :view
is equivalent to calling
variables.fw.setView()
. You’ll note that assoc
can take any number of key/value pairs and add them all into the given struct.
Finally we have the json
handler. By this point, it won’t surprise you to learn that this tells FW/1 to render the specified data
as JSON. The Clojure struct {:a 1 :b "two" :c [3 4 5]}
is equivalent to the CFML struct {a : 1, b : "two", c : [3, 4, 5]}
.
src/hello/services
In this folder we have a single Clojure file, greeter.clj
. As with the controller convention, the file path tells FW/1 that this is
a service (and it would be autowired into any CFML code that declared property greeterService;
as a dependency). This can also be
pulled from the bean factory as "greeterService"
, as seen in the main.default
view file.
There’s a single function hello
in here that takes a string and returns it wrapped with "Hello "
and "!"
.
test/hello
Finally, we’ll look at the tests, first for the main
controller, then the greeter
service.
In controllers/main_test.clj
, we have one test function default-item-test
which contains two related
tests. The arrow syntax means “take this thing and pass it through these functions” so:
(-> {} default :greeting)
takes an empty struct and passes it as the first argument to the default
function (our handler method being tested) and then
pass the result to the :greeting
function — remember that (:greeting my-struct)
is like my_struct.greeting
in CFML. So
this tests that if the rc
is empty and you run main.default
you get a new key called :greeting
whose value is "Hello anonymous!"
.
The second test checks that if rc
contains a :name
element, you get back the appropriate greeting based on the value of that.
The (testing "label" ...)
expression can have multiple is
tests in it, even tho’ ours do not.
In services/greeter_test.clj
, we again have one test function hello-test
that verifies the hello
function does what we expect.
FW/1 Conventions with Clojure
The naming and file path conventions for how you structure your Clojure code for use with FW/1 should be familiar to you if you’ve already used DI/1 in the past: plural folder names, containing “components”, become beans named for the component, with a suffix that is the singular of the folder name:
src/hello/controllers/main.clj
–>mainController
src/hello/services/greeter.clj
–>greeterService
FW/1 requires that there are at least three segments in a name for this convention (so just src/controllers/main.clj
would not
match the convention, but src/hello/admin/controllers/user.clj
would match and become userController
). An additional restriction
is that the filename + suffix must be unique across your whole application (within the Clojure code (so also having
src/hello/public/controllers/user.clj
would conflict with src/hello/admin/controllers/user.clj
).
Aside: You can have additional Clojure code that doesn’t follow this convention, but the bean factory reload()
function only attempts to
reload Clojure files that it “knows” about via this convention. You can explicitly reload others — if you allow for a URL variable that can
be passed to the reload()
method of the bean factory, identifying a single namespace —
but there are some subtleties there which are beyond the scope of this
documentation (if you want to learn more, read the clojure.core/require docstring
and know that reload("all")
does (require ... :reload)
on each namespace covered by the convention but
(require ... :reload-all)
for an explicitly provided namespace).
What is ns all about?
Probably the most complex and confusing aspect when you are first learning Clojure is the ns
expression. ns
serves two main purposes:
- It declares the namespace in which the code in a given file lives.
- It declares what additional namespaces you depend on and how you’re going to access functions in them.
Think of a namespace as a “package” or “module”. The default convention in Clojure is that the namespace matches the filesystem path below your src
or test
folder, except that -
in a namespace identifier matches _
in the file path. Technically, a namespace can be implemented across multiple
files but it isn’t very common to see that, so don’t worry about it.
In the 6helloclojure
example, you’ll see hello.controllers.main
for src/hello/controllers/main.clj
and hello.controllers.main-test
for
test/hello/controllers/main_test.clj
. If you follow this basic convention, you won’t go wrong. If your ns
declaration doesn’t match the
filesystem path, you can get strange errors when you attempt to access it. Think of it much like the dotted-path used to access CFCs in CFML.
The second important part of ns
is the list of namespaces your code :require
s. There are two basic forms here:
[some.namespace :as alias]
which lets you usealias/name
as a way to reference any functions defined insome.namespace
.[some.namespace :refer [fn1 fn2]]
which lets you usefn1
andfn2
directly fromsome.namespace
without a prefix. The shorthand:refer :all
brings in every function from that namespace, and is generally only used in test code.
Prefer the first form — which you see in hello.controllers.main
where hello.services.greeter
is given an alias of greet
so that
the controller can call greet/hello
.
You’ll use the :require
expression to bring in Clojure standard libraries, 3rd party Clojure libraries, and parts of your own code. For most
3rd party libraries, you’ll also need to add an entry to :dependencies
in your project.clj
file in order to tell Leiningen that you
need that library downloaded. We’ll see this when we learn about database access below.
I recommend writing your required namespaces in alphabetical order — most production Clojure code relies on quite a long list of other namespaces so organization is important.
You might think this sounds a bit like import
statements in Java and you’d be right, except that :require
is purely for Clojure code.
There is another form for importing Java classes, called :import
, but Java interop is a whole other subject and you should consult a
Clojure book or the online documentation for more details about that.
Building Your Own CFML / Clojure Application
Since we want to focus on the Clojure aspect of a combined CFML / Clojure project, we’ll start out by creating a Clojure project, and adding the necessary FW/1 CFML files to it in order to create a web application.
We will build a very simple task manager, backed by a database. We will initially create a CFML controller and write a Clojure service to interact with the database, then we’ll replace the CFML controller with a Clojure controller to wrap things up.
Creating the Clojure project
Our Clojure code doesn’t need to be in our CFML webroot so just pick a folder and we’ll create a new Clojure application, in which we’ll write our task manager code:
lein new app taskmanager
This will create a folder called taskmanager
containing a bare bones Clojure project. It’ll have a -main
function so we can use it to run specific operations from the command line, and it’ll have tests we can run to validate our code.
Accessing a Database from Clojure
In order to access a database (via JDBC) from Clojure, you will first need to update your project.clj
file to include
dependencies on Clojure’s JDBC library and what your choice of JDBC driver is. For now we’ll use Apache Derby but if you
look at the java.jdbc page on GitHub, you’ll see links to several other common
database drivers (if you use SQL Server, you’ll find it easiest to use the jTDS driver to get started!).
Edit project.clj
and update the :dependencies
section to include:
[org.apache.derby/derby "<IP_ADDRESS>"]
[org.clojure/java.jdbc "0.3.7"]
You’ll now have a vector with three vectors inside it like this:
:dependencies [[org.apache.derby/derby "<IP_ADDRESS>"]
[org.clojure/java.jdbc "0.3.7"]
[org.clojure/clojure "1.6.0"]]
Now run lein repl
and we can try this out. As the REPL starts up, it will download the new
libraries and then you’ll get the prompt. Let’s create test database and write and read some
data with it:
user> (require '[clojure.java.jdbc :as sql])
nil ;; now we have the JDBC library loaded with an alias
user> (def db {:subprotocol "derby" :subname "cfmltest" :create true})
#'user/db ;; this is our database spec
user=> (sql/execute! db [(str "CREATE TABLE task ("
"id INT GENERATED ALWAYS AS IDENTITY,"
"task VARCHAR(32),"
"done BOOLEAN DEFAULT false"
")"])
[0] ;; success! we created the task table
user> (sql/insert! db :task {:task "Test database"})
((:1 1M)) ;; the sequence of inserted keys:
;; there is just one key, labeled :1, with the value 1
;; the M indicates a BigDecimal value
user> (sql/insert! db :task {:task "Read some data"})
((:1 2M)) ;; generated key is 2 this time
user> (sql/query db ["SELECT * FROM task WHERE NOT done"])
({:done false, :task "Test database", :id 1} {:done false, :task "Read some data", :id 2})
;; our two records came back, let's update one
user> (sql/update! db :task {:done true} ["id = ?" 1])
(1) ;; one row was updated
user> (sql/query db ["SELECT * FROM task WHERE NOT done"])
({:done false, :task "Read some data", :id 2})
;; yup, that's our only task not done now
user> (sql/update! db :task {:done true} ["id = ?" 1])
(1) ;; one row was updated
;; let's delete our table to clean up
user> (sql/execute! db [ "DROP TABLE task"])
[0] ;; success! we dropped the table
Some notes on the syntax:
- Functions that modify the database end in
!
to indicate they have side effects - SQL and any parameters are specified together in a vector:
["a SQL string" param1 param2 param3]
- Use
?
in the SQL string to indicate a parameter - A
PreparedStatement
is used for all operations
execute!
can be used for arbitrary SQL or DDLquery
is intended forSELECT
only and returns a result setinsert!
inserts a new row from a hash map (struct)update!
sets the column values shown in the hash map for all rows that match theWHERE
clause provided in the vector, so it is shorthand for["UPDATE table SET column values WHERE clause" param1 param2 param3]
Adding the initial CFML files
Writing a Clojure Service
Writing a Clojure Controller
A Clojure Primer
To learn about Clojure in any depth, I’d recommend you go through the More Stuff to Read section at the end of this page, but I’m going to give you a quick run through of some useful basics that should get you up and running more quickly.
As I claimed earlier, Clojure is a very simple language with only a few pieces of syntax:
- A semicolon introduces a comment. Typically a single semicolon is used for an end of line comment and a double semicolon is used for a whole line produces
(func arg1 arg2 arg3)
represents a function call (with three arguments). You can use commas if you want but they are just whitespace:(func arg1, arg2, arg3)
. Most Clojure developers omit commas in function calls. Almost everything in Clojure is a function call. A few things that look like function calls are actually “special forms” but you can pretend they’re really function calls until you get a bit more proficient (a function call evaluates all its arguments before the call, a special form may not evaluate its arguments until it needs them).a
is a symbol — a variable or function name — that evaluates to whatever it has been bound to. Seedef
,defn
andlet
below.:a
is a keyword — it evaluates to itself — that is a bit like a string except it is cached (so two:a
s in different parts of your code and the exact same thing and can be compared for identity based on their address, not their value). Keywords are commonly used as the keys in a hash map (see below).[1 2 3 4]
represents a vector (array) with the specified elements. You can use commas if you want, but they are just whitespace:[1, 2, 3, 4]
. Most Clojure developers omit commas in vectors.{:a 1, :b 2, :c 3}
represents a hash map (struct) with keys:a
,:b
,:c
and values1
,2
,3
respectively. The commas are just whitespace but some Clojure developers use them anyway to clearly delineate pairs.#{1 2 3}
represents a set of values. If you add4
to that set you get#{1 2 3 4}
but if you add1
,2
, or3
to it, it remains unchanged because those values are already in the set. CFML doesn’t have a set data type, but you might simulate it with a struct whose values aretrue
(or some other arbitrary value) and the presence or absence of a key says whether it’s in the set or not.
That’s about it. When you learn about macros (in one of the Clojure books), you’ll encounter a few new pieces of syntax but you don’t need that to get going.
Some Basic Clojure Functions
Functions all the way down. Some functions / special forms are very important so I’m going to go through some of those here.
def
, fn
, and defn
The def
special form creates a global (top-level) binding of a name to a value within the current namespace:
(def a 42)
;; binds a to the value 42 -- technically a is a Var
a
;; produces 42
The fn
special form creates an anonymous function:
(fn [a b c] (* a b c))
;; creates a function with three arguments a, b, and c
;; that multiplies those three values together
Anonymous functions are often used as arguments to other functions:
(map (fn [x] (* x 2)) [1 2 3 4 5])
;; produces (2 4 6 8 10)
Strictly speaking, a function can contain more than one expression: they are all evaluated in order, but only the value of the last expression is returned. The others are throw away. So why have multiple expressions? You might have some operations that cause side effects, such as logging to file or writing to a database, and you want to evaluate those for their effects but not necessarily their result.
You can bind a name to an anonymous function, to create a named function:
(def twice (fn [x] (* x 2)))
This is so common that defn
exists as a shorthand for it:
(defn twice [x] (* x 2))
Documentation is built into Clojure and you can (and should) provide a “docstring” for all your functions that say what they do and possibly provide example usage:
(defn twice "Doubles its argument." [x] (* x 2))
You’ll often see this written on multiple lines like this:
(defn sum-of-squares
"Given two values, return the sum of their squares."
[a b]
(+ (* a a) (* b b)))
It’s common for functions to have short argument names because each function should be very short and simple, and the function names should be descriptive.
The docstring — and the source code — of functions is available in the REPL (and in any Clojure editor that supports live evaluation) through
the doc
— and source
— functions (in the clojure.repl
namespace). This makes it very easy to experiment with new libraries since all
of the documentation and source code is right there at your fingertips!
if
, when
, and do
In CFML we have an if
statement. If the condition is true, the first group of statements is executed, else the second group of statements
is executed. In functional languages like Clojure, if
is an expression (a special form) and it takes a condition and two expressions.
If the condition is true, the first expression is evaluated, else the second expression is evaluated. It’s more like the tertiary operator
? :
in CFML.
Also, it’s important to note that Clojure has strong views on what is true and false. You’ll hear of “truthy” and “falsey” in the Clojure
world because Clojure treats everything as true except for false
and nil
. In particular, that means that 0
is true, unlike in CFML.
The reason for this is an idiom called “nil punning”: it’s common for Clojure functions to return nil
for “no such value” instead of
throwing an exception, and allowing nil
to mean false makes it easy to test for such things:
(if (:name rc) (str "Hello " (:name rc) "!") "Who?")
In CFML, if you did rc.name
and it wasn’t present, you’d get an exception. In Clojure, (:name rc)
simple returns nil
if there’s no
such key and you just test for that. You can prevent repetition of (:name rc)
with if-let
— see below.
If you don’t have an “else” expression (and want to return nil
instead), use when
instead of if
:
(when (:name rc) (str "Hello " (:name rc) "!"))
If the condition is “falsey”, you get nil
back. Be aware that when
allows multiple expressions, just like fn
above and let
below, and it evaluates
all of them but only returns the value of the last expression.
If you want to evaluate multiple expressions in an if
, you need do
:
(if some-condition
(do
(log-something)
(update-the-database)
"Result!")
"Failure!")
do
can be used where any single expression is accepted and behaves like the body of fn
.
It might not surprise you to learn that when
is really defined in terms of if
and do
something like this:
(when condition expr1 expr2 expr3)
;; is treated like
(if condition (do expr1 expr2 expr3) nil)
let
and its cousins
Global bindings are fine for functions that you want exposed to the world, but you often want local bindings inside a function. That’s what the
let
special form is for:
(defn sum-of-squares
"Given two values, return the sum of their squares."
[a b]
(let [a-squared (* a a)
b-squared (* b b)]
(+ a-squared b-squared)))
let
is following by a vector of bindings — pairs of symbol and expression — and then one or more expressions. It creates a local binding
for each pair by evaluating the expression and binding it to the name (symbol), and then it evaluates the expressions in its body and returns
the last expression’s value (in the same way function bodies are evaluated).
There are several variants of let
that are useful. The most common is probably if-let
:
(if-let [name (:name rc)]
(str "Hello " name "!")
"Who?")
Unlike let
, if-let
only allows one binding pair followed by two expressions. If the binding is “truthy”, the first expression will be evaluated,
else the second expression will be evaluated. Note that the bound symbol is only available in the first expression!
loop
and recur
Since I often tell people that functional programming means no mutable variables and therefore no loops, it might surprise you to learn that
Clojure has a loop
construct. It isn’t quite what it seems!
First, let’s look at a recursive function:
(defn fact [n] (if (zero? n) 1 (* n (fact (dec n)))))
;; (fact 1) => 1
;; (fact 3) => 6
;; (fact 5) => 120
Because it is recursive, it creates a new stack frame for every call to itself. You can still call it with some big numbers but eventually you will get a stack overflow:
(fact 1000N) =><PHONE_NUMBER>77093773543702433923003985719374...
(fact 10000N) => StackOverflowError java.math.BigInteger.valueOf (BigInteger.java:1098)
There’s a technique called tail recursion that allows some languages to evaluate recursive functions without needing stack frames. You
have to rewrite the function to ensure the recursive call is in the tail position (the fact
call above is nested inside multiplcation).
Often, you need to create a helper function:
(defn fact-helper [n prod] (if (zero? n) prod (fact-helper (dec n) (* n prod))))
(defn fact [n] (fact-helper n 1))
This produces the same results as fact
above, but now the recursive call to fact-helper
is in the tail position. Clojure doesn’t optimize this
directly but provides recur
for you to tell the compiler you want it optimized — and to verify you really are using tail recursion:
(defn fact [n] (if (zero? n) 1 (* n (recur (dec n)))))
;; CompilerException: Can only recur from tail position
But:
(defn fact-helper [n prod] (if (zero? n) prod (recur (dec n) (* n prod))))
(defn fact [n] (fact-helper n 1))
(fact 10000N) =><PHONE_NUMBER>9170545189064132121198688901480514...
You can see that recur
replaces the recursive call, but what it’s really doing behind the scenes is rebinding the function arguments
and “jumping” back to the beginning of the function, to avoid a function call altogether. Since this is really a loop-with-rebinding,
Clojure provides a loop
construct that lets you do this directly:
(defn fact [n] (loop [n n, prod 1] (if (zero? n) prod (recur (dec n) (* n prod)))))
This single function is identical in behavior to the fact
/ fact-helper
pair shown immediately above. You can see how the loop
binding behaves just like the initial call to fact-helper
, binding fact
s argument n
to the local symbol n
and 1
to the local
symbol prod
.
Useful core Functions
Since Clojure is all about data structures, there is a rich selection of functions that operate on them. Some of the valuable ones to know are:
(first [1 2 3 4])
returns the first element of a sequence:1
(rest [1 2 3 4])
returns the rest of a sequence:(2 3 4)
The rest
of a single element sequence is an empty sequence — ()
— and the rest
of an empty sequence is also an empty sequence!
(seq some-collection)
returns a sequence ofsome-collection
s elements if it is non-empty, else returnsnil
It is common to test for empty sequences with if (seq some-collection)
.
(cons 1 [2 3 4])
returns a new sequence with that element added:(1 2 3 4)
(assoc {:a 1} :b 2)
returns a new hash map with the key associated to the value:{:a 1, :b 2}
(dissoc {:a 1, :b 2} :a)
returns a new hash map with the key removed (dissociated):{:b 2}
(map inc [1 2 3 4])
returns a new sequence with the function applied to each element:(2 3 4 5]
(filter even? [1 2 3 4])
returns a new sequence containing just the elements for which the predicate is “truthy”:(2 4)
(reduce + 0 [1 2 3 4])
returns the value computed by repeatedly applying the function to the initial value and each element of the sequence:10
If the initial value is omitted, the first element of the sequence is used so:
(reduce func some-collection)
;; is the same as
(reduce func (first some-collection) (rest some-collection))
The project.clj
File
The piece of project.clj
you’ll touch most often is the :dependencies
entry. This is a list of all the libraries your
program needs and the versions of each you want to use:
:dependencies [[org.clojure/clojure "1.6.0"]
[clj-time "0.9.0"]]
Libraries come from two locations by default: Maven Central and Clojars.
Most Clojure libraries tell you what to put in project.clj
to pull them in so you mostly won’t need to care which location
they actually come from but it’s instructive to at least know how to read this stuff and how to search for libraries yourself.
Each entry is called a “coordinate” and contains a “group ID” and an “artifact ID”. A single name just means that the group ID
and artifact ID are the same thing (so clj-time
is shorthand for clj-time/clj-time
).
To search Maven Central for org.clojure/clojure
you would use the query g:"org.clojure" AND a:"clojure"
which asks for
group ID org.clojure
and artifact ID clojure
. Right now there are 74 versions of that library on Maven Central and the
latest is 1.7.0-RC1
but if you click the All (74)
link, you’ll see the most recent non-prerelease version is 1.6.0
which is what Leiningen puts in project.clj
by default.
On the other hand, clj-time
comes from Clojars because it is a community project. If you search for clj-time
you’ll
get a lot of results but most of them are not canonical versions. The most recent canonical version is https://clojars.org/clj-time but
there are other, earlier canonical versions, such as https://clojars.org/backtype/clj-time so you need to be a bit careful. If in doubt,
get on IRC, Slack, or the mailing list and ask!
For an overview of all the possible settings in project.clj
, take a look at the Sample project.clj File on GitHub.
About Functional Programming
Functional programming isn’t new. It’s origins lie in Lisp which was created in the 1950’s and is the second-oldest computer language (second only to FORTRAN). Throughout the 70’s and 80’s a lot of functional languages were created, mostly in academia, to study the benefits of the functional style, as well look at levels of expressiveness in programming languages. Classic functional languages include Standard ML, Miranda, and Haskell. Haskell was a result of the proliferation of similar functional languages being created by each university in England (and elsewhere). It was decided that a single, committee-designed functional language should exist that included the best ideas of all of the diverse variants out there. Haskell is probably the most widely used language today from that era. It has an extremely powerful type system and a very strong view of purity — lack of side effects — but it has been used extensively over the last 25 years in industry as well as academia.
The recent resurgence of functional programming has shown itself in languages like F# from Microsoft, Scala, and Clojure, even Rust, as well as some compile-to-JS languages like Elm and PureScript. The reason behind this resurgence is that immutable data structures and pure functions offer the ability to write concurrent code a lot more easily and lot more safely than the mainstream OOP approach. And we need concurrency in order to take advantage of multi-core machines, now that we’re no longer seeing continued speed increases in individual cores like we have for the last several decades.
While it may seem obvious that functional programming leans heavily on functions as building blocks, the real core values of
functional programming are avoiding mutable data and avoiding side effects in functions. The more that you can push side effects
to the edges of your program, the more of your code becomes pure functions that can be easily reasoned about, easily tested, and
often easily reused. Functional programming focuses on small, pure functions that can be composed to create larger pieces of
functionality. If you have a function inc
that adds one to its argument and a function twice
that doubles its argument, then
(comp twice inc)
is a function that adds one to its argument and then doubles it: functions are like Legos that you can easily
assemble to build products.
Immutable or Persistent Data Structures
In the context of functional programming, you’ll hear a lot of talk of immutable data structures and persistent data structures. In OOP languages, you typically perform operations on a data structure to modify it in place. That means you can’t safely share it with other pieces of code, especially across multiple threads. By constrast, in a functional language, when you perform an operation on a data structure, you get a new data structure back, that shares as much structure as possible with the original data structure — and that leaves the original data structure unchanged.
While they are designed for efficiency, it is usually at scale, rather than for small examples. In Clojure, many data structures are “chunked” internally into groups of 32 elements. A vector of 100 elements is going to be four chunks and is optimized for adding elements to the end of the vector. A list is optimized for adding elements at the start of it. A hash map is also chunked and optimized for adding elements in random locations. They are also optimized for different patterns of access: a list is optimized for purely sequential access, a vector for indexed (random) access, and a hash map for keyed (random) access.
Clojure and Scala share a lot of heavily optimized implementation details in their persistent data structures.
Despite all this efficiency, you still need to think about how to use data structures, and there are going to be some algorithms where bashing a data structure in place is just going to be faster. It won’t be as safe, just faster. Clojure is fine with the idea of localized mutation and has versions of vectors and hash maps that are optimized for that purpose (known as transients).
The most important aspect of these data structures in Clojure is the set of abstractions over them, including “sequence” and “associative”. These are uniform ways to think about data structures as just sequences of data (accessed in order, or randomly by keys), no matter what their actual implementation is, so that you can apply all of Clojure’s core functions to arbitrary data structures in standardized ways. The lack of unique types for each data structure you use means that you don’t need unique functions to operate on them all. A function that operates on a sequence can accept any data structure that supports the sequence abstraction. A function that operates on an associative collection can accept any data structure that supports the associative abstraction.
For example, a result set from a database query is simply a sequence of associative collections. It can be mapped, filtered, reduced using standard functions and its rows transformed using any of the standard associative functions. This allows abstraction over different data stores as well since, from Clojure’s point of view, MySQL and MongoDB look very similar.
Functions as Building Blocks
I’ve already emphasized that functional programming favors small, simple, pure functions but you can do that sort of functional decomposition in most languages. Many modern languages allow you to write anonymous functions and pass them around as arguments, as well as return them from functions. Even with those features available, it takes a while to shift from an imperative style with some functions being passed around to a functional style where functions are your primary abstraction.
You’ll hear the term “higher order functions” a lot but all this means is a function that accepts a function as one (or
more) of its arguments or a function that returns a function as a result. You’ll see the former in CFML with the new
map
, filter
, and reduce
member functions — or perhaps you’ve seen it in JavaScript.
Consider these two functions (in CFML):
function saveStuff( data ) {
if ( validStuff( data ) ) {
dbSave( "stuffTable", data );
} else {
writeLog( "Invalid stuff, not saved" );
}
}
function saveThing( data ) {
if ( thingIsValid( "all", data ) ) {
dbSave( "thingTable", data );
} else {
writeLog( "Invalid thing, not saved" );
}
}
Now, consider this function:
function saveValidData( validator, type, data ) {
if ( validator( data ) ) {
dbSave( type & "Table", data );
} else {
writeLog( "Invalid #type#, not saved" );
}
}
This is probably not a transform you would do in CFML but it’s a natural one in a functional language, because you would see the commonality and want to remove the duplication:
var saveStuff = function( data ) { return saveValidData( validStuff, "stuff", data ); };
var saveThing = function( data ) {
return saveValidData(
function( data ) { return thingIsValid( "all", data ); },
"thing",
data
);
}
Now imagine you had a higher order function called
partial
that accepted a function and one or more of its arguments and returned a new function that accepted
the rest of its arguments and then called it, it would be very natural to make this transform and then write:
var saveStuff = partial( saveValidData, validStuff, "stuff" );
var saveThing = partial( saveValidData, partial( thingIsValid, "all" ), "thing" );
This is much cleaner, especially if you had quite a few of these “save data if valid” variants.
Another way to write this without partial
would be:
function thingIsAllValid( data ) { return thingIsValid( "all", data ); }
function saveValidData( validator, type ) {
// accept validator and type, return a function that accepts data
return function( data ) {
if ( validator( data ) ) {
dbSave( type & "Table", data );
} else {
writeLog( "Invalid #type#, not saved" );
}
}
}
var saveStuff = saveValidData( validStuff, "stuff" ); // returns a function
var saveThing = saveValidData( thingIsAllValid, "thing" );
You could also write “thing” validation like this:
function thingValidator( scope ) {
return function( data ) {
return thingIsValid( scope, data );
}
}
var saveThing = saveValidData( thingValidator( "all" ), "thing" );
By making our functions more flexible in how they accept arguments, we make it easier to reuse them. This is functional thinking!
In Clojure we can define a function with multiple argument lists so this becomes even easier:
(defn thing-is-valid
([scope] (fn [data] (thing-is-valid scope data)))
([scope data] ... return true or false ...))
(defn save-valid-data
([validator type] (fn [data] (save-valid-data validator type data)))
([validator type data]
(if (validator data)
(db-save (str type "Table") data)
(write-log (str "Invalid " type ", not saved")))))
(def save-stuff (save-valid-data valid-stuff "stuff"))
(def save-thing (save-valid-data (thing-is-valid "all") "thing")
No need for partial
(although Clojure has that built-in), no need for helper functions.
All You Know About OO Programming is Wrong
I learned old-fashioned imperative procedural programming first. I learned BASIC, assembly language, Pascal and later COBOL and FORTRAN. Although OOP has its roots back in the 50’s and 60’s (ironically, with Lisp, just like FP has its roots in Lisp), it didn’t really go mainstream until the mid-to-late 80’s with the arrival of Eiffel and C++. I learned a lot of FP during the 80’s but since it wasn’t going mainstream and OOP was, I switched horses to stay employable. By the time Java appeared, OOP had become the default “standard” way to build software, even though C++ and Java were not at all what Alan Kay had in mind when he coined the phrase “object-oriented”.
What most developers know as modern OOP focuses on polymorhism, inheritance, encapsulation and objects that have both state and behavior bundled together. You construct an object with its initial state. You run a bunch of methods on it, interacting with other objects, to modify its state, and then you query the object to get that state back out.
A common idiom in the OOP world for collections is an iterator. In CFML this shows up in query objects. As you loop
over the iterator, it changes its state to refer to successive elements of the underlying collection. A CFML query
refers to successive rows of the result set as you loop over it and the currentrow
element is updated at each
iteration. Instead of a result set looking like a sequence of rows, we’re used to looking at a snapshot of the “current
row” — and that’s what iterators do to us for collections as well.
In addition, instead of processing collections holistically to produce either new collections or specific results, we’re using to iterating through the elements and either modifying them in place or performing side effecting operations along the way.
What makes this problematic is that you can’t then easily run this code concurrently to take advantage of multiple cores: code that mutates collections in places or generates side effects is rarely thread safe.
In other words, mutable state is bad.
What about OOP’s other basic tenets?
Why do you encapsulate data? The primary reason is so that you can control mutation of that data. If your data is immutable, encapsulation is no longer needed for that. The other argument for encapsulation is so that you can change the representation of the state without affecting your clients. In a functional world, if you change your representation, you can always provide a function that transforms it to the original structure and then simply compose that transformation with any client function that needs to access it. That composed client + transform can be refactored away over time as the client transitions to the new API. In other words, your data is your API and there’s no need to encapsulate it (at least, not for the traditional OOP reasons).
Inheritance? Inheritance exists in OOP because the notion of data types is inherently tied to classes and objects. Inheritance represents a strong coupling between an implementation and an interface or between one implementation and another related implementation. It exists because there’s no way to separate out the notion of data types and their relationships from the class implementation relationships. Needless to say, in a functional world, you can choose to have relationships between data types as you need them, without being forced to create relationships between data representations. In Clojure, in particular, you can create hierarchies of types independent of any data and use those to guide function call dispatching.
Which brings us nicely to polymorphism! Polymorphism is great. It’s very useful. Unfortunately, in OOP it is tied to inheritance which, as we’ve just seen, is all about coupling when you’re dealing with classes. If you only ever use interfaces and pure implementations, you can free yourself from some of the problems of coupling forced on you by OOP, but you still get stuck if you have a class (implementation) that isn’t declared to implement an interface that you need to use, even though it has the right methods. Nor can you easily take an arbitrary existing class and make it implement your interface (you can extend the class and implement your interface, only if the class is not final in Java, for example). In addition to all that, polymorphism in OOP is only effective on the first argument — the object type itself — which means that when faced with more complex problems, you have to resort to design patterns like Visitor and implement double dispatch. But then you are forced to modify the “visited” class every time you want to visit it with a new class. What you really need there is polymorphism based on multiple arguments. Fortunately, you can have that in functional programming.
So what have we learned?
Polymorphism is very limited in OOP but can be very powerful in FP once we remove the restriction of single dispatch and the coupling to a static inheritance hierarchy: this gives you ad hoc or a la carte polymorphism.
Inheritance as seen in OOP is essentially an implementation detail. You can have ad hoc inheritance in FP, which provides expressiveness where you want it and avoids boilerplate and coupling where you don’t.
Encapsulation is required in OOP when you have mutatable state and is also needed in order to allow changes in implementation. In other words, encapsulation is also essentially an implementation detail. FP solves this by making data immutable and making functions easily composable.
Mutable state is just bad. It prevents refactoring to leverage concurrency, it leads to hard to find bugs in complex programs, and it also erases any notion of time in your program (because you have only the current version of the state, rather than the series of values that were transformed to get to that point). FP solves that by removing mutability.
If FP is so great, why aren’t we all using it already?
Good question. The OOP industry is vast. Design Patterns, training and consulting, higher education based on teaching OOP (ironically after supplanting a lot of courses that taught FP!), testing, tooling, IDEs. The momentum behind OOP is huge and the inertia of industry to keep doing things the way they know is almost overwhelming. Yet we see functional features in nearly every new language being designed, we see functional features being added to nearly every existing language over time, we see the functional style of programming being advocated even in traditional languages — with less reliance on mutable state. Most of that pressure is coming from the need to do more concurrency and to avoid the bugs that arise from side-effecting code. In other words, a lot of people already know that FP is a better way to solve a lot of problems.
Remember that modern OOP — as enshrined in Java and C# particularly — is not what the originators of OOP had in mind. They imagined objects as proxies for real world elements such as displays and control devices, that objects would be coarse-grained and communicate by sending messages between themselves.
More Stuff to Read
Once you’ve got a taste for Clojure, there are lots of online resources and a host of great books you can read. Here’s a small sample, roughly in order of approachability:
- The online tutorial for learning Clojure, no installation required: http://www.tryclj.com
- The “4Clojure” puzzles online: https://www.4clojure.com
- These quickly get hard enough that you’ll want a REPL open locally to play with!
- The Clojure Koans: http://clojurekoans.com
- You need at least Java, Leiningen, and Git installed for these.
- Some great books to read:
- Clojure Programming http://www.clojurebook.com followed by
- The Joy Of Clojure http://www.joyofclojure.com :)


| Full Statistics for August 2007 |
|---|
| Monthly Summary | |||
|---|---|---|---|
|
Total hits (any request) Total files sent (Code 200) Total files saved by cache (Code 304) Other response codes (see below) |
100.00% 89.91% 3.23% 6.85% |
30614 27526 990 2098 | |
|
Total pageviews Remaining responses |
61.30% 38.70% |
18766 11848 | |
| Total KB requested Total KB transferred (Code 200) Total KB saved by cache (Code 304) |
|
100.00% 96.06% 3.94% |
467873<PHONE_NUMBER>6 |
| Total unique URLs Total unique sites Total user sessions Total unique agents Total unique referrer URLs | 425 1312 1849 366 1925 | ||
| Maximum | Average | ||
|
Hits per day Files sent per day Files cached per day Pageviews per day Sessions per day KB sent per day |
2809 2415 218 1576 189 45858 |
1800 1619 58 1103 108 26439 | |
| Logfile statistics | |||
| Total logfile entries read Total logfile entries processed Empty Request Method |
30632 30614 18 | ||
| Other Response Codes | |||
| Partial Content (Code 206) Moved Permanently (Code 301) Moved Temporarily (Code 302) Bad Request (Code 400) Forbidden (Code 403) Not Found (Code 404) Request Timeout (Code 408) |
55 283 1625 1 1 121 3 | ||
| Request Methods other than GET/POST | |||
| HEAD | 9 | ||
| Hits: | by Day / by Weekday & Hour / by Country / 3D model |
| Items/URLs: | Top Ten / Overview / Not Found / List |
| Client Domain: | Top Ten / Overview / Reverse Domain / List |
| Browser Type: | Top Ten / Overview / List |
| Referrer URL: | Top Ten / Overview / List |
| Summary for 2007 | |
|


{% load staticfiles %}
These are examples of galaxy morphology that are rare, but still important to note when you see them. You can select more than one option if you see multiple features in the same galaxy. Ring galaxies have a bright circle of stars around the edge of the galaxy. Lenses and arcs are curved, detached bands of light that can be caused by gravitational lensing. Irregular galaxies have shapes that are neither smooth ellipses or well-behaved spirals, but look more like a chaotic blob. Dust lanes are thin, dark features across a galaxy that resemble shadows. Overlapping galaxies occur when two galaxies appear to be located at least partially on top of each other, but where you don't see any distortions or features that would indicate a merger. Click to see larger images.


A browser with JavaScript enabled is required for this page to operate properly.
Developed by Safirasoft.com


<category>
The <category>
element represents any category by which a topic might be
classified for retrieval or navigation. For example, the categories could be used to group
topics in a generated navigation bar. Topics can belong to multiple categories.
Category: Prolog (metadata) elements


Commands
A Command is a typed representation of the user's intent in performing an action. As such, it is a simple Data Transfer Object and performs no logic or calculations. It is an instruction to the system to do something.
 Another system can issue commands to our system and is considered a user.
Naming
A command SHOULD be named in the imperative form. It SHOULD also be named in accordance with the intention of the user rather than the anticipated outcome of the command. For example, UpdateShoppingCart is a poor command name. It focuses on what will happen, rather than why the user wants to perform the action. AddItemToShoppingCart better captures what the user wants to achieve, when clicking on an "Add to Cart" button. It is also recommended to distinguish between similar actions that have the same main result. For example, we could add further commands, even with identical structures and handling, to distinguish between AddAccessoryToCart, AddRecommendationToCart, AddWishlistItemToCart and so on, where these are or could be important distinctions in our domain.
Transaction
A command is a transaction. There is no concept of a partially successful command. You MUST structure and handle your commands such that the command succeeds or fails in its entireity. A transaction here is a domain concept, not a technical one. When modelling and naming your commands, you should consider the invariants of your domain and the aggregate root that the command will act upon.
Structure
A command MUST include all necessary information to perform the action. These should be in the form of parameters on the command object.
You may include optional parameters, though it is recommended that you create multiple commands that represent the different states associated
with the optional parameters. It is recommended that you use Concepts and
Value Objects on your commands rather than primitives. This gives a more expressive command and aids in
validation.
Note
For JavaScript, proxy representations can be used for the commands, read more about the mechanism here.


Classes
The following classes are available globally.
-
The
Tink
class encapsulates a connection to the Tink API.By default a shared
See moreTink
instance will be used, but you can also create your own instance and use that instead. This allows you to use multipleTink
instances at the same time.Declaration
Swift
public class Tink
-
An object that you use to authorize for a user with requested scopes.
See moreDeclaration
Swift
public final class AuthorizationContext
-
An object that you use to access the user’s credentials and supports the flow for adding credentials.
See moreDeclaration
Swift
public final class CredentialContext
-
An object that accesses providers for a specific market and supports the grouping of providers.
See moreDeclaration
Swift
public final class ProviderContext
-
An object that you use to create a user that will be used in other Tink APIs.
See moreDeclaration
Swift
public final class UserContext
-
A task that manages progress of adding a credential.
Use
See moreCredentialContext
to create a task.Declaration
Swift
public final class AddCredentialTask : Identifiable
-
A task that manages progress of refreshing a credential.
Use
See moreCredentialContext
to create a task.Declaration
Swift
public final class RefreshCredentialTask : Identifiable
-
A task that handles submitting supplemental information for a credential.
This task is provided when an
AddCredentialTask
‘s status changes toawaitingSupplementalInformation
.When a credential’s status is
awaitingSupplementalInformation
the user needs to provide additional information to finish adding the credential.See moreNote
If the user dismiss supplementing information, by e.g. closing the form, you need to callcancel()
to stop adding the credential.Declaration
Swift
public final class SupplementInformationTask : Identifiable
-
A task that handles opening third party apps.
This task is provided when an
AddCredentialTask
‘s status changes toawaitingThirdPartyAppAuthentication
.When a credential’s status is
awaitingThirdPartyAppAuthentication
the user needs to authenticate in a third party app to finish adding the credential.See moreNote
If the app couldn’t be opened you need to handle theAddCredentialTask
completion result and check for aThirdPartyAppAuthenticationTask.Error
. This error can tell you if the user needs to download the app.Declaration
Swift
public class ThirdPartyAppAuthenticationTask : Identifiable


Please fill in the real information.
Only the SM3 hash of the Identity Information will be stored on the blockchain after checking.
No third party will store your private information.
In BlockImage, you needn't worry about copyright issues and all your works mean a lot.
用户名： James
邮箱：<EMAIL_ADDRESS>收益： James
infoHash： James
| # | 图片ID | 价格 | 状态 | 处理 |
|---|
| # | 图片ID | 价格 | 状态 | 处理 |
|---|


{% extends 'base.html'%} {% import 'macros.html' as macro%} {% block styles%} {{ super() }} {% endblock %} {% block content %} Promotion Pitches Let's promote all our ideas suggestions or anyhting you might be thinking about Add a new Pitch {{macro.displayPitchesInCategories(pitches,3)}} {% endblock %}
Let's promote all our ideas suggestions or anyhting you might be thinking about


Wikipedia: "A JavaScript library is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications."
jQuery is an example of a popular library today. youtube.js is another example of a library, written by Pamela Fox, that contains pre-written JavaScript that you can use.
In the youtube.js library, there are four functions you can use:
youtube.getIdFromUrl(videoUrlOrID)Expects an argument (videoUrlOrID) that is either a youtube video URL or a video ID and returns back the video's ID.
var vid_id = youtube.getIdFromUrl('http://www.youtube.com/watch?v=epUk3T2Kfno'); //vid_id equals 'epUk3T2Kfno' (notice where the ID is in the original url)
youtube.generateThumbnailUrl(videoUrlOrID)Expects an argument (videoUrlOrID) that is either a youtube URL or a ID and returns back the URL of the thumbnail for that video.
var vid_thumbnail = youtube.generateThumbnailUrl('http://www.youtube.com/watch?v=epUk3T2Kfno'); //vid_thumbnail equals 'http://i3.ytimg.com/vi/epUk3T2Kfno/default.jpg' (notice how the video's ID is inserted in the middle of the image url)
youtube.generateWatchUrl(videoUrlOrID)Expects an argument (videoUrlOrID) that is either a youtube URL or a ID and returns back the URL for that video.
var vid_watch = youtube.generateWatchUrl('epUk3T2Kfno'); //vid_watch equals 'https://www.youtube.com/watch?v=epUk3T2Kfno' (notice where the video ID is in the url)
youtube.generateEmbedUrl(videoUrlOrID)Expects an argument (videoUrlOrID) that is either a youtube URL or a ID and returns back the embed URL for that video.
var vid_embed = youtube.generateEmbedUrl('http://www.youtube.com/watch?v=epUk3T2Kfno'); //vid_embed equals 'http://www.youtube.com/embed/epUk3T2Kfno' (notice where the video ID is in the url)


With help of svg
With help of CSS
With help of CSS(pseudo-elements)
With help of CSS
(repeating-linear-gradient)
With help of CSS Paint API
If you can't see anything then watch the log message in console tab in browser devtools)


Hi, I’m Mark Druffel!
I’m a data scientist, I mutate
☕ + 🍺 into code.
Motivation
I have been working in analytics since ~2013. My undergraduate degree was in business and I started my career in financial and IT audit 😴 After a few years, I was lucky enough to land a role managing a Business Intelligence team and my journey in analytics began. Like many data scientists, I started out without the background or formal training so I spent a lot of time learning. I set up this blog as a tool to reflect on that process and share it with the community. I hope the content will be useful to other newcomers and encourage collaboration. If you have any feedback or want to discuss any of the topics please feel free to reach out!
A bit about me
I grew up in Cincinnati, Ohio but I moved to Portland, Oregon by way of Chicago. I work at a boutique management consulting company, Propeller, where I help clients better leverage data in their organizations. The opinions on this site are my own. I am the author of a few small R packages including harvestR & dataPipeline and enjoy discussing data science and technology whenever I get the chance. I am also a sisyphean rock-climber and a cooking / travel enthusiast 🗻
-Mark


Stone(point: Point)
Supertype for SGF Stone types. Game-specific, but always contains a Point.
SGF Stone


This demo uses the Leaflet Basemap Providers plugin to show off several categories of basemaps that are available for web maps.


CRL Concerned Over Lack Of Monitoring Use Of Indigenous Languages In Govt Depts
by NG EditorJOHANNESBURG – The CRL Rights Commission on Tuesday said it was concerned that many government departments didn’t have systems in place to assess whether the public was satisfied with the access to all official languages.
It said that while some departments had language policies, they were lagging behind in ensuring indigenous languages were accorded the same rights and treatment.
The commission held hearings on Tuesday to assess what measures have been put in place to regulate and monitor the use of official languages.
The commission’s Professor David Mosomo said: “Because we think that for the language to flourish and develop, it must be used. If it’s not, it becomes a rank of history.”


INFO3165 Project
Facial Recognition
Upload a new image and it will identify how many people/faces are in the image!
Upload New Photo


Class CBJsonController
Yii controllers exchanging JSON objects.
This base controller class allows developers to write controller actions which expect object parameters and return objects instead of printing/rendering them. It also has a uniform error handling mechanism which converts exceptions and PHP errors to standard-form jsons. The client application can be tuned to properly handle such exceptions.
This approach, apart from making writing actions as if they were naturally called by the client/consumer, allows for proper out-of-the-box documentation (i.e. through apigen).
Action signatures
All restful action signatures:- Accept at most one input parameter object. The input parameter name can be anything since there's at most one parameter.
- Return exactly one output object.
public function actionGetAll(NotificationQueryJson $notificationQuery) { return new NotificationJson(); }
Request/Input Objects
Input parameters are fetched in two different ways:
- Production mode: From the POST body as raw json object.
- Development mode: From the 'jsin' GET parameter as raw json object.
Input object types of a restful action can be:
- Scalars
- Objects of a CBJsonModel subtype
Request/Input Headers
Further input can be passed to a restful action through request headers:
- Production mode: Headers of the form 'this-is-some-header' are
accessed as 'thisIsSomeHeader':
this-is-some-header: someValue\r\n this-is-another-header: anotherValue\r\n
- Development mode: From the 'header' GET parameter as a hash:
http://.../jsin=...&header[thisIsSomeHeader]=someValue&header[thisIsAnotherHeader]=anotherValue
Response/Output objects
Output object types of a restful action can be:
- Scalars
- Objects of a CBJsonModel subtype
- Arrays of the above two element types
Response/Output errors
Errors are uniformly output using the createErrorObject method.
Examples
Here is an example GET request (for development mode) with both header and json:
http://.../index-test.php?r=controller/action&header[applicationId]=1&jsin={"id":34034,"name":"John Doe"}
- CController
- CBJsonController
Author: Konstantinos Filios<EMAIL_ADDRESS>Since: 1.0
Located at components/CBJsonController.php
public
|
|
protected
string
|
|
protected
|
|
protected
|
|
protected
array
|
|
public
|
|
public
CAction
|
|
public
array
|
|
public
|
|
public
|
|
protected
|
|
protected
array
|
#
createErrorObject( integer $code, string $message, string $traceString, string $type )
Create a standard-form error object from passed details. |
public
boolean
|
$groupByToken | true |


Shuffling is the process of rearranging an array of elements randomly. For example, you might shuffle a deck of cards before dealing a poker game. A good shuffling algorithm is unbiased, where every ordering is equally likely.
The Fisher–Yates shuffle is an optimal shuffling algorithm. Not only is it unbiased, but it runs in linear time, uses constant space, and is easy to implement.
function shuffle(array) {
var n = array.length, t, i;
while (n) {
i = Math.random() * n-- | 0; // 0 ≤ i < n
t = array[n];
array[n] = array[i];
array[i] = t;
}
return array;
}
Above is the code, and below is a visual explanation:
Each line represents a number. Small numbers lean left and large numbers lean right. (Note that you can shuffle an array of anything — not just numbers — but this visual encoding is useful for showing the order of elements. It is inspired by Robert Sedgwick’s sorting visualizations in Algorithms in C.)
The algorithm splits the array into two parts: the right side of the array (in black) is the shuffled section, while the left side of the array (in gray) contains elements remaining to be shuffled. At each step it picks a random element from the left and moves it to the right, thereby expanding the shuffled section by one. The original order on the left does not need to be preserved, so to make room for the new element in the shuffled section, the algorithm can simply swap the element into place. Eventually all elements are shuffled, and the algorithm terminates.


Once we are confident in our hypothesis, we can export this code into backtesting. One way to accomodate this model into research is to create a scheduled event which uses our model to pick stocks and goes long.
private List<string> _asset = new List<string>{"SHY", "TLT", "IEI", "SHV", "TLH", "EDV", "BIL", "SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT", "VGLT", "SCHO", "SCHR", "SPTS", "GOVT"}; public override void Initialize() { // 1. Required: Five years of backtest history SetStartDate(2014, 1, 1); // 2. Required: Alpha Streams Models: SetBrokerageModel(BrokerageName.AlphaStreams); // 3. Required: Significant AUM Capacity SetCash(1000000); // 4. Required: Benchmark to SPY SetBenchmark("SPY"); SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel()); SetExecution(new ImmediateExecutionModel()); // Add Equity ------------------------------------------------ foreach(var ticker in _asset) { AddEquity(ticker, Resolution.Minute); } // Set Scheduled Event Method For Our Model. In this example, we'll rebalance every month. Schedule.On(DateRules.MonthStart(), TimeRules.BeforeMarketClose("SHY", 5), EveryDayBeforeMarketClose); }
def Initialize(self) -> None: #1. Required: Five years of backtest history self.SetStartDate(2014, 1, 1) #2. Required: Alpha Streams Models: self.SetBrokerageModel(BrokerageName.AlphaStreams) #3. Required: Significant AUM Capacity self.SetCash(1000000) #4. Required: Benchmark to SPY self.SetBenchmark("SPY") self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel()) self.SetExecution(ImmediateExecutionModel()) self.assets = ["SHY", "TLT", "IEI", "SHV", "TLH", "EDV", "BIL", "SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT", "VGLT", "SCHO", "SCHR", "SPTS", "GOVT"] # Add Equity ------------------------------------------------ for i in range(len(self.assets)): self.AddEquity(self.assets[i], Resolution.Minute) # Set Scheduled Event Method For Our Model. In this example, we'll rebalance every month. self.Schedule.On(self.DateRules.MonthStart(), self.TimeRules.BeforeMarketClose("SHY", 5), self.EveryDayBeforeMarketClose)
Now we export our model into the scheduled event method. We will remove qb
and replace methods with their QCAlgorithm
counterparts as needed. In this example, this is not an issue because all the methods we used in research also exist in QCAlgorithm
.
Now we export our model into the scheduled event method. We will switch qb
with self
and replace methods with their QCAlgorithm
counterparts as needed. In this example, this is not an issue because all the methods we used in research also exist in QCAlgorithm
.
private void EveryDayBeforeMarketClose() { // Fetch history on our universe var history = History(Securities.Keys, 252*2, Resolution.Daily); if (history.Count() < 0) return; // Extract daily return of close prices for each Symbol from Slice data var returns = new Dictionary<string, List<Double>>(); var last = new Dictionary<string, Double>(); foreach(var slice in history){ foreach(var symbol in slice.Bars.Keys){ if(!returns.ContainsKey(symbol)){ returns.Add(symbol, new List<Double>()); last.Add(symbol, (Double)slice.Bars[symbol].Close); } var change = (Double) ((Double)slice.Bars[symbol].Close - last[symbol])/last[symbol]; last[symbol] = (Double)slice.Bars[symbol].Close; returns[symbol].Add(change); } } // Convert returns into 2-d array double[,] ret = new double[returns.Values.ElementAt(0).Count - 1, _asset.Count]; int k = 0; foreach(var kvp in returns) { var symbol = kvp.Key; for(int i=0; i < returns[symbol].Count - 1; i++) { ret[i, k] = returns[symbol][i + 1]; } k++; } // Get correlation matrix var corrMatrix = Measures.Correlation(ret); // Find 5 assets with the least absolute sum correlation var correlations = new Dictionary<string, Double>(); for(int i=0; i < corrMatrix.GetLength(0); i++) { var symbol = _asset[i]; if(!correlations.ContainsKey(symbol)){ correlations.Add(symbol, 0); } for (int j=0; j < corrMatrix.GetLength(1); j++) { var value_ = corrMatrix[i, j]; correlations[symbol] += value_ >= 0 ? value_ : -value_; } } var selected = correlations.OrderBy(x => x.Value).Take(5).Select(x => x.Key).ToList(); // Emit insights foreach(var symbol in selected) { var insight = new Insight(symbol, Expiry.EndOfMonth, InsightType.Price, InsightDirection.Up); EmitInsights(insight); } }
def EveryDayBeforeMarketClose(self) -> None: qb = self # Fetch history on our universe history = qb.History(qb.Securities.Keys, 252*2, Resolution.Daily) if history.empty: return # Select the close column and then call the unstack method, then call pct_change to compute the daily return. returns = history['close'].unstack(level=0).pct_change().iloc[1:] # Get correlation correlation = returns.corr() # Find 5 assets with lowest absolute sum correlation selected = [] for index, row in correlation.iteritems(): corr_rank = row.abs().sum() selected.append((index, corr_rank)) sort_ = sorted(selected, key = lambda x: x[1]) selected = [x[0] for x in sort_[:5]] # ============================== insights = [] for symbol in selected: insights.append( Insight.Price(symbol, Expiry.EndOfMonth, InsightDirection.Up) ) self.EmitInsights(insights)


Registration No: {{reg}}
| Number Of Seats | {{seats}} |
|---|---|
| Mileage | {{mileage}} |
| Year Of Manufacture | {{manfYear}} |
| Date Created | {{created | date}} |
Trips: 200
Revenue: Ksh: 20000
Incidents: None
Rating: 4.2
| Document Name | Date Of Issue | Expires On | File Type | Status | Action |
|---|---|---|---|---|---|
| Driving Linces | 12/11/2019 | 12/31/2021 | .PNG | Active |
|
| Document Name | Date Of Issue | Expires On | File Type | Status | Action |
|---|---|---|---|---|---|
| Driving Linces | 12/11/2019 | 12/31/2021 | .PNG | Active |
|
| Document Name | Date Of Issue | Expires On | File Type | Status | Action |
|---|---|---|---|---|---|
| Driving Linces | 12/11/2019 | 12/31/2021 | .PNG | Active |
|


{% extends "base.html" %} {% block content %}
Please enter a city and select a country acronym to register a 5 day forecast.
Click here to logout.


The power of voice analytics in your hands.
Release date: June 15th
If you want to know first or need more information, please fill out this form:
The power of voice analytics in your hands.
If you want to know first or need more information, please fill out this form:


Static Private _commandBlacklist
_commandBlacklist: object
actions
actions: boolean = true
addCommand
addCommand: boolean = true
alertAccept
alertAccept: boolean = true
alertDismiss
alertDismiss: boolean = true
alertText
alertText: boolean = true
applicationCacheStatus
applicationCacheStatus: boolean = true
back
back: boolean = true
background
background: boolean = true
call
call: boolean = true
catch
catch: boolean = true
close
close: boolean = true
closeApp
closeApp: boolean = true
commandList
commandList: boolean = true
context
context: boolean = true
contexts
contexts: boolean = true
cookie
cookie: boolean = true
currentActivity
currentActivity: boolean = true
defer
defer: boolean = true
deleteCookie
deleteCookie: boolean = true
desiredCapabilities
desiredCapabilities: boolean = true
deviceKeyEvent
deviceKeyEvent: boolean = true
endAll
endAll: boolean = true
eventNames
eventNames: boolean = true
finally
finally: boolean = true
frame
frame: boolean = true
frameParent
frameParent: boolean = true
getAppStrings
getAppStrings: boolean = true
getCurrentDeviceActivity
getCurrentDeviceActivity: boolean = true
getCurrentPackage
getCurrentPackage: boolean = true
getDeviceTime
getDeviceTime: boolean = true
getNetworkConnection
getNetworkConnection: boolean = true
getPrototype
getPrototype: boolean = true
gridProxyDetails
gridProxyDetails: boolean = true
gridTestSession
gridTestSession: boolean = true
hideDeviceKeyboard
hideDeviceKeyboard: boolean = true
imeActivate
imeActivate: boolean = true
imeActivated
imeActivated: boolean = true
imeActiveEngine
imeActiveEngine: boolean = true
imeAvailableEngines
imeAvailableEngines: boolean = true
imeDeactivated
imeDeactivated: boolean = true
init
init: boolean = true
inspect
inspect: boolean = true
installApp
installApp: boolean = true
isAndroid
isAndroid: boolean = true
isAppInstalled
isAppInstalled: boolean = true
isExecuted
isExecuted: boolean = true
isIOS
isIOS: boolean = true
isLocked
isLocked: boolean = true
isMobile
isMobile: boolean = true
isMultiremote
isMultiremote: boolean = true
lastPromise
lastPromise: boolean = true
lastResult
lastResult: boolean = true
launch
launch: boolean = true
localStorage
localStorage: boolean = true
localStorageSize
localStorageSize: boolean = true
location
location: boolean = true
lock
lock: boolean = true
logTypes
logTypes: boolean = true
logger
logger: boolean = true
next
next: boolean = true
openNotifications
openNotifications: boolean = true
options
options: boolean = true
orientation
orientation: boolean = true
pause
pause: boolean = true
prependListener
prependListener: boolean = true
prependOnceListener
prependOnceListener: boolean = true
promise
promise: boolean = true
removeApp
removeApp: boolean = true
requestHandler
requestHandler: boolean = true
saveScreenshot
saveScreenshot: boolean = true
screenshot
screenshot: boolean = true
sessionId
sessionId: boolean = true
sessionStorage
sessionStorage: boolean = true
sessionStorageSize
sessionStorageSize: boolean = true
setImmediateValue
setImmediateValue: boolean = true
setNetworkConnection
setNetworkConnection: boolean = true
settings
settings: boolean = true
source
source: boolean = true
status
status: boolean = true
then
then: boolean = true
timeouts
timeouts: boolean = true
timeoutsAsyncScript
timeoutsAsyncScript: boolean = true
timeoutsImplicitWait
timeoutsImplicitWait: boolean = true
transferPromiseness
transferPromiseness: boolean = true
unify
unify: boolean = true
window
window: boolean = true
windowHandle
windowHandle: boolean = true
windowHandleFullscreen
windowHandleFullscreen: boolean = true
windowHandleMaximize
windowHandleMaximize: boolean = true
windowHandlePosition
windowHandlePosition: boolean = true
windowHandleSize
windowHandleSize: boolean = true
windowHandles
windowHandles: boolean = true
Steps consist of a description and an execution function. The execution function performs changes to the state of the tested application and the description briefly summarizes these changes in natural language.
A step can be parameterized by passing step arguments and a step callback (both of which are optional) to the execution function:
Step arguments are key-value pair objects that provide dynamic values to the state changes of the execution function. They also enable the interpolation of a step's description by replacing
%{key}
in the description string with key's value retrieved from the step arguments object).Step callbacks can be used to query and validate the state of the tested application right after step execution. A step callback will be passed the return value of the execution function as its first parameter.
ArgsType defines the type of the step arguments passed to the execution function.
ReturnType defines the return type of the execution function.


This script uses the following markup to trigger slideshow behavior:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

As you can see, a simple .slideshow
class with some div
s in it suffices (with the default css).
You can use a different container element or slides if you like. You'll just need to change some of the default css)
The slideshow only supports a handful of options via attributes on the .slideshow
element:
The right slideshow above uses the following code:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5


The tracker node has a built in automatic calibration feature.
On startup it measures the noise on the currently selected channel and subtracts this from future readings.
Please do turn of your video transmitter during startup to avoid false readings!.
The tracker then enters calibration mode.
On the first pass after startup the unit is measuring the peak RSSI value and subtracts the calibration offset and stores this as the trigger value.
The RSSI must fall below trigger value minus the calibration threshold to end the calibration mode.
For the following laps the tracker is waiting for the RSSI to be equal or higher than the trigger value. The timestamp during the highest RSSI value is stored.
As soon as the RSSI value is falling below the trigger value minus the trigger threshold the lap detection is ended. The laptime is calculated based on the difference between the current and the previous timestamp (aka peak-to-peak time).
Example:
Quad is passing the gate for the first time and RSSI is 240. If the calibration offset is 10 then the trigger value will be 230.
Calibration is left if RSSI is below 110 (if calibration threshold is 120).
Timestamp is saved if the quad is passing the gate and the RSSI is higher than 230. The next timestamp is saved as soon as RSSI is below 190 (trigger value - trigger threshold).
The minimum allowed lap time. Lap times that are below the defined value are not taken into account and therefore not counted.
The RSSI value that triggers a new lap detection. If the measured RSSI value is equal or above this value a new lap detection is started.
The trigger threshold defines the RSSI window in which the lap detection is active. The lap detection ends if RSSI is below trigger value minus trigger threshold.
The RSSI trigger threshold during calibration state. The calibration ends if RSSI is below trigger value (see below) minus calibration trigger threshold.
The RSSI offset that is substracted from found peek during calibration. Improves lap detection but can add jitter to lap times. This should compensate for a slightly different flying path (e.g. flying a bit higher than during calibration).
The filter ratio is the smoothing factor for the RSSI signal. The ratio is allowed to be in the range from 0 to 1. Values more near zero mean more smoothing while values near 1 mean less smoothing but more jitter. When set to zero no new values are considered. A value of one disables smoothing.
The filter ratio calibration is the smoothing factor for the RSSI signal during calibration. The ratio is allowed to be in the range from 0 to 1. Values more near zero mean more smoothing while values near 1 mean less smoothing but more jitter. When set to zero no new values are considered. A value of one disables smoothing. This can come in handy if your VTX sends multiple bursts during startup, you can set a very low value (e.g. 0.001) here to add extreme smoothing (please keep in mind that the calibration run should be done very slow then!)


Check for errors during memory allocation.
If memory allocation fails and the error is not handled, the result may be unpredictable and dangerous behavior of the program.
Check for and handle errors whenever allocating memory.
Perform the following actions to assure that errors during memory allocation are handled:
Identify memory allocation code. Find all code that allocates memory for objects. Search for calloc(), malloc(), realloc() function calls, and the new operator.
Check return values. Calloc(), malloc(), and realloc() return null pointers when they fail. Add code that checks the return values of these functions and handles error conditions appropriately.
Handle exceptions. The new operator throws a std::bad_alloc exception when it fails. Add code that handles the std::bad_alloc exception when the new operator is used.


Anti-Drink Drive 酒死一生
The first wall painting I’ve ever done; about 2.2m height to 5m width. Our task was to create a wall-The first wall painting I’ve ever done; about 2.2m height to 5m width. Our task was to create a wall-painting for our military camp to promote anti-drink driving. Me and two comrades had a little more than two months to complete the painting. I initially thought we could do this until we began the actual draft. The difficulty of applying pencil marks onto the surface was phenomenal. Imagine drafting on a stone cladding covered by thick paint. Any errors we made became extremely unforgiving. Trying to block in lines was hard enough, but erasing takes it to a whole new level. As a result, the draft itself took us an entire week before completion.
The painting The painting stage was when things become a nightmare. Under minimal budget, we couldn’t afford anything but five buckets of student grade paint plus a few paintbrushes used at kindergartens. The bristle would get mixed into the paint as they fall apart so frequently. If that wasn’t hard enough, the rough surface took us triple the time to paint any area as we had to force the paint into those tiny holes of the surface.
How I got this photo:
Trying to get this photo of the painting involved our company commander risking himself (all personal electrical devices were banned in the military). The only option was to borrow a local DSLR that’s used for shooting military events. I remember kindly asking our company commander(the highest position in a company) if he could take us a photo. It was on a good day as he strolled by to look at our painting. He looked relaxed. We were quite surprised he accepted our request. He was a nice guy compared to those of other companies. He told me that giving us the photo via USB would cause him serious trouble. There were security cameras installed intensively inside the PC room. The only solution was to have the images printed directly off the computer. Which is why the quality of the photo I’ve uploaded here is quite poor. The actual painting’s sky was less saturated.


My Lorem Option #1
Your Ipsum Option #2
Their Consectuer Option #3
His Adjascent Option #4
Her Split Option #5


This site is commissioned by Omaha Public Schools and as such is a part of their overall privacy statement. Additionally this site will collect any data submitted for upload will keep track of individual browsers login session and parameters used for searching for data.


Roblox was my first contact with programming, allowed and shone a light into me that has motivated me to continue programming since then.
"Where words fail, music speaks."
- Hans Christian Anderson
I find learning new things absolutely enjoyable. Courses are built into steps which helps on aggregating information.
Learning new languages opens up a world of opportunities and allows you to discover new cultures and the world.