`
* Part 1 - Primitive Functions
<<#experiment0>>
* Experiment 0 - How not to make a window
If we start Xcode, do `File->New->Project` and select `Cocoa Application`
then set the language to `Swift` then Xcode will create a file called
`ApplicationDelegate.swift` with the following content:
@include{file = "../includes/swift/AppDelegate.swift"} DO NOT EDIT BELOW
//
// AppDelegate.swift
// Project
//
// Created by joseph armstrong on 28/12/15.
// Copyright © 2015 joseph armstrong. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
@END
This file cannot be run outside Xcode - here's what happens if we try to
run this directly in a terminal:
swift AppDelegate.swift
AppDelegate.swift:11:1: error: 'NSApplicationMain' attribute cannot be
used in a module that contains top-level code @NSApplicationMain
^
AppDelegate.swift:1:1: note: top-level code defined in this source file
//
^
So this doesn't work - but after a little Googling and some small
edits we can modify this so that we can create a window in the shell, this is show in the next
section.
<<#experiment1>>
* Experiment 1 - A simple window
This window is created with the following code - which is
derived from `AppDelegate.swift`.
@include{ file="../includes/swift/experiment1.swift"} DO NOT EDIT BELOW
// experiment1.swift
// run with:
// $ swift experiment1.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification) {
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
To run the program store the above in a file `experiment1.swift` and run
the program in a terminal with the following command:
$ swift experiment1.swift
<<#experiment2>>
* Experiment 2 - A window with a title and specific size
Now I'll make a larger window and add a title:
Here I've make the window a specific size a title and some controls
to the title bar:
@include{ file = "../includes/swift/experiment2.swift"} DO NOT EDIT BELOW
// experiment2.swift
// run with:
// $ swift experiment2.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 2"
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
* Adding controls
Now we can make a simple window. The next step is to add some controls.
I've added one control in each experiment.
<<#experiment3>>
* Experiment 3 - A window with a button
Here's a window with a button in it - note that nothing happens when
we click the button - in experiment 5 I'll add a click action to the
button.
The code is as follows:
@include{file = "../includes/swift/experiment3.swift"} DO NOT EDIT BELOW
// experiment3.swift
// run with:
// $ swift experiment3.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 3"
let button = NSButton(frame: NSMakeRect(20, 100, 180, 30))
button.bezelStyle = .ThickSquareBezelStyle
button.title = "Click Me"
button.target = NSApp
window.contentView!.addSubview(button)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
*Exercise:* Try Googling `ThickSquareBezelStyle` you should be able to
find all the available button styles. Try making small edits to the
program to see what happens.
<<#experiment4>>
* Experiment 4 - A window with a text field
This is actually a `TextView` where I've set the background color to the window
background color.
*Exercise:* Make a better or alternative version.
@include{file="../includes/swift/experiment4.swift"} DO NOT EDIT BELOW
// experiment4.swift
// run with:
// $ swift experiment4.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 4"
let text = NSTextView(frame: NSMakeRect(20, 150, 180, 30))
text.string = "Some Text"
text.editable = false
text.backgroundColor = window.backgroundColor
text.selectable = false
window.contentView!.addSubview(text)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
<<#experiment5>>
* Experiment 5 - Connecting the button to the text field
@include{file="../includes/swift/experiment4.swift"} DO NOT EDIT BELOW
// experiment4.swift
// run with:
// $ swift experiment4.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 4"
let text = NSTextView(frame: NSMakeRect(20, 150, 180, 30))
text.string = "Some Text"
text.editable = false
text.backgroundColor = window.backgroundColor
text.selectable = false
window.contentView!.addSubview(text)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
@include{file="../includes/swift/experiment5.swift"} DO NOT EDIT BELOW
// experiment5.swift
// run with:
// $ swift experiment5.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
var text = NSTextView(frame: NSMakeRect(20, 150, 180, 30))
let window = NSWindow()
@IBAction func myAction(sender: AnyObject) {
text.string = "Wow I've been clicked"
}
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 5"
let button = NSButton(frame: NSMakeRect(20, 100, 280, 30))
button.bezelStyle = .ThickSquareBezelStyle
button.title = "Click me and the text will change"
button.target = self;
button.action = "myAction:" // Note the colon
window.contentView!.addSubview(button)
text.string = "Some Text"
text.editable = false
text.backgroundColor = window.backgroundColor
text.selectable = false
window.contentView!.addSubview(text)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
This code is a bit of a mess, it had to be carefully constructed so
that the variable `text` was defined *before* the button callback
function `myAction` (since `text` is referred to in the body of the
`myAction` function).
This is a tad tricky and would indeed be impossible if the relationships
between the controls could not be ordered (for example, it would be
impossible to create two buttons `b1` and `b2` which when clicked
change the labels of the ``other'' button) - I'll solve this problem
later by allowing the click action on a button to be defined *after*
the all the controls have been created.
<<#experiment6>>
* Experiment 6 - A window with an image
The image is from Sydney Padua's most excellent book [[http://sydneypadua.com/2dgoggles/][The Thrilling
Adventures of Lovelace and Babbage]]
@include{file="../includes/swift/experiment6.swift"} DO NOT EDIT BELOW
// experiment6.swift
// run with:
// $ swift experiment6.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:500, height:260))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 6"
// load and display an image
let path = "../images/ada.png"
let img = NSImage(contentsOfFile: path)!
let imgView = NSImageView(frame: NSMakeRect(10, 10, 480, 240))
imgView.image = img
window.contentView!.addSubview(imgView)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
* Part 2 - Abstractions
The goal of this part is to make a simple set of functions that hides
most of the detail of making windows and adding controls to them.
The end result is going to be a program fragment that looks like this:
let entry1 = make_entry(window, (200, 80, 180, 30), "1")
let text1 = make_text(window, (20, 80, 180, 30), "Hello from me")
let text2 = make_text(window, (20, 120, 180, 30), "Another field")
let button1 = make_button(window, (120, 40, 80, 30), "Click")
// make a click function
let f1 = {() -> Bool in
text1.string = "Callback worked"
print(entry1.textStorage!.string)
text2.string = entry1.textStorage!.string
return true} //
button1.onclick = f1
All the details of making the controls will be hidden in functions
like `make_text`, `make_button` and so ``wiring up'' the controls will
be done by hooking callback functions on the buttons.
To do this needs some trickery, so in the sections that follow I'll
first explain the techniques and then refactor the code in the Part 1
into a form that fits my purpose.
Firt I'll look at parameter passing in Swift.
<<#parameters>>
* Parameter naming gobbledygook
> Swift parameter passing is totally unobvious.
I had expected that the ``obvious'' way to declare and call a function
would be something like this:
@include{file="../includes/swift/funcs1.swift"} DO NOT EDIT BELOW
// funcs1.swift
func add(x:Int, y:Int, z:Int) -> Int {
return x+y+z
}
print("add=", add(1,2,3))
@END
But oh dear:
swift funcs1.swift
funcs1.swift:5:18: error: missing argument labels 'y:z:' in call
print("add=", add(1,2,3))
^
y: z:
A little research revealed that the correct way to call
`add` was to use the totally unobvious syntax:
@include{file = "../includes/swift/funcs2.swift"} DO NOT EDIT BELOW
// funcs2.swift
func add(x:Int, y:Int, z:Int) -> Int {
return x+y+z
}
print("add =", add(1,y:2,z:3))
@END
Inconsistent *moi*? - the first parameter name is omitted. All the other parameters
must be present in the same order as the definition. Great shades of objective C!
This horrible syntax works:
> swift funcs2.swift
add = 6
Better though again unobvious is to prefix each argument in the function definition with
underscore `_` like this:
@include{file="../includes/swift/funcs3.swift"} DO NOT EDIT BELOW
// funcs3.swift
func add(x:Int, _ y:Int, _ z:Int) -> Int {
return x+y+z
}
print("add=", add(1,2,3))
@END
Now at least we can call the function in the same way as we'd do in
just about every other programming language under the sun.
* A button callback function
To make a callback function for a button we have to step back and then understand how
closures work, and then we can make a callback function.
I'll start by defining a simple class with an instance variable:
@include{file="../includes/swift/classes1.swift"} DO NOT EDIT BELOW
class Demo {
var firstname: String = "fred"
}
let x = Demo()
print(x.firstname)
x.firstname = "joe"
print(x.firstname)
@END
This should look familiar to you if you've programmed in an OO language.
Running this we see the following:
> swift classes1.swift
fred
joe
Now I'll do the same things with a functional argument:
@include{file = "../includes/swift/closures1.swift"} DO NOT EDIT BELOW
class Demo {
var call: () -> Bool = {() -> Bool in true}
}
let x = Demo()
print(x.call())
var i = 10
var f = {() -> Bool in print("hello I'm a callback and i =", i); return true}
x.call = f
print(x.call())
i = 20
print(x.call())
@END
Running this:
true
hello I'm a callback and i = 10
true
hello I'm a callback and i = 20
true
> Which to my mind is horrendous. The closure `f` does not capture the value of
`i` at the time when `f` is defined, changing `i` *after* `f` was defined
make nonsense of the idea of a closure.
If we are extremely careful we *can* use this mechanism to add a callback facility to
buttons. We'll do this and make a custom class, by inheriting the properties
of `NSButton` and adding our own callback routine:
class MyButton: NSButton {
var onclick: () -> Bool = {() -> Bool in true}
func myclick(sender: AnyObject) {
self.onclick()
}
}
and to make a button I call `make_button`
func make_button(window: NSWindow,
_ size:(x:Int, y:Int, width:Int, ht:Int),
_ title:String
) -> MyButton {
let button = MyButton()
button.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y),
CGFloat(size.width), CGFloat(size.ht))
button.title = title
button.bezelStyle = .ThickSquareBezelStyle
button.target = button
button.action = "myclick:"
window.contentView!.addSubview(button)
return button
}
Now we can make some objects and add an `onclick` callback to the buttons (just like
jquery) - the pseudo code to do this will look something like this:
... create a window ...
text1 = make_text(window, Size, Text)
entry1 = make_entry(window, Size, Default)
button1 = make_button(window, Size, Text)
F = ... a function involving text1, entry1, ... etc.
button1.onclick = F
<<#combined>>
* Putting it all together
Now let's put it all together:
The code is rather long - but I was able to pull out most of
the mess into simple reusable functionbs.
> The code to create the window and add controls was easy
and Xcode was not used.
@include{file="../includes/swift/combined1.swift"} DO NOT EDIT BELOW
// combined1.swift
// run with:
// $ swift combined1.swift
import Cocoa
class MyButton: NSButton {
var onclick: () -> Bool = {() -> Bool in true}
func myclick(sender: AnyObject) {
self.onclick()
}
}
func make_button(window: NSWindow,
_ size:(x:Int, y:Int, width:Int, ht:Int),
_ title:String
) -> MyButton {
let button = MyButton()
button.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y),
CGFloat(size.width), CGFloat(size.ht))
button.title = title
button.bezelStyle = .ThickSquareBezelStyle
button.target = button
button.action = "myclick:"
window.contentView!.addSubview(button)
return button
}
func make_entry(window:NSWindow,
_ size:(x:Int, y:Int, width:Int, ht:Int),
_ str: String
) -> NSTextView {
let text = NSTextView(frame: NSMakeRect(10, 140, 40, 20))
text.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y),
CGFloat(size.width), CGFloat(size.ht))
text.string = str
text.editable = true
text.selectable = true
window.contentView!.addSubview(text)
return text
}
func make_text(window:NSWindow,
_ size:(x:Int, y:Int, width:Int, ht:Int),
_ str: String
) -> NSTextView {
let text = NSTextView(frame: NSMakeRect(10, 140, 40, 20))
text.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y),
CGFloat(size.width), CGFloat(size.ht))
text.string = str
text.editable = false
text.backgroundColor = window.backgroundColor
text.selectable = false
window.contentView!.addSubview(text)
return text
}
func make_window(w: Int, _ h: Int, _ title: String) -> NSWindow {
let window = NSWindow()
window.setContentSize(NSSize(width:w, height:h))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask | NSResizableWindowMask
window.opaque = false
window.center();
window.title = title
return window
}
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = make_window(400, 200, "My title")
func applicationDidFinishLaunching(aNotification: NSNotification)
{
let entry1 = make_entry(window, (200, 80, 180, 30), "1")
let text1 = make_text(window, (20, 80, 180, 30), "Hello from me")
let text2 = make_text(window, (20, 120, 180, 30), "Another field")
let button1 = make_button(window, (120, 40, 80, 30), "Click")
// make a click function
let f1 = {() -> Bool in
text1.string = "Callback worked"
print(entry1.textStorage!.string)
text2.string = entry1.textStorage!.string
return true} //
button1.onclick = f1
window.makeKeyAndOrderFront(window)
window.makeMainWindow()
window.level = 1
}
}
let app = NSApplication.sharedApplication()
app.setActivationPolicy(.Regular)
let controller = AppDelegate()
app.delegate = controller
app.run()
@END
<<#open>>
* Open Problems
I had hoped to write:
let window = make_window(400, 200, "My Title")
let entry1 = make_text(window, ...)
But for some reason this does not work, so I have to move the call to `make_window`
to the initialisation part of the class. I haven't a clue why.
<<#swift_fpl>>
* Swift as a functional language
The bad
+ Verbose syntax - types are declared rather than inferred
+ Mutable data types
+ Weird mix of Classes, Structs and functions
+ No concurrency model
The good
+ It has a REPL
+ I can write apps *outside* XCode
I *like* the syntax of exceptions if the function X can raise an exception
then one must qualify call with ! ? or use an explicit try syntax
In Erlang term the use of ! and ? is easy to explain
Imagine an Erlang function f(X) that returns {ok, Val} when `Val = f(X)` or
otherwise `{eror, Why}` if the function could not compute a value for some argument `X`
The Swift compiler convention if implemented in Erlang would require `f(X)` to be
evaluated within a `catch` statement, like this:
case (catch f(X)) of
{ok, Val} ->
...;
{error, Why} ->
...
end
otherwise an error would be indicted.
If we were absolutely sure that `{ok, Val}` would be returned we'd write:
Val = f!(X)
Which is equivalent to the Erlang
{ok, Val} = f(X)
The ? convention unwraps `{ok, Val}` into `Val` or `{error, Why}` into `nil` in Swift.
<<#comments>>
* Comments on Swift
I've been programming Swift for a couple of weeks now. Do I like it?
Swift is widely marketed as a functional language - so it's
interesting to see how well it shapes up as a functional programming
language - or at least to see how compares to other FPLs that I am
familiar with.
Sequential FPLs gain a lot of power from the mechanisms they offer.
The offer (in varying degrees) type systems that (claim to) prevent
(some run-time) errors. Pattern matching syntaxes make the
programs very short. Immutable data structures simplifies
reasoning about the programming and debugging. Higher order functions
add to power of the language be treating functions as first
class data.
Where Swift shines it is in the integratiion with the underlying Objective C
frameworks on the Mac. To this extent Swift programming is a much
more attractive proposition than programming in C or Objective-C but
but this is not because Swift is a good language rather that C and
objective-C are bad languages for writing user-space application in.
The C family of languages (C, C++, Objective-C) are fine for writing
operating system but not for writing the majority of user-space
applications - here things like Python or visual-basic are far better.
Swift is a good replacement for
contexts in which Objective-C would be used.
If you're coming form Erlang/Haskell world you'll think ``Swift is
verbose and a bit of a mess`` but if you're coming from Objective-C
you'll think ``Swift is concise and elegant''
In Swift I really miss pattern matching and I dislike having to
excessivly declare types.
The lack of a decent concurrency model in Cocoa and Objective-C is
reflected in the Swift code - which although it works is pretty
horrible.
<<#why_i_use_text>>
* Textual vs Interactive interfaces
I've said that I don't like Xcode so I've added some reasons why.
Two common ways to create programs are:
1) We create a text file using a text editor.
2) We create a program by clicking on buttons and dragging objects in
an IDE (Integrated Development Environment) (for example, Xcode).
In the first method we don't usually have to tell the user how to
create a text file with given content. It suffices to give a listing
of the file and assume that the user can create the file using an
editor of their choice. It is totally irrelevant *how* the file is
created the only thing that matters is that the content of the file is
correct.
In order to understand the program only the content of the file must
be understood. We can examine it line by line, asking if we understand
what the lines of code mean.
Using an IDE is horribly different - describing how to interact with a
an IDE is very difficulty to do in text. Usually we have to *show* how to
do this typically with a YouTube video, or in a mixture of text and images.
An excellent example of the difficulty of describing how to do
something is can be found in [[http://swiftrien.blogspot.se/2015/11/swift-example-binding-nstableview-to.html][Notes from a Swift Developer]] -- in this
example the author uses a mixture of text and screenshots to describe
how to build an application. Text alone does not work.
The application described in the link above has a simple layout which could be *easily*
described in text (for example as an html table)
Unfortunately when we try to reproduce what we've seen in a video or
follow a description that is a mixture of text and images, we find that
the description almost invariably describes a different version of the
IDE than the one we have available.
Textual descriptions of the form ``and now click on the doggle control
icon'' are pretty useless if you haven't got a clue what the doggle
control icon looks like.
Worse - when the design process in an interface builder is finished -
all the correct buttons have been clicked the resulting ``state'' of
the system (ie the program) is not available in a textual format so we
cannot ask, line-by-line what the individual statement in the
description mean.
As you might gather - I hate IDEs like Xcode and Eclipse - I like to
totally understand every line of code I wrote - my method of
understanding code is always the same and independent of
language. Find an example program that works then reduce lines until I
can reduce no more making a minimal example that works - then
understand every line.
This is a slow process - but in the long run faster than clicking at
random in a IDE until your program works or Googling like crazy to see
if somebody else has a canned solution to your problem.
I get the impression that developers think that developing in a IDE is
somehow ``quicker'' than developing with no such tools. As far as I can see this
is false. Once I have a working program in a given directory structure
I can make a clone of this in a single terminal command (`cp -R ...`) and then
I'm off in my trusty editor.
Following instructions like
+ enter this ... into a file called ...
+ type the command ... into the shell
are easy to obey and pass the ``telephone test'' (ie can we describe exactly what to do
over a telephone) - no images or videos are needed to ``show'' the users what to do.
Once upon a time we could describe how to do something using text only.
Then we used text and images. Now it needs videos.
Asking questions about text was easy - ``what did you mean in paragraph 4''
now we'd have to ask ``what did you do 41.6-41.8 seconds into your video''
watching somebody doing something in Xcode 200.7 in a video and preforming slow
motion playbacks of selected sections is not my idea of programming.
* References
I've found several documents which helped me - none of them solves the problem
I'm try to solve but they have all provided clues to the solution:
+ [[http://czak.pl/2015/09/23/single-file-cocoa-app-with-swift.html]]
+ [[https://github.com/Eonil/CocoaProgrammaticHowtoCollection]]
+ [[https://forums.developer.apple.com/thread/5137]]
+ [[http://stackoverflow.com/questions/26609778/nsopenpanel-in-swift-how-to-open]]
+ [[https://objectivec2swift.com/#/converter/code]]
+ [[http://practicalswift.com/]]
+ [[https://github.com/tylergaw/js-osx-app-examples]]
+ [[http://www.raywenderlich.com/82046/introduction-to-os-x-tutorial-core-controls-and-swift-part-1]]
+ [[http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art024]]
+ [[http://mediautopia.weebly.com/swift-1-intro.html]]
+ [[http://dev.iachieved.it/iachievedit/using-swift-as-a-scripting-language/]]
+ [[http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art024]]
+ [[http://www.knowstack.com/swift-programming-an-introduction/]]
* Help and tips wanted
Does anynody know:
+ How can I create two or more windows? - I seem to only be able to create a single window
+ How can I make a socket client?
+ How can I make a socket server?
Solutions should be single Swift files that can be run from the terminal.
* The future
Articles like this are never finished only started ...


---
layout: page
tags: [Jekyll, HADDOCK, Bonvin, Docking, Simulation, Molecular Dynamics, Structural Biology, Computational Biology, Modelling, Protein Structure]
modified: 2014-08-08T20:53:07.573882-04:00
comments: false
image:
feature: pages/banner_software.jpg
---
HADDOCK2.2 manual
Software Links
HADDOCK consists of a collection of python and
CNS scripts and some other additional programs and scripts
(csh, awk, perl, c++).
Needed: To run HADDOCK, YOU NEED TO OBTAIN SEPARATELY AND INSTALL:
CNS
(http://cns-online.org).
Also recommended are:
- NACCESS:
Naccess is a stand alone program that calculates the accessible area
of a molecule from a PDB format file. It can calculate the atomic and
residue accessibilities for both proteins and nucleic acids, and is
available for free of charge for researchers at academic and non
profit-making institutions. We make use of NACCESS in HADDOCK to filter
active and passive residues based on their solvent accessible area (see
section AIR restraints).
- ProFit: ProFit is
designed to be the ultimate protein least squares fitting program. Some of
the provided analysis tools in HADDOCK make use of Profit. Profit can
be obtained free of charge for academics at http://www.bioinf.org.uk/software
- Pales:
PALES is a software for analysis of residual dipolar couplings. Pales provides
features for analysis of experimental dipolar couplings and dipolar coupling tensors,
such as best-fitting a dipolar coupling tensor to its corresponding 3D structure.
Pales can thus be used to derive the tensor components (Dxx, Dyy, Dzz or Da and R)
needed for the use of dipolar couplings as restraints for docking.
- Module: Modules is
another useful software for analysis of residual dipolar couplings with a nice
graphical interface. Modules allows the determination of alignment tensor
parameters for individual or multiple domains in macromolecules from residual
dipolar couplings and facilitates their manipulation to construct low-resolution
models of macromolecular structure.
- Tensor: Tensor is
another useful software for analysis of diffusion anisotropy data (NMR relaxation) with a nice
graphical interface. Tensor2 allows the determination of alignment tensor
parameters for individual or multiple domains in macromolecules from diffusion anisotropy data
and facilitates their manipulation to construct low-resolution models of macromolecular structure.
- 3DNA: 3DNA is a versatile package for
the analysis, rebuilding, and visualization of three-dimensional nucleic acid structures, based on a standard
reference frame (Olson et al., J. Mol. Biol. 313, 229-237, 2001). It is the software we
are using to generate libraries of pre-bent DNA conformations for protein-DNA docking in
our 3D-DART web server.
Here are a few links to other useful software:
- iCING:
The ultimate structure validation software suite... As a web portal. CING stands for
Common Interface for NMR structure Generation and is known for structure and NMR data validation.
- PSVS
Another nice structure validation server which integrates analyses from several widely-used structure quality evaluation tools,
including RPF, PROCHECK, MolProbity, Verify3D, Prosa II, the PDB validation software, and various structure-validation tools.
- LIGPLOT:
LIGPLOT is a program for automatically plotting protein-ligand interactions or protein-protein
interactions (use for that dimplot). It automatically generates schematic diagrams of protein-ligand
interactions for a given PDB file. The interactions shown are those mediated by hydrogen bonds and by
hydrophobic contacts.
- NUCPLOT:
NUCPLOT is a program for automatically plotting protein-nucleic acid interactions.
NUCPLOT can generate schematic diagrams automatically - directly from the 3D coordinates of the
complex as found in a given PDB file. The program works for any single- or double-stranded protein-DNA,
DNA-ligand and protein-RNA complexes.
- WhatIF This is a program
for protein structure analysis, validation and repair. It is available as a
webserver.
- Xmgr/Grace:
A very nice graphing tool for UNIX.
- Rasmol
This molecular graphics program displays your PDB
structures on screen using X graphics and enables you to rotate, display
and color the structure in a number of ways. Very convenient for a Quick
look at a structure. We use it for example to display, select and color
active and passive residues for HADDOCK (see
section AIR restraints)
- Pymol This is a very nice visualization (and much more)
program for high-quality display of 3D molecular structures.
- Molscript This is a
script-driven program for high-quality display of molecular 3D structures
in both schematic and detailed representations. You can get an academic
license for free from Avatar.
Here are a few links to scoring-related software:
- MOLPROBITY: MOLPROBITY can be used to
assess the packing and hydrogen-bonding quality of an interface.
- CCHarPPI: CCharPPI integrates many binding affinity
and scoring functions into a single web server. It calculates up to 108 parameters, including models of electrostatics,
desolvation and hydrogen bonding, as well as interface packing and complementarity scores, empirical potentials
at various resolutions, docking potentials and composite scoring functions.
- FastContact: FastContact is a
free energy scoring tool for protein-protein complex structures based on electrostatic and desolvation energies.
- DComplex: DComplex uses the
DFIRE energy function for the prediction of binding affinities.
- FoldX: FoldX is a program for calculating the folding pathways of
proteins and for calculating the effect of a point mutation on the stability of a protein.
- PISA: PISA is an interactive tool for the
exploration of macromolecular (protein, DNA/RNA and ligand) interfaces, prediction of probable quaternary structures
(assemblies), database searches of structurally similar interfaces and assemblies, as well as searches on various
assembly and PDB entry parameters.


A nice way to get some pretty output is to use find and printf
%f file name
%p path
%u user who owns
%g group
%m file permissions
using \t for tab delimeters
need to terminate with \n
find /home -type f -printf "%f\t%p\t%u\t%g\t%m\n" 2>dev/null | column -t


| Version: | 1.3 |
| Author: | Jeff Clement |
| Status: | Active Development |
A really simple mailing list package written in Python and intended for those who do not have a dedicated server. Simply take any POP3 account and turn it into a full featured mailing list.
JMLM is a very simple mailing list package that operates against an existing POP3 account and doesn't need any sort of dedicated server or access to the mail servers config. Simple:
This list will work against free POP3 accounts and you can even use dialup accounts for the mailing list software assuming you don't mind a little latency :)
The software is essentially complete now. It's very simple and certainly won't handle large lists but it works and does the normal things you expect.
Configuration is pretty simple. Just edit source code and modify the variables near the top. You can even tweak the reply messages when the server has something to say.
There are comments in the source code to give you a clue as to what you are editing. Just remember to be careful. Strings are encludes in quotes, boolean values are True or False. That sort of thing.
The messages MSG_... are just the message body of what gets sent on server messages. You can tweak it if you like. The %(...)s stuff is templating code for putting in things like the original message, the time and date, their address, etc.
Bare minimum you will need to setup SMTP_SERVER, POP3_SERVER, POP3_USER, POP3_PASS, LIST_NAME, LIST_ADDR, LIST_OWNER and LIST_KEY
Simply run the program with Python 2.2 or higher and it will tell you what you need to know. Basically the -p option tells it to poll the POP3 account for new messages and process them. The -l option lists subscribers and -s and -u subscribe and unsubscribe users.
Have fun and let me know if you use it please.
This software is licensed under the BSD license. Please make sure you have read and understood this license before downloading this software!
Copyright (c) 2003, Jeffrey Clement All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.


About Me
I am a seasoned programmer with a B.A. from Samford University, who has also taken advantage of further adult education in programming, database design, and full stack web development.
My work programming robotic systems controls gave me extensive experience in building proof of concept systems, connecting into customer databases, building flexible user interfaces, and generating reports and providing real-time data from the system .
I am currently a part-time student at UCF and freelance web developer, interested in full-time work in the web development field.
I am focused on providing elegant solutions by writing object based programs that provide maximum flexibility and code reusability, that also present intuitive interfaces for the user experience. I have lead teams of programmers to push projects forward in design, development, debugging, and implementation.
I enjoy the collaborative nature of well executed projects, and I am always looking for “+1” opportunities to exceed expectations.


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
Represents the context in which a scenario segment is being executed. The information in the context can be used to evaluate Expressions, and to execute Actions.
This interface extends ComponentNameResolver, and can thus be used to resolve arbitrary Nucleus names, either as Strings or as ComponentNames. If the scenario segment is being executed in the context of an HTTP request, the NameResolver can be used to resolve request-scoped components; otherwise, it can only resolve global components.
ProcessExecutionContext
| Field Summary | |
static java.lang.String |
CLASS_VERSION
Deprecated. Class version string |
| Method Summary | |
java.lang.Object |
getMessage()
Deprecated. Returns the JMS message bean which prompted the scenario segment execution to start or resume. |
java.lang.String |
getMessageType()
Deprecated. Returns the JMS type of the message which prompted the scenario segment execution to start or resume. |
RepositoryItem |
getProfile()
Deprecated. replaced by ProcessExecutionContext.getSubject() . |
DynamoHttpServletRequest |
getRequest()
Deprecated. Returns the current HTTP request, null if the scenario segment is not being executed in the context of an HTTP request. |
DynamoHttpServletResponse |
getResponse()
Deprecated. Returns the current HTTP response, null if the scenario segment is not being executed in the context of an HTTP request. |
RepositoryItem |
getScenarioInstance()
Deprecated. Returns the scenario instance going through the scenario segment. |
boolean |
isIndividual()
Deprecated. Returns true if this context corresponds to an individual user going through the scenario segment, false if it corresponds to a "collective" scenario instance which operates on behalf of all individual users. |
| Methods inherited from interface atg.nucleus.naming.ComponentNameResolver |
resolveName |
| Methods inherited from interface atg.naming.NameResolver |
resolveName |
| Field Detail |
public static final java.lang.String CLASS_VERSION
| Method Detail |
public boolean isIndividual()
public RepositoryItem getScenarioInstance()
isIndividual
is true), the
scenario instance points to that user, and any context variables
set during the segment execution; otherwise, this is a
"collective" scenario instance which represents, and operates on
behalf of, all individual users.
public RepositoryItem getProfile()
ProcessExecutionContext.getSubject()
.
ProcessExecutionContext
public java.lang.String getMessageType()
public java.lang.Object getMessage()
public DynamoHttpServletRequest getRequest()
public DynamoHttpServletResponse getResponse()
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


|
RCI Message Board
1.0
https://github.com/Jguer/RCI-Message-Board
|
| ▼ src | |
| ▼ msgserv | |
| identity.c | |
| identity.h | |
| main.c | |
| message.c | |
| message.h | |
| ▼ rmb | |
| ban.c | |
| ban.h | Basic structure to implement banned servers |
| identity.c | |
| identity.h | Initialization of the program and identity server communication |
| main.c | Reliable Message Board - Client |
| message.c | |
| message.h | Outbound communication with message server |
| ▼ testing | |
| greatest.h | |
| message_struct_test.c | |
| tests.c | |
| ▼ utils | |
| struct_message.c | |
| struct_message.h | |
| struct_server.c | |
| struct_server.h | |
| util_list.c | |
| util_list.h | |
| util_matrix.c | |
| util_matrix.h | Matrix structure definition |
| utils.c | |
| utils.h |


1 write to ExperimentAction
System.Management.Automation (1)
engine\Attributes.cs (1)
591
ExperimentAction
= experimentAction;
1 reference to ExperimentAction
System.Management.Automation (1)
engine\Attributes.cs (1)
625
_effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName,
ExperimentAction
);


Curly and Floppy Twistytail, the Funny Piggie Boys
by Howard R. Garis
Chapter 27: “Flop and the Skate Wagon”
Additional Information
- Year Published: 1918
- Language: English
- Country of Origin: United States of America
- Source: Garis, H. R. (1918). Curly and Floppy Twistytail, the Funny Piggie Boys. New York, NY: A. L. Burt Co.
-
Readability:
- Flesch–Kincaid Level: 4.4
- Word Count: 1,280
- Genre: Fantasy
- ✎ Cite This
Downloads
One morning Flop Ear, the little piggie boy, awakened in his bed of straw, and said:
“I don’t feel very well today.”
“I wish I didn’t, too,” spoke Curly Tail.
“Why?” asked his brother in surprise. “I’m not fooling. Honestly, I don’t feel well. Do you want to be sick, too?”
“Just a little bit,” answered Curly Tail.  “There is school today. I thought it was Saturday, and I was sorry I didn’t feel well, but now—”
Well, as it happened it was Friday, instead of Saturday, and, of course, there was school. But when Mrs. Twistytail heard that Flop Ear did not feel well, she said:
“Perhaps you had better not go today. Just lie abed and maybe you will be better by afternoon.”
So Curly Tail had to go to school alone, and he felt rather lonesome, and Flop Ear stayed at home, just like the little pig in the story.
But pretty soon, oh, I guess about 10 o’clock, when it was too late to go to school, Flop Ear got out of bed and said:
“I don’t feel quite so badly now, mother. Maybe if I go out in the air, I’ll be all well.”
“All right,” she said, and there was a funny little twinkle in her eyes. “But first you must take some castor oil, and then I will be sure you will be better,” she added.
Then Flop Ear wished he had gone to school, whether he felt well or not, but there was no help for it; he had to take the castor oil. After it was down—and it wasn’t much fun swallowing it, let me tell you—after it was down, Flop Ear walked out in the street sort of slow and thoughtful-like, and wished he had someone to play with, or something to do.
“It isn’t so much fun staying home as I thought it would be,” he said. Just then, in an ash barrel, he saw one roller skate. It was pretty well battered and worn, but the four wheels of it were good yet, and Flop Ear, as he took it out and knocked the ashes from it, said:
“Ha! One roller skate. Now if I had two I might have some fun, and forget about the castor oil.”
“You can have fun with one roller skate,” said a voice behind the little piggie boy, and turning, Flop Ear saw Uncle Butter, the goat gentleman, just coming back from having delivered all his milk.
“How can you have fun with one roller skate?” asked Flop Ear.
“By making a skate wagon,” said the goat gentleman. “I saw some boy animals up in Roseville playing on them yesterday, and I’ll tell you how to make one. First, you have to have a box, a long, narrow board, a stick and some nails and string.”
“I can get all those!” exclaimed Flop Ear, and he did. Then Uncle Butter took the roller skate apart at the place where it slid together to be made smaller or larger. Right apart he took it, and there were two wheels on one part and two on the other.
The goat gentleman used the string to fasten two wheels on one end of the long narrow board and two wheels on the other end. Then he nailed the box on the front end of the board, right over the front wheels, and on top of the box he nailed the stick for a handle, just as on a bicycle, only this handle was straight and not curved.
“There is your skate wagon,” he said to Flop Ear. “You take it to some street that runs down hill and you start at the top. Stand up on the board, near the box, and lean against it so you won’t fall off.  Down the hilly street you will roll on the skate wheels, just like a coaster wagon.”
“Fine!” cried Flop Ear, as he thanked Uncle Butter. Then he ran to the top of a hilly, smooth street to try his skate wagon.
He stood up in the middle of the long narrow board, took hold of the handles on top of the box, and steadied himself. Then, with one foot he gave himself a good push, and down the hill he went as fast as anything, making a noise just like a real roller skater boy only louder.
“Oh, this is great!” he cried as he reached the bottom of the hill, and ran back for another coast down it. Then Flop Ear forgot all about being sick, and he had lots of fun riding on his skate wagon, so you see that even one roller skate may be good for something.
Well Flop Ear was just going to coast down the hill for about the forty-’leventh time when, all of a sudden, he heard a voice calling:
“Save me! Save me! Oh, help me!”
He looked around and there he saw a poor old lady cat being chased by a bad dog that had once caught Uncle Butter to pull out his horns. The lady cat was running as fast as she could with her tail all swelled up like a bologna sausage.
“Save me from the bad dog!” she cried.
“Bow-wow! Woof! Woof! Bur-r-rr!” barked the dog. “I’ll get you!”
“No you won’t!” cried Flop Ear. “Get on my skate wagon!” he called to the old lady cat, and with one jump she landed in the box. Flop Ear gave a good push, jumped on the wagon himself, and down the hill he went faster and faster, with the dog coming after him.
“Oh, he’ll get us!” cried the lady cat.
“No he won’t!” shouted Flop Ear. Faster and faster went the skate wagon down the hill, and the bad dog tried so hard to catch up to it that, all of a sudden, his legs got tied up in a hard knot—yes, sir, just as hard a knot as if a sailor had made it.
But by that time Flop Ear and the lady cat were safe at the bottom of the hill on the skate wagon, and the dog could not get them. Then the cat lady thanked the piggie boy very much, and gave him a penny, and Flop Ear went to school that afternoon, and was all better, and later he and Curly Tail had lots of fun on the strange wagon Uncle Butter had told how to make.
And so in case the rose bush doesn’t scratch the lilac leaves off the pie plant and make the clothes line catch cold, I’ll tell you next about Baby Pinky and the lemon.


Pygments
Write your own filter
« Back To IndexContents
New in Pygments 0.7.
Writing own filters is very easy. All you have to do is to subclass the Filter class and override the filter method. Additionally a filter is instanciated with some keyword arguments you can use to adjust the behavior of your filter.
Subclassing Filters
As an example, we write a filter that converts all Name.Function tokens to normal Name tokens to make the output less colorful.
from pygments.util import get_bool_opt from pygments.token import Name from pygments.filter import Filter class UncolorFilter(Filter): def __init__(self, **options): Filter.__init__(self, **options) self.class_too = get_bool_opt(options, 'classtoo') def filter(self, lexer, stream): for ttype, value in stream: if ttype is Name.Function or (self.class_too and ttype is Name.Class): ttype = Name yield ttype, value
Some notes on the lexer argument: that can be quite confusing since it doesn't need to be a lexer instance. If a filter was added by using the add_filter() function of lexers, that lexer is registered for the filter. In that case lexer will refer to the lexer that has registered the filter. It can be used to access options passed to a lexer. Because it could be None you always have to check for that case if you access it.
Using a decorator
You can also use the simplefilter decorator from the pygments.filter module:
from pygments.util import get_bool_opt from pygments.token import Name from pygments.filter import simplefilter @simplefilter def uncolor(lexer, stream, options): class_too = get_bool_opt(options, 'classtoo') for ttype, value in stream: if ttype is Name.Function or (class_too and ttype is Name.Class): ttype = Name yield ttype, value
The decorator automatically subclasses an internal filter class and uses the decorated function for filtering.


TL;DR
This project was linked to a lecture about Shape Modeling. This project presents a method to deform meshs, based on high frequency details conservation and low frequency forms deformation, to keep a good integrity of the mesh during the edition.
The editing method is real-time for small to medium meshes on a medium-class laptop computer.
Overview of the method - [Source]( http://graphics.uni-bielefeld.de )
Table of Contents
1. Multiresolution mesh editing
1.1. Selecting the handles
1.2. Removal of high-frequency details
1.3. Deforming the smooth mesh
1.4. Transferring high-frequency details to the deformed surface
1.5. Real-time performance
2. Optional tasks
1. Multiresolution mesh editing
1.1. Selecting the handles
The first step to deform a mesh is to select which part will move and which won’t. Therefore, you can use the GUI to select handle over the mesh.
1.2. Removal of high-frequency details
The next processing step is to remove, and store, high frequency details of the mesh. To proceed, we create a copy of the mesh, that we heavily smooth, by minimizing the thing-plate energy. Information on this energy
We will have to build and solve a system, to represent the minimization of this energy.
Documentation informations
We can use the following function :
- igl::invert_diag()
- igl::massmatrix()
- igl::cotmatrix()
- igl::adjacency_list()
- igl::per_vertex_normals()
Informations on these functions were already provided for previous assignements. The others were not specified in the assignement.
Usage
The goal is to store the details of the original mesh, by storing the differences between the smoothed mesh and the original mesh.
First we smooth the mesh.
- We create the LML matrix (once for each mesh except if you change an option in the interface).
- We extract Aff and Afc from this matrix.
- We use a solver to obtain the smoothed positions of the free vertices.
We obtained the smoothed version of the mesh. Then we want to compute and store the difference between the original and smoothed mesh.
So we compute a local basis for each vertex, thanks to the Gram-Schmidt orthonormalization process applied to a 3-dimensions basis. So, we will have 3 vectors :
- First vector : we get the normal of each vertex of the mesh
- Second vector : we find the farest vertex-neighboor of the current vertex and we compute the projection on the plan of the vector between the current point and this neighboor
- Third vector :we get a third vector thanks to a cross product.
Gram Schmidt orthonormalization process (Public domain)
We then calculate the displacement vector between the original and the smoothed mesh, by an easy soustraction. We project this vector on the three axis on the basis created, by dot product. We store the 3 factors for later use.
// == Save Old positions of vertices ==
igl::slice(V, handle_vertices, 1, Handles_BeforeMove);
igl::slice(V, free_vertices_indexes, 1, free_BeforeSmooth_Pos);
(...)
// == We compute the LML matrix (global variable) ==
//CREATION OF Lw
igl::cotmatrix(V, F, L);
igl::massmatrix(V, F, massMatrixType, M);
igl::invert_diag(M, Minvert);
LML = L * Minvert * L;
// == Division of the Bilaplacian ==
igl::slice(LML, free_vertices_indexes, free_vertices_indexes, Aff);
igl::slice(LML, free_vertices_indexes, handle_vertices, Afc);
solverCholesky.compute(Aff);
//Creation of B (right side)
RightSide = -1 * Afc * Handles_BeforeMove_Sparse;
//Solving of the system
Eigen::SparseMatrix<double> free_AfterSmooth_Pos_Sparse;
free_AfterSmooth_Pos_Sparse = solverCholesky.solve(RightSide);
(...)
//Complete the base for each vertex
Eigen::MatrixXd NormalsPerVertex;
Eigen::MatrixXd T1;
Eigen::MatrixXd T2;
computeBasis(NormalsPerVertex, T1, T2, true); // true = creation mode of the basis
// == Get the details ==
int index_currentFreeVertex = 0;
for (int i = 0; i < free_vertices_indexes.rows(); i++)
{
index_currentFreeVertex = free_vertices_indexes[i];
TMP_Diff = free_BeforeSmooth_Pos.row(i) - free_AfterSmooth_Pos.row(i);
Difference.row(i)[0] = TMP_Diff.dot(NormalsPerVertex.row(index_currentFreeVertex));
Difference.row(i)[1] = TMP_Diff.dot(T1.row(index_currentFreeVertex));
Difference.row(i)[2] = TMP_Diff.dot(T2.row(index_currentFreeVertex));
}
(...)
static void computeBasis(Eigen::MatrixXd &NormalsPerVertex, Eigen::MatrixXd &T1, Eigen::MatrixXd &T2, bool modeCreation)
{
//Compute the normal of each vertex
igl::per_vertex_normals(V, F, NormalsPerVertex);
if (!CreatedAdjacency)
{
igl::adjacency_list(F, AdjacencyList);
CreatedAdjacency = true;
}
//We create the basis
for (int i = 0; i < free_vertices_indexes.rows(); i++)
{
int curFreePtsIndex = free_vertices_indexes[i];
//Get the first vector
Eigen::Matrix<double, 1, 3> x = NormalsPerVertex.row(curFreePtsIndex).normalized();
int neighboorVertexID = -1;
if (modeCreation)
{
//Take the "best" neighboor
double maxDist = 0;
int indexMaxDist = AdjacencyList[curFreePtsIndex][0]; //possible to blow up here if the vertex is alone
for (int j = 0; j < AdjacencyList[curFreePtsIndex].size(); j++)
{
Eigen::Matrix<double, 1, 3> vectorToNeighboor = (V.row(AdjacencyList[curFreePtsIndex][j]) - V.row(curFreePtsIndex));
Eigen::Matrix<double, 1, 3> projectionNeighboorOnX = (vectorToNeighboor).dot(x) * x; //X has a norm = 1
double tempDist = (vectorToNeighboor - projectionNeighboorOnX).squaredNorm();
if (maxDist < tempDist)
{
maxDist = tempDist;
indexMaxDist = AdjacencyList[curFreePtsIndex][j];
}
}
neighboorVertexID = indexMaxDist;
//We store it for later use
indiceNeighboor[curFreePtsIndex] = neighboorVertexID;
}
else
{
//We pick up consistenly
neighboorVertexID = indiceNeighboor[curFreePtsIndex];
}
Eigen::Matrix<double, 1, 3> vectorToNeighboor = (V.row(neighboorVertexID) - V.row(curFreePtsIndex));
Eigen::Matrix<double, 1, 3> projectionNeighboorOnX = (vectorToNeighboor.dot(x) / x.dot(x)) * x;
Eigen::Matrix<double, 1, 3> y = (vectorToNeighboor - projectionNeighboorOnX).normalized();
//Get the third vector
Eigen::Matrix<double, 1, 3> z = x.cross(y).normalized(); // Or X Cross Y ?
//Store the vectors
NormalsPerVertex.row(curFreePtsIndex) = x.normalized();
T1.row(curFreePtsIndex) = y.normalized();
T2.row(curFreePtsIndex) = z.normalized();
}
}
Result
1.3. Deforming the smooth mesh
Deforming the mesh is pretty straighforward, as it is similar to the previous smoothing operation, only with different constrained positions.
Usage
To deform the mesh, we apply the new positions of the handles moved by the user, and we solve again a system, to obtain the smoothed positions of the free vertices.
(...)
(Saving high frequency details)
(...)
//Move the handle
igl::slice_into(handle_vertex_positions, handle_vertices, 1, V);
//Creation of B (right side)
RightSide = -1 * Afc * handle_vertex_positionsSparse;
//Solving of the system
free_AfterSmooth_Pos_Sparse = solverCholesky.solve(RightSide);
free_AfterSmooth_Pos = MatrixXd(free_AfterSmooth_Pos_Sparse);
//Put the positions of free_AfterSmooth_Pos in view
igl::slice_into(free_AfterSmooth_Pos, free_vertices_indexes, 1, V);
(...)
Result
1.4. Transferring high-frequency details to the deformed surface
We then want to mesh to have all the details it had at the begining of the process. We will transfer high-frequency details previously stored to the deformed surface. As these details were encoded in local basis, we have to recompute these local basis in a consistent way.
Usage
So we want to put back the details, captured in each local basis of the smooth meshed, in the smoothed deformed mesh.
We recompute (same function) the local basis for each vertex of the mesh. Note, this time, we pick the same neighboor we choosed the first time and do not recalculate the farest one. This is the only difference.
The main reason is, that due to the deformation, the farest neighboor might have changed, and this may leads to inconsistencies.
We then add to the actual position of each vertex of the deformed smoothed mesh, the displacement stored, projected in the local basis.
(...)
//Complete the base for each vertex
computeBasis(NormalsPerVertex, T1, T2, false);
// == Add back the details ==
for (int i = 0; i < free_vertices_indexes.rows(); i++)
{
index_currentFreeVertex = free_vertices_indexes[i];
// Calculate the addition (T1 = Y, T2 = Z, Normals = X), consistent with basis
V.row(index_currentFreeVertex) =
V.row(index_currentFreeVertex) +
Difference.row(i)[0] * NormalsPerVertex.row(index_currentFreeVertex) +
Difference.row(i)[1] * T1.row(index_currentFreeVertex) +
Difference.row(i)[2] * T2.row(index_currentFreeVertex);
}
(...)
Result
1.5. Real-time performance
To acheive real-time perfomance (10+ fps) , we need the solving step of the system to be as fast as possible. An easy solution is to prefactor fixed part of the system, to avoid recomputation of static parts.
We use the Cholesky factorization provided by Eigen.
Usage
To allow better performances, some more modifications are made :
- Instead of specified function, only one “big” function solve is used. It saves some time for copies, and allow to reuse previous data structures. (same kind of optimization that we can find in videogames-industry : dirty and hard to maintain code, but efficient)
- Time-counting functions were added to follow were the time is spend during the computation. This does have an negative influence on the performance ! I decided to keep it to allow evaluation of the code.
Exemple of trace :
Solve iteration (total 1 pass) time : 0.236447 // Total time spend to solve the current move
Solve timeTOsolveCompute : 0.043758 // Time before the call to .compute() of the solver, construting Aff, etc.
Solve compute time : 0.162786 // Time to process the .compute() of the solver
Solve timeTOsolve1 : 0.000236 // Time between the .compute() of the solver and the first .solve() of the system. Create some data structures
Solve old position time : 0.007828 // Time of the first solve of the system (old positions of handles) to get the smoothed old version of the mesh
Solve timeTOsolve2 : 0.004818 // Time between the first and the second solve of the system, some data structure manipulation and save of the details.
Solve new position time : 0.013654 // Time of the second solve of the system, to get the new positins of the free vertices, with new positions of the handles
Solve timeTOEnd : 0.003366 // Time to the end of the function, manipulating data structure
FrameRate : 4.22928 // Framerate calculated from total elapsed time.
Note : this trace is from an old version of the application, before some optimisation.
- The Aff/Afc, LML calculations were moved into the onNewHandleID function, and are only calculated once during the selection of the handles. It allows 2 things : save approximately 50% of the calculation time (see previous trace, before this update) and make the deformations “reversibles”, without artifact. (We can do a deformation and make it back without “blowing up” behaviors)
- Another optimization (called “Booster” in the interface) espace in time the new calculation. It’s does not changed the calculation time but make the animation “look smoother”. The gif of this report are not taken with this option activated. This is a visual improvement only.
(...)
if (showTime)
{
printTime();
}
if (showFrameRate)
{
printFrameRate();
}
(...)
void printTime()
{
std::cout << "Solve iteration (total 1 pass) time : " << timeTotal.getElapsedTime() << endl;
std::cout << "Solve timeTOsolveCompute : " << timeTOsolveCompute.getElapsedTime() << endl;
std::cout << "Solve compute time : " << timesolveCompute.getElapsedTime() << endl;
std::cout << "Solve timeTOsolve1 : " << timeTOsolve1.getElapsedTime() << endl;
std::cout << "Solve old position time : " << timesolve1.getElapsedTime() << endl;
std::cout << "Solve timeTOsolve2 : " << timeTOsolve2.getElapsedTime() << endl;
std::cout << "Solve new position time : " << timesolve2.getElapsedTime() << endl;
std::cout << "Solve timeTOEnd : " << timeTOEnd.getElapsedTime() << endl;
}
void printFrameRate()
{
std::cout << "FrameRate : " << 1 / timeTotal.getElapsedTime() << endl;
}
(...)
Result
Note : timing are valid on a Intel Core i5 6300HQ 3.2 Ghz.
woody-low
FrameRate : 1960.78
Solve iteration (total 1 pass) time : 0.00051
Solve timeTOsolveCompute : 1.9e-05
Solve compute time : 0
Solve timeTOsolve1 : 7.6e-05
Solve old position time : 6.7e-05
Solve timeTOsolve2 : 0.000189
Solve new position time : 5.3e-05
Solve timeTOEnd : 0.000104
woody-high
FrameRate : 315.06
Solve iteration (total 1 pass) time : 0.003174
Solve timeTOsolveCompute : 1.8e-05
Solve compute time : 0
Solve timeTOsolve1 : 4.6e-05
Solve old position time : 0.000801
Solve timeTOsolve2 : 0.000867
Solve new position time : 0.000799
Solve timeTOEnd : 0.000643
bar
FrameRate : 90.1226
Solve iteration (total 1 pass) time : 0.011096
Solve timeTOsolveCompute : 4.7e-05
Solve compute time : 0
Solve timeTOsolve1 : 7.4e-05
Solve old position time : 0.00384
Solve timeTOsolve2 : 0.001847
Solve new position time : 0.003857
Solve timeTOEnd : 0.001431
bumpy plan
FrameRate : 11.5867
Solve iteration (total 1 pass) time : 0.086306
Solve timeTOsolveCompute : 0.000315
Solve compute time : 0
Solve timeTOsolve1 : 0.00033
Solve old position time : 0.031813
Solve timeTOsolve2 : 0.011801
Solve new position time : 0.031935
Solve timeTOEnd : 0.010111
cactus
FrameRate : 86.1995
Solve iteration (total 1 pass) time : 0.011601
Solve timeTOsolveCompute : 0.000166
Solve compute time : 0
Solve timeTOsolve1 : 9.9e-05
Solve old position time : 0.006307
Solve timeTOsolve2 : 0.001841
Solve new position time : 0.002008
Solve timeTOEnd : 0.00118
camel
FrameRate : 52.1349
Solve iteration (total 1 pass) time : 0.019181
Solve timeTOsolveCompute : 0.000103
Solve compute time : 1e-06
Solve timeTOsolve1 : 0.000306
Solve old position time : 0.006273
Solve timeTOsolve2 : 0.003633
Solve new position time : 0.006251
Solve timeTOEnd : 0.002614
cylinder
FrameRate : 117.343
Solve iteration (total 1 pass) time : 0.008522
Solve timeTOsolveCompute : 2.9e-05
Solve compute time : 0
Solve timeTOsolve1 : 4.7e-05
Solve old position time : 0.002948
Solve timeTOsolve2 : 0.001443
Solve new position time : 0.002918
Solve timeTOEnd : 0.001137
hand
FrameRate : 42.6185
Solve iteration (total 1 pass) time : 0.023464
Solve timeTOsolveCompute : 0.000141
Solve compute time : 1e-06
Solve timeTOsolve1 : 0.000183
Solve old position time : 0.007935
Solve timeTOsolve2 : 0.00409
Solve new position time : 0.007923
Solve timeTOEnd : 0.003191
For more information, see : -> Repository
Note that the code is not optimized by thoughtful laziness: this code is not made to be reused as is in other applications, and if this is the case, the code will be reviewed and optimized. Thanks for your understanding.


|
Arduino NBduino Library
0.20.0
|
Public Member Functions | |
| NBduino () | |
| NBduino (const char *mqttServer, const int mqttPort, const char *mqttUser, const char *mqttPassword) | |
| NBduino (const char *mqttServer, const int mqttPort, const char *mqttUser, const char *mqttPassword, unsigned long timeToConn) | |
| setAPN (const char *APN) | |
| bool | begin () |
| wakeup () | |
| sleep () | |
| bool | reqIMEI (char *imei) |
| publish (const char *topic, const char *value) | |
| connect (const char *clientname) | |
| disconnect () | |
Definition at line 17 of file NBduinoLibrary.h.
| NBduino::NBduino | ( | ) |
This method is the constructor of the NBduuino
Definition at line 109 of file NBduinoLibrary.cpp.
| NBduino::NBduino | ( | const char * | mqttServer, |
| const int | mqttPort, | ||
| const char * | mqttUser, | ||
| const char * | mqttPassword | ||
| ) |
This method is the constructor of the NBduuino
| mqttServer | The name or the IP address of the MQTT broker (char*) |
| mqttPort | The port number of the MQTT broker (Int) |
| mqttUser | The username enabeled to access the MQTT broker (char*) |
| mqttPassword | The password to autenticate the userto access the MQTT broker (char*) |
Definition at line 122 of file NBduinoLibrary.cpp.
| NBduino::NBduino | ( | const char * | mqttServer, |
| const int | mqttPort, | ||
| const char * | mqttUser, | ||
| const char * | mqttPassword, | ||
| unsigned long | timeToConn | ||
| ) |
This method is the constructor of the NBduuino
| mqttServer | The name or the IP address of the MQTT broker (char*) |
| mqttPort | The port number of the MQTT broker (Int) |
| mqttUser | The username enabeled to access the MQTT broker (char*) |
| mqttPassword | The password to autenticate the userto access the MQTT broker (char*) |
| timeToConn | The timeout in ms in connection phase (unsigned long) |
Definition at line 141 of file NBduinoLibrary.cpp.
| bool NBduino::begin | ( | ) |
This method must be called at beginning before any publish, subscribe, wakeup and sleep call.
Definition at line 190 of file NBduinoLibrary.cpp.
| NBduino::connect | ( | const char * | clientname | ) |
This method connect to MQTT broker.
| clientname | The unique name for MQTT connection (char*) |
Definition at line 258 of file NBduinoLibrary.cpp.
| NBduino::disconnect | ( | ) |
This method disconnect from MQTT broker.
Definition at line 274 of file NBduinoLibrary.cpp.
| NBduino::publish | ( | const char * | topic, |
| const char * | value | ||
| ) |
This method publish a topic/value to the MQTT broker.
| topic | The topic name for publishing (char*) |
| value | The string to publish (char*) |
Definition at line 236 of file NBduinoLibrary.cpp.
| bool NBduino::reqIMEI | ( | char * | imei | ) |
This method return the NBduno IMEI value.
| imei | a pointer to buffer were IMEI is returned If no IMEI is read void string is returned (char*) |
Definition at line 286 of file NBduinoLibrary.cpp.
| NBduino::setAPN | ( | const char * | APN | ) |
This method set the APN
| APN | The name or the APN (String) |
Definition at line 156 of file NBduinoLibrary.cpp.
| NBduino::sleep | ( | ) |
This method asleep the NBduino shield.
Definition at line 222 of file NBduinoLibrary.cpp.
| NBduino::wakeup | ( | ) |
This method wakeup the NBduino shield.
Definition at line 209 of file NBduinoLibrary.cpp.


Reference Designs
Reference Architecture
Typical Product Product
Live Streaming
Smart Devices
Serviced Product
IoT Central
Platform
IoTHub
IoT Central
Devices
IoT
IoT Edge
Streams
Stream Analytics
Function App
SignalR
Storage
CosmosDB
Data Lake Store
SQL Server
Table Store
UI
Web App
AKS
AAD B2C
ML/Analytics
AML
Data Bricks
PowerBI
graph LR A[IoT Device] IH[IoTHub] A---IH A---IH B-->C[Function App] C-->D[Table Store] D-->F[Web App] C-->E(
IoT Hub
);


|
Finite Geometry Notes
|
Time Fold
by Steven H. Cullinane, Oct. 10, 2003
"It seems, as one becomes older,
That the past has another pattern,
and ceases to be a mere
sequence...."
-- T. S. Eliot, Four Quartets
Part I: Art Theory
From Rosalind Krauss, "Grids"
at http://www.rhizome.org/artbase/3019/grids/Rosalind.swf:
On Time and Grids
"In suggesting that the success [1] of the grid is somehow connected to its structure as myth, I may of course be accused of stretching a point beyond the limits of common sense, since myths are stories, and like all narratives they unravel through time, whereas grids are not only spatial to start with, they are visual structures that explicitly reject a narrative or sequential reading of any kind. But the notion of myth I am using here depends on a structuralist mode of analysis by which the sequential features of a story are rearranged to form a spatial organization [2].
[1] Success here refers to three things at once: a sheerly quantitative success, involving the number of artists in this century who have used grids; a qualitative success through which the grid has become the medium for some of the greatest works of modernism; and an ideological success, in that the grid is able-- in a work of whatever quality-- to emblematize the Modern.
[2] See Claude Levi-Strauss, Structural Anthropology, New York, 1963, particularly 'The Structural Analysis of Myth.' "
(The above remarks by Krauss were, apparently, originally published in "Grids," October (Summer 1979), 9: 50-64. See also The Originality of the Avant-Garde and Other Modernist Myths (1985), pp. 8-22.)
Part II: The Folding of Time
IIA... From a conversation on myth and time...
"We must conceive or imagine how Hermes flies and gets about when he carries messages from the gods - or how angels travel. And for this one must describe the spaces situated between things that are already marked out - spaces of interference, as I called them in the title of my second book on Hermes. This god or these angels pass through folded time, making millions of connections. Between has always struck me as a preposition of prime importance.
Follow the flight pattern of a fly. Doesn't time sometimes flow according to the breaks and bends that this flight seems to follow or invent? Likewise, my book Rome describes in its own way the baker's transformation... a certain folding of half a plane of dough over the other half, repeated indefinitely according to a simple rule, produces a design precisely comparable to the flight of the fly or the wasp, the one Verlaine in his famous sonnet describes as drunk from this crazy flight."
-- Michel Serres in Conversations on Science, Culture, and Time, Michel Serres and Bruno Latour, trans. Roxanne Lapidus. Ann Arbor: The University of Michigan Press, 1995. 64-5
IIB... From the mathematics of Diamond Theory...
Part III: Tradition and the Modern
In a 1922 essay, "Tradition and the Individual Talent," T. S. Eliot offered the following remarks on what he later called, in Four Quartets, the "intersection of the timeless with time":
"...the historical sense compels a man to write not merely with his own generation in his bones, but with a feeling that the whole of the literature of Europe from Homer and within it the whole of the literature of his own country has a simultaneous existence and composes a simultaneous order. This historical sense, which is a sense of the timeless as well as of the temporal and of the timeless and of the temporal together, is what makes a writer traditional. And it is at the same time what makes a writer most acutely conscious of his place in time, of his contemporaneity...."
Part IV: The Form, the Pattern
"... Only by the form, the
pattern,
Can words or music reach
The stillness...."
-- T. S. Eliot,
Four
Quartets
Four Quartets
For a discussion of the above
form, or pattern, see Diamond Theory.
Part V: Time and the Grid
Rosalind Krauss (Part I above) cites Levi-Strauss as supplying a "mode of analysis by which the sequential features of a story are rearranged to form a spatial organization."
Here is another such rearrangement, based on the "folding" shown in Part IIB above.
From Symmetry of Walsh Functions:
This correspondence may serve to illustrate what Eliot called (in Part II above) "a sense of the timeless as well as of the temporal and of the timeless and of the temporal together."
Eliot did not, of course, have, in writing Four Quartets, a 4x4 grid in mind. Such a structure does, however, help in finding the "possibilities of contrapuntal arrangement" that he sought.
For details of such possibilities, see Poetry's Bones.
For the question to which Eliot's "the point of intersection of the timeless with time" is the answer, see a work of undergraduate fiction:
"... even if we can break down time into component Walsh functions, what would it achieve?"
-- The Professor, in "Passing in
Silence,"
by Oliver Humpage
Part VI: Related Material
Quotations from Bakhtin on the Chronotope
Bakhtin and Children's Literature
From Mythic
to Linear:
Time in Children's Literature
A Wrinkle in Time, Chapter Five
Entries from the Journal of S. H. Cullinane:
Sunday, November 9, 2003 5:00 PM
For Hermann Weyl's Birthday:
A Structure-Endowed Entity
"A guiding principle in modern mathematics is this lesson: Whenever you have to do with a structure-endowed entity S, try to determine its group of automorphisms, the group of those element-wise transformations which leave all structural relations undisturbed. You can expect to gain a deep insight into the constitution of S in this way."
-- Hermann Weyl in Symmetry
Exercise: Apply Weyl's lesson to the following "structure-endowed entity."
What is the order of the resulting group of
automorphisms? (The answer will, of course, depend on which aspects of
the array's structure you choose to examine. It could be in the
hundreds, or in the hundreds of thousands.)
Tuesday, November 11, 2003 11:00 AM
Tuesday, November 11, 2003 11:11 AM
11:11
"Why do we remember the past
but not the future?"
-- Stephen Hawking,
A Brief History of Time,
Ch. 9, "The Arrow of Time"
For another look at
the arrow of time, see
Time Fold (the current page).
"Imaginary time is a relatively simple concept that is rather difficult to visualize or conceptualize. In essence, it is another direction of time moving at right angles to ordinary time. In the image at right, the light gray lines represent ordinary time flowing from left to right - past to future. The dark gray lines depict imaginary time, moving at right angles to ordinary time."
Is Time Quantized?
Yes.
Let us suppose, for the sake of argument, that time is in fact quantized and two-dimensional. Then the following picture,
from Time Fold (the current page), of "four quartets" time, of use in the study of poetry and myth, might, in fact, be of use also in theoretical physics.
In this event, last Sunday's entry (see above), on the symmetry group of a generic 4x4 array, might also have some physical significance.
At any rate, the Hawking quotation above suggests the following remarks from T. S. Eliot's own brief history of time, Four Quartets:
"It seems, as one becomes older,
That the past has another pattern,
and ceases to be a mere sequence....
I sometimes wonder if that is
what Krishna meant—
Among other things—or one way
of putting the same thing:
That the future is a faded song,
a Royal Rose or a lavender spray
Of wistful regret for those who are
not yet here to regret,
Pressed between yellow leaves
of a book that has never been opened.
And the way up is the way down,
the way forward is the way back."
Related reading:
Sunday, January 11, 2004 1:00 PM
Two-Dimensional Time
The following is from the Prime Quotes page at the website of Matthew R. Watkins...
"I have sometimes thought that the profound mystery which envelops our conceptions relative to prime numbers depends upon the limitations of our faculties in regard to time, which like space may be in essence poly-dimensional and that this and other such sort of truths would become self-evident to a being whose mode of perception is according to superficially as opposed to our own limitation to linearly extended time."
J.J. Sylvester, from "On certain inequalities relating to prime numbers", Nature 38 (1888) 259-262, and reproduced in Collected Mathematical Papers, Volume 4, page 600 (Chelsea, New York, 1973)
Translated into contemporary English, Sylvester is saying more-or-less this:"I have sometimes thought that if we were able to perceive time in some multi-dimensional way, more like a surface than like a line, then perhaps the distribution of prime numbers would be entirely self-evident, and would not seem at all mysterious to us."
Many thanks to Heckler & Coch (5/19/03) for pointing out the Sylvester quotation.
Related pages:
Page created Oct. 10, 2003. Updated Feb. 1, 2010.


Alya:
Since the beginning of class we have been told that there is no choice.
Hadji Murat was doomed from the start; the thistle was plucked in the first words.
Anna died the moment she met eyes with Vronsky.
Shklovsky believed "the beginning was already played out," that
no one can change the denouement," that "tragic endings—at the very least,
a broken heart—are inevitable in an epistolary novel."
Now, reading Dostoevsky, we learn that there is choice. We are all allowed a suddenly.


🗳SQLite Voting
Which do you prefer?
🐶
dog
😺
cat
🦓
zebra
🐨
koala
Source Code
vote.php
schema.sql (actual flag is removed)


Everytime you press a letter it will count as a guess. If your letter is incorrect you'll lose an attempt and gain a body part.