Scala classes and objects
Feb 23, 2016
When learning Scala, you often find yourself reading stuff from lots of sources with tons of information about different topics. Hence, it is not difficult to end up going down a rabbit-hole, starting reading about some cool feature or concept and end up 3 hours later trying to understand some obscure type level programming technique/pattern which is not what your original plans were.
So I wanted to go a little bit back to Scala basics in this post, targeting people who are just starting and wants to get familiar with it.
Classes
“But I heard that Scala was a functional language, shouldn’t everything be a function?”
Well, you’ve heard well. Scala is a functional language, but it’s actually more of a hybrid between the OOP and functional worlds.
In order to better organize concepts and units of logic, Scala supports classes. The idea behind them is not that different to their counterparts in Java or C++. Here is an overly simplified example:
class Lift(val levels: Int) {
private var level = 0
def currentLevel() = level
def goUp(levels: Int) = level += levels
def goDown(levels: Int) = level -= levels
def goesHigherThan(other: Lift) = this.levels > other.levels
}
We are using the class keyword to declare a Lift class. Scala makes it public by default, so there’s no need for the redundant “public” Java modifier. To construct objects of this class, the same good old new keyword is used:
val lift = new Lift(10)
In Scala, class definitions are very concise and accept parameters in their very definition, acting as their primary constructor. These parameters can generate lots of boilerplate code for us. If we specify them with the val keyword, a getter method with the same name as the field will be available for us. If instead of val we use var, both a getter and a setter will be made available to us:
class Lift(val levels: Int)
val lift = new Lift(10)
lift.levels // Int = 10
lift.levels = 50 // error: reassignment to val
vs
class Lift(var levels: Int)
val lift = new Lift(10)
lift.levels // Int = 10
lift.levels = 50
lift.levels // Int = 50
Like in Java, private fields from other classes are accessible from the current class as long as their types are the same.
def goesHigherThan(other: Lift) = this.levels > other.levels
We already mentioned the primary constructor, but what if we want to have more ways to instantiate the class? Scala allows us to define auxiliary constructors by using this keyword:
class Lift(val levels: Int) {
private var hasUndergroundLevels = false
def this(levels: Int, hasUndergroundLevels: Boolean) {
this(levels)
this.hasUndergroundLevels = hasUndergroundLevels
}
}
//now the class can be instantiated using an auxiliary constructor
val lift = new Lift(10, true)
“This is just like Java!”
In reality, this kind of constructors are not used that often. The main reason is because it’s possible to define default values to constructor parameters. Furthermore, it’s also possible to instantiate classes by passing their parameters by name:
class Lift(val levels: Int = 10, val hasUndergroundLevels: Boolean = false)
val defaultLift = new Lift
defaultLift.levels // Int = 10
defaultLeft.hasUndergroundLevels // Boolean = false
val customLift = new Lift(hasUndergroundLevels = true, levels = 3)
customLift.levels // Int = 3
customLift.hasUndergroundLevels // Boolean = true
Objects
“Aha! I know this one. Objects are instances of those classes that you mentioned before!”
Well, that’s indeed what an object is, but Scala has a reserved keyword and logic behind a construct that is also called Object. A Scala object defines a single instance of a class that encapsulates logic.
“Are you saying that is a singleton?
Truth is, that singletons are as bad as the usage that you make of them. If you’re aware that a Scala object is a singleton and use it as such, there should be nothing wrong with it. Going a bit further, Scala objects are a very helpful construct to define utility methods that do not require state to compute. A rather silly example, could be a CaseConverter object which operates on Strings:
object CaseConverter {
def toPascalCase(input: String): String = input.split(" ").map(_.capitalize).mkString
def toSnakeCase(input: String): String = input.split(" ").map(_.toLowerCase).mkString("_")
def toCamelCase(input: String): String = {
def lowerFirstChar(string: String): String = {
string.head.toLower.toString + string.tail
}
lowerFirstChar(toPascalCase(input))
}
}
This object can then be used without instantiating, pretty much like a static method:
CaseConverter.toPascalCase("my shiny variable")
res0: String = MyShinyVariable
CaseConverter.toSnakeCase("my shiny variable")
res1: String = my_shiny_variable
CaseConverter.toCamelCase("my shiny variable")
res2: String = myShinyVariable
Objects are very much like a Scala class but they do not receive constructor parameters. A typical use case for objects, is to provide static and instance methods to a class. This is known as acting as a Companion Object. For this to occur, both class and object should have the very same name and should live in the same file. Instance methods are achieved by implementing the apply method:
class Person(val name: String, val age: Int)
object Person {
def apply(age: Int): Person = new Person("", age)
def apply(name: String, age: Int): Person = new Person(name, age)
}
At a first glance, this might seem like an overkill and completely unnecessary. But actually, having objects acting as factories for creating instances of their accompanied classes can enhance Scala code readability a lot.
val unknownPerson = Person(20)
val knownPerson = Person("Alan", 25)
“Wait! Where did the new keyword go?”
Companion objects have the capability of removing the need for the new keyword when instantiating the accompanied classes. This is pretty handy, specially when dealing with nested structures such as lists of lists:
val list = new List(new List(1), new List(2,5), new List(4,4))
vs
val list = List(List(1), List(2,5), List(4,4))
A final common use case for objects is to define a set of constants or enumerations. The easiest way to define them is by extending scala Enumeration:
object CardinalPoint extends Enumeration {
type CardinalPoint = Value
val North, South, West, East = Value
}
The type CardinalPoint is not actually necessary, but it’s a good thing to add if type enforcing is needed in a function:
def move(towards: CardinalPoint): Position = ???
// This function can be called like so:
move(CardinalPoint.North)
It’s also possible to give custom values to the elements of an enumeration. This way, the internal representation can be the one used by the algorithm but the code can read much better having meaningful names:
object CardinalPoint extends Enumeration {
val North = "N"
val South = "S"
val West = "W"
val East = "E"
}
...
val point = "N"
if (point == CardinalPoint.North) "I'm heading North!"
else "I'm lost :("
Wrapping up
So hopefully this overview of classes and objects helps someone that is starting with Scala. There are a few more things that I could have mentioned about both classes and objects, but this overview was meant to cover just the basics and the most common use cases.
In the near future I’d like to continue this post by discussing case classes, which are one of the corner stones of the Scala language and are very much related to both classes and objects.
Tweet


The Sort Mail From dialog box allows you to set up a rule based on the From: address of the current viewed mail message.
This is a Hot Spot image. Move your mouse pointer over the image
and when the mouse pointer changes to the shape of a hand click
the left mouse button once for extra help.
You can choose to move messages from this address to an existing folder or to a new folder.
Ameol can scan the current mail folder for other messages from this address and sort them into the selected folder. To do this select the Move other messages from this user to the specified folder option.


?EW^ORR
BOTAČ
ÁJ,
AL
GJ
Plants
of
Trinidad,
British
West
Indies
Erythrina
Poeppigiana
(Walp.)
Cook
Det.
by
B.A.Kruko’F,
1938.
SADDLE
ROAD
N.
L.
BRITTON
/
T.
E.
HAZEN
1
February
28,
1020
1619013
Legend -
Level of confidence that token is an accurately-transcribed word
extremely low
very low
low
undetermined
medium
high
very high


|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object de.ilu.movingletters.MovingLetters
public class MovingLetters
a typeset for moving letters with given size and agility.
| Field Summary | |
|---|---|
private int |
mAgility
agility of the letters |
private Letter[] |
mFont
letter definition |
private int |
mHeight
height for the letters |
private int |
mJitter
number of pixels to randomly move the letters |
private int |
mJitterHalf
number of pixels to randomly move the letters-helper value |
private Letter[] |
mLetters
list of letters indexable by character-values 0-255 |
private int[] |
mPointLocX
list of pixel x-coordinates of the letter coordinates, all relative to letter coordinate 1 |
private int[] |
mPointLocY
list of pixel y-coordinates of the letter coordinates, all relative to letter coordinate 1 |
private processing.core.PApplet |
mRuntime
reference to the processing runtime |
private static int |
NUM_LETTER_COORDINATES
number of letter coordinates |
| Constructor Summary | |
|---|---|
MovingLetters(processing.core.PApplet pRuntime,
int pHeight)
create moving letters with given height and an agility of 1. |
|
MovingLetters(processing.core.PApplet pRuntime,
int pHeight,
int pAgility)
create moving letters with given height and and agility. |
|
MovingLetters(processing.core.PApplet pRuntime,
int pHeight,
int pAgility,
int pJitter)
create moving letters with given height and and agility. |
| Method Summary | |
|---|---|
private void |
calcPointLoc(int pMovement)
(re)calculate pixel coordinates for letter coordinates relative to letter coordinate 1. |
(package private) processing.core.PApplet |
getRuntime()
get processing runtime. |
(package private) int |
getX(int pPos)
get a pixel x-coordinate for a letter coordinate. |
(package private) int |
getY(int pPos)
get a pixel y-coordinate for a letter coordinate. |
void |
text(java.lang.String pData,
int pX,
int pY)
draw text at given coordinate. |
void |
text(java.lang.String pData,
int pX,
int pY,
int pDotSize)
draw text at given coordinate. |
void |
text(java.lang.String pData,
int pX,
int pY,
int pDotSize,
int pLineWidth)
draw text at given coordinate. |
void |
text(java.lang.String pData,
int pX,
int pY,
int pDotSize,
int pLineWidth,
int[] pColors)
draw text at given coordinate. |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
|---|
private static final int NUM_LETTER_COORDINATES
private Letter[] mFont
private processing.core.PApplet mRuntime
private Letter[] mLetters
private int[] mPointLocX
private int[] mPointLocY
private int mAgility
private int mHeight
private int mJitter
private int mJitterHalf
| Constructor Detail |
|---|
public MovingLetters(processing.core.PApplet pRuntime, int pHeight)
pRuntime
- the reference to the processing runtime.pHeight
- wanted height of the letters.public MovingLetters(processing.core.PApplet pRuntime, int pHeight, int pAgility)
pAgility
- indicates for how many frames the pixel coordinates of the letter coordinates should kept unchanged.pRuntime
- the reference to the processing runtime.pHeight
- wanted height of the letters.public MovingLetters(processing.core.PApplet pRuntime, int pHeight, int pAgility, int pJitter)
pAgility
- indicates for how many frames the pixel coordinates of the letter coordinates should kept unchanged.pRuntime
- the reference to the processing runtime.pHeight
- wanted height of the letters.pJitter
- number of pixels to randomly move the edges of the letters. This must be divideable by 2!| Method Detail |
|---|
public void text(java.lang.String pData, int pX, int pY)
pData
- text string.pX
- x-xoordinate for upper left corner of first letter.pY
- y-xoordinate for upper left corner of first letter.public void text(java.lang.String pData, int pX, int pY, int pDotSize)
pData
- text string.pX
- x-xoordinate for upper left corner of first letter.pY
- y-xoordinate for upper left corner of first letter.pDotSize
- size of dots to draw at start/end of lines. 0 for no dots.public void text(java.lang.String pData, int pX, int pY, int pDotSize, int pLineWidth)
pData
- text string.pX
- x-xoordinate for upper left corner of first letter.pY
- y-xoordinate for upper left corner of first letter.pDotSize
- size of dots to draw at start/end of lines. 0 for no dots.pLineWidth
- width of the lines for the text.public void text(java.lang.String pData, int pX, int pY, int pDotSize, int pLineWidth, int[] pColors)
pData
- text string.pX
- x-xoordinate for upper left corner of first letter.pY
- y-xoordinate for upper left corner of first letter.pDotSize
- size of dots to draw at start/end of lines. 0 for no dots.pLineWidth
- width of the lines for the text.pColors
- an array of colors which can be used by the #color; syntax.int getX(int pPos)
pPos
- letter coordinate.
int getY(int pPos)
pPos
- letter coordinate.
private void calcPointLoc(int pMovement)
pMovement
- processing.core.PApplet getRuntime()
|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Construct a new renderer.
A selector which matches the close icon node in a tab.
Create the class name for the tab icon.
The data to use for the tab.
The full class name for the tab icon.
Create the class name for the tab.
The data to use for the tab.
The full class name for the tab.
Create the dataset for a tab.
The data to use for the tab.
The dataset for the tab.
Create a unique render key for the tab.
The data to use for the tab.
The unique render key for the tab.
This method caches the key against the tab title the first time the key is generated. This enables efficient rendering of moved tabs and avoids subtle hover style artifacts.
Create the inline style object for a tab.
The data to use for the tab.
The inline style data for the tab.
Render the close icon element for a tab.
The data to use for rendering the tab.
A virtual element representing the tab close icon.
Render the icon element for a tab.
The data to use for rendering the tab.
A virtual element representing the tab icon.
Render the label element for a tab.
The data to use for rendering the tab.
A virtual element representing the tab label.
Render the virtual element for a tab.
The data to use for rendering the tab.
A virtual element representing the tab.
Generated using TypeDoc
The default implementation of
IRenderer
.Notes
Subclasses are free to reimplement rendering methods as needed.


Royal Mint releases poppy coin to mark 100 years of Remembrance Day
The coin is decorated with a single Flanders red poppy and the phrase, “We will remember them” – which originates from Laurence Binyon’s poem ’For the Fallen”
by Linda HowardThis year marks a century of commemorating Remembrance Day across the UK.
Originally conceived as a means of paying respect to servicemen and women who died in the First World War, the ceremony has expanded to include tributes to those who have given their lives in service to their country in subsequent conflicts.
The Royal Mint has released a new Remembrance Day 2019 £5 coin which offers a permanent and reverent way to remember the sacrifices of our military personnel over the past century.
View the Remembrance Day coin collection here
The Remembrance Day 2019 UK £5 Brilliant Uncirculated Coin, £17
A keepsake for a veteran or military enthusiast, this commemorative coin honours 100 years of Remembrance Day and comes with booklet sharing the fascinating history of Remembrance.
The Remembrance Day 2019 UK £5 Silver Proof Coin (limited edition), £90
The design incorporates a line from the Ode of Remembrance.
The Remembrance Day 2019 UK £5 Silver Proof Piedfort Coin (limited edition), £170
This commemorative coin is double the weight of the silver Proof edition and limited to just 775 - almost half the number available last year.


{% extends 'base.html'%} {% block content%} {% block styles %} {{super()}} {% endblock %}
If you don't have an account? Sign Up


CHILDREN OF THE REVOLUTION A film review by Jun Yan Copyright 1997 Jun Yan
It's Australia, 1953.  Although without much support in her own world, she stands by her faith and writes letters to Stalin with all her admiration. They somehow get to catch Stalin's eyes (Stalin played by Murray Abraham, who in no way reminds me of Stalin at all in his appearance despite his chunky nose). The next thing we know, she's on her way to Moscow and has a one-night-stand with him which both kills him with a heart attack and inpregnated her. Back to Australia, Joan marries her puppy lover Zackery Welch (played with ease by Geoffery Rush) and makes him swear never tell anyone he's not really her boy's father.
The boy, Joseph Welch, grows up with a strange interest in going to jail, and he does finally, for refusing to register in the army to go to Vietnam. Although brain-washed by his mother all his life about the greatness of Communism and Stalin, he does later recognizes the ugly truth of his father. He seems to be a sweet natured kid at first. However, as time passes by, he slowly develops an appetite for power and dominance and becomes alarming like one certain famous historical figure.
As a political satire, the film definitely shows its weakness in dealing with the reality of the Soviet Union and Stalin. All the scenes in Moscow with Stalin and his guards/followers fall into the level of forced comedy that's not very funny. But the parts with Joan and people surrounding her and her passion for Stalin as well as Communism are quite amuzing -- at least to me, who grew up in a Communist country yet am never convinced and converted of the idea. She is more of a comical and pitiful figure than a force that persuades anyone.
Other characters in the film are less one-dimensional and more interesting. The passive, good-hearted husband Welch, the secretive (at least trying hard to be secretive) KGB/Secret Service Man and double agent David (played with understated humor by Sam Neil) who has a crush on Joan and fantacizes being Joe's father, and Joe's police officer wife, Anna, who gets into dating him by repeated arresting him in anti-Vietnam war protests. This is probably the funniest and most genuine part of the film and gains much chuckles from the audience. They are not simplified personalities that we've seen in other films and they keep me interested.
The plot itself is not that intersting and engaging. The writer does not seem to have made up his mind as to what would be the theme or central issue of the film. Ideas are not developed and story lines scatter all over the place without a clear destination. A clear example is the transformation of Joe Welch as his hunger for power and control grows. He is a sweet kid when he grows up and dates Anna. He clearly recognizes Stalin's brutality and cruelty. He even saves a prison officer's life risking his own.  However, the filmmaker never makes clear just what his ultimate intentions are. He said it's a "revolution." But his own cynicism and disbelief in Communism hardly support that claim. And the finale is strange and illogical.
I certainly had some good chuckles out of this film, but it's hardly a refined piece of work. I give it a C+.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Contact Us
account_circle
First Name
account_circle
Last Name
mail_outline
Email
mode_edit
Send Us Your Inquiries ...
ADDRESS
Location
Phone Number
HOURS
MON-FRI
SAT - 9AM - 2PM
SUN CLOSED


VSL // The Cultured Valentines
* For the Adventurous Valentine, the decadence, mystery and seduction of the theatre/dining/nightclub experience, Queen of the Night
today’s Very Short List:
culture 5 Feb 2014
Jordan Roth is the President of Jujamcyn Theaters
Subscribe
* For the Glittering Valentine, the sparkling imagination and exquisite craftsmanship of a lifetime of Jewels by JAR
* For the Funny Valentine, the hilarity and hijinks, the wit and whimsy, the music and mayhem of A Gentleman’s Guide to Love and Murder
http://link.nyobserver.com/516ca68465217dc6e1b9a3a61fau0.bu1/UgqgLuYQbsTE3UNnD2679 very short list is a
delightful e-mail that shares
cultural gems from a
different curator every day.
If you have any problems reading this e-mail, click here
http://link.nyobserver.com/516ca68465217dc6e1b9a3a61fau0.bu1/UgqgLuYQbsTE3UNnE5f20
Subscribe
Forward
My Account
Unsubscribe
tech 3 Feb 2014
Reuben Ingber on how to get yourself in the tech game.
design 31 Jan 2014
Carly Ayres on getting in touch with your inner child.
style 29 Jan 2014
Amrit Richmond on Tech x Style.
Editorial Policy
Privacy Policy
Contact Us
Press
Terms + Conditions
very fine print: ©2014
Observer VSL LLC.
321 West 44th Street, 6th Floor
New York, NY 10036 USA
All rights reserved.
Questions?<PHONE_NUMBER>.
This message was intended for<EMAIL_ADDRESS>If you believe this has been sent to you in error, please safely unsubscribe


--- layout: slides title: 'XMPP-FTW @ Realtime Conf 2013' description: 'A worldwind tour around the why and how of XMPP-FTW' theme: simple ---
XMPP For The Web World?
The goal of XMPP-FTW is to make XMPP really simple to use for (web) developers
Written in nodejs
Proxy between XMPP server + browser
Doesn't mandate a transport
Acts as an XMPP client (using `node-xmpp`)
Can be run in the browser too
var socket = new Primus('{{ site.prefix }}{{ site.host }}{{ site.port }}')
socket.on('online', function() {
console.log('i haz websocket')
socket.emit('xmpp.login', credentials)
socket.on('xmpp.connection', function() {
// Now we can do all the things!
})
})
socket.emit(
'xmpp.chat.message',
{
"to"<EMAIL_ADDRESS>/* "content": "Hello world", */
/* "format": "plain", */
/* "state": "composing" */
}
)
socket.on('xmpp.chat.message', function(data) {
console.log(data)
})
(Payloads where a response will be received)
socket.emit(
'xmpp.area.specific',
{
"your": "payload"
},
function(error, data) { console.log(error, data) }
)
Apply standard key names and formats across XMPP messages for convenience and familiarity
socket.emit(
'xmpp.discover.info',
{
"of": "evilprofessor.co.uk"
},
function(error, features) {
console.log(error, features)
}
)
Head over to {{ site.prefix }}{{ site.host }}{{ site.port }}/demo
xmpp.login
{
"jid"<EMAIL_ADDRESS>"password": "password",
"register": true,
"host": "localhost"
}
xmpp.pubsub.publish
{
"to": "pubsub.evilprofessor.co.uk",
"node": "xmpp-ftw updates",
"content": "<your name in lights?>"
}
xmpp.pubsub.retrieve
{
"to": "pubsub.evilprofessor.co.uk",
"node": "xmpp-ftw updates"
}
Hint: Ctrl/Cmd + Click to enlarge results
Tell the server we're here & listening...
xmpp.presence
{}
xmpp.pubsub.subscribe
{
"to": "pubsub.evilprofessor.co.uk",
"node": "xmpp-ftw updates"
}
Items are now received via the xmpp.pubsub.push.item event
...and what did we just do?
...a web-app without a backend?
npm i xmpp-ftw-demo npm start open http://localhost:3000
...or...
Hosted for free by nodejitsu under the open source scheme. Please show them some ❤


We're sorry, but you seem to be using some form of "software" which is trying to imitate a browser but failing miserably™.
Please download and install a REAL browser, and try again!
Here are some suggestions:
| Windows | Mac OS X | Linux |
|---|---|---|
| Firefox | Firefox | Firefox |
| Opera | Opera | Opera |
| Safari | Safari | Midori |
| Chrome | ||
| Konqueror | Konqueror | Konqueror |
| Lynx | Lynx | Lynx |


6.5.2
- [Fix] use
safer-buffer
instead of Buffer
constructor
- [Refactor] utils:
module.exports
one thing, instead of mutating exports
(#230)
- [Dev Deps] update
browserify
, eslint
, iconv-lite
, safer-buffer
, tape
, browserify
6.5.1
- [Fix] Fix parsing & compacting very deep objects (#224)
- [Refactor] name utils functions
- [Dev Deps] update
eslint
, @ljharb/eslint-config
, tape
- [Tests] up to
node
v8.4
; use nvm install-latest-npm
so newer npm doesn’t break older node
- [Tests] Use precise dist for Node.js 0.6 runtime (#225)
- [Tests] make 0.6 required, now that it’s passing
- [Tests] on
node
v8.2
; fix npm on node 0.6
6.5.0
- [New] add
utils.assign
- [New] pass default encoder/decoder to custom encoder/decoder functions (#206)
- [New]
parse
/stringify
: add ignoreQueryPrefix
/addQueryPrefix
options, respectively (#213)
- [Fix] Handle stringifying empty objects with addQueryPrefix (#217)
- [Fix] do not mutate
options
argument (#207)
- [Refactor]
parse
: cache index to reuse in else statement (#182)
- [Docs] add various badges to readme (#208)
- [Dev Deps] update
eslint
, browserify
, iconv-lite
, tape
- [Tests] up to
node
v8.1
, v7.10
, v6.11
; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4
- [Tests] add
editorconfig-tools
6.4.0
- [New]
qs.stringify
: add encodeValuesOnly
option
- [Fix] follow
allowPrototypes
option during merge (#201, #201)
- [Fix] support keys starting with brackets (#202, #200)
- [Fix] chmod a-x
- [Dev Deps] update
eslint
- [Tests] up to
node
v7.7
, v6.10
,v4.8
; disable osx builds since they block linux builds
- [eslint] reduce warnings
6.3.2
- [Fix] follow
allowPrototypes
option during merge (#201, #200)
- [Dev Deps] update
eslint
- [Fix] chmod a-x
- [Fix] support keys starting with brackets (#202, #200)
- [Tests] up to
node
v7.7
, v6.10
,v4.8
; disable osx builds since they block linux builds
6.3.1
- [Fix] ensure that
allowPrototypes: false
does not ever shadow Object.prototype properties (thanks, @snyk!)
- [Dev Deps] update
eslint
, @ljharb/eslint-config
, browserify
, iconv-lite
, qs-iconv
, tape
- [Tests] on all node minors; improve test matrix
- [Docs] document stringify option
allowDots
(#195)
- [Docs] add empty object and array values example (#195)
- [Docs] Fix minor inconsistency/typo (#192)
- [Docs] document stringify option
sort
(#191)
- [Refactor]
stringify
: throw faster with an invalid encoder
- [Refactor] remove unnecessary escapes (#184)
- Remove contributing.md, since
qs
is no longer part of hapi
(#183)
6.3.0
- [New] Add support for RFC 1738 (#174, #173)
- [New]
stringify
: Add serializeDate
option to customize Date serialization (#159)
- [Fix] ensure
utils.merge
handles merging two arrays
- [Refactor] only constructors should be capitalized
- [Refactor] capitalized var names are for constructors only
- [Refactor] avoid using a sparse array
- [Robustness]
formats
: cache String#replace
- [Dev Deps] update
browserify
, eslint
, @ljharb/eslint-config
; add safe-publish-latest
- [Tests] up to
node
v6.8
, v4.6
; improve test matrix
- [Tests] flesh out arrayLimit/arrayFormat tests (#107)
- [Tests] skip Object.create tests when null objects are not available
- [Tests] Turn on eslint for test files (#175)
6.2.3
- [Fix] follow
allowPrototypes
option during merge (#201, #200)
- [Fix] chmod a-x
- [Fix] support keys starting with brackets (#202, #200)
- [Tests] up to
node
v7.7
, v6.10
,v4.8
; disable osx builds since they block linux builds
6.2.2
- [Fix] ensure that
allowPrototypes: false
does not ever shadow Object.prototype properties
6.2.1
- [Fix] ensure
key[]=x&key[]&key[]=y
results in 3, not 2, values
- [Refactor] Be explicit and use
Object.prototype.hasOwnProperty.call
- [Tests] remove
parallelshell
since it does not reliably report failures
- [Tests] up to
node
v6.3
, v5.12
- [Dev Deps] update
tape
, eslint
, @ljharb/eslint-config
, qs-iconv
- [New] pass Buffers to the encoder/decoder directly (#161)
- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160)
- [Fix] fix compacting of nested sparse arrays (#150)
**6.1.2
- [Fix] follow
allowPrototypes
option during merge (#201, #200)
- [Fix] chmod a-x
- [Fix] support keys starting with brackets (#202, #200)
- [Tests] up to
node
v7.7
, v6.10
,v4.8
; disable osx builds since they block linux builds
6.1.1
- [Fix] ensure that
allowPrototypes: false
does not ever shadow Object.prototype properties
- [New] allowDots option for
stringify
(#151)
- [Fix] "sort" option should work at a depth of 3 or more (#151)
- [Fix] Restore
dist
directory; will be removed in v7 (#148)
6.0.4
- [Fix] follow
allowPrototypes
option during merge (#201, #200)
- [Fix] chmod a-x
- [Fix] support keys starting with brackets (#202, #200)
- [Tests] up to
node
v7.7
, v6.10
,v4.8
; disable osx builds since they block linux builds
6.0.3
- [Fix] ensure that
allowPrototypes: false
does not ever shadow Object.prototype properties
- [Fix] Restore
dist
directory; will be removed in v7 (#148)
- Revert ES6 requirement and restore support for node down to v0.8.
- #127 Fix engines definition in package.json
- #124 Use ES6 and drop support for node < v4
5.2.1
- [Fix] ensure
key[]=x&key[]&key[]=y
results in 3, not 2, values
- #64 Add option to sort object keys in the query string
- #117 make URI encoding stringified results optional
- #106 Add flag
skipNulls
to optionally skip null values in stringify
- #114 default allowDots to false
- #100 include dist to npm
- #98 make returning plain objects and allowing prototype overwriting properties optional
- #89 Add option to disable "Transform dot notation to bracket notation"
- #80 qs.parse silently drops properties
- #77 Perf boost
- #60 Add explicit option to disable array parsing
- #74 Bad parse when turning array into object
- #81 Add a
filter
option
- #68 Fixed issue with recursion and passing strings into objects.
- #66 Add mixed array and object dot notation support Closes: #47
- #76 RFC 3986
- #85 No equal sign
- #84 update license attribute
- #73 Property 'hasOwnProperty' of object #
- #70 Add arrayFormat option
- #59 make sure array indexes are >= 0, closes #57
- #58 make qs usable for browser loader
- #55 allow merging a string into an object
- #52 Return "undefined" and "false" instead of throwing "TypeError".
- #50 add option to omit array indices, closes #46
- #39 Is there an alternative to Buffer.isBuffer?
- #49 refactor utils.merge, fixes #45
- #41 avoid browserifying Buffer, for #39
- #38 how to handle object keys beginning with a number
- #37 parser discards first empty value in array
- #36 Update to lab 4.x
- #33 Error when plain object in a value
- #34 use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty
- #24 Changelog? Semver?
- #32 account for circular references properly, closes #31
- #31 qs.parse stackoverflow on circular objects
- #26 Don't use Buffer global if it's not present
- #30 Bug when merging non-object values into arrays
- #29 Don't call Utils.clone at the top of Utils.merge
- #23 Ability to not limit parameters?
- #22 Enable using a RegExp as delimiter
- #18 Why is there arrayLimit?
- #20 Configurable parametersLimit
- #21 make all limits optional, for #18, for #20
- #19 Don't overwrite null values
- #16 ignore non-string delimiters
- #15 Close code block
- #12 Add optional delim argument
- #13 fix #11: flattened keys in array are now correctly parsed
- #7 Empty values of a POST array disappear after being submitted
- #9 Should not omit equals signs (=) when value is null
- #6 Minor grammar fix in README
- #5 array holes incorrectly copied into object on large index


Match play. 2-2 to 7. How should Red play 55?
pips Red=153 White=143
(CorrectAnswer= 0/0, ErrorScore= 0)
It is too early to run with 20/10(2), especially with a blot on the 14-pt. Red has the choice of 13/3, 8/3(2) or 13/3, 8/3, 6/1*.
The blot on White’s 2-pt just edges the decision towards the hitting play but the two plays are only a whisker apart. The key is to avoid 20/10(2).
The blot on White’s 2-pt just edges the decision towards the hitting play but the two plays are only a whisker apart. The key is to avoid 20/10(2).
1. Cubeful 2-ply 13/3 8/3(2) Eq.: +0.322 0.571 0.166 0.004 - 0.429 0.069 0.002 2. Cubeful 2-ply 20/10(2) Eq.: +0.308 (-0.014) 0.600 0.086 0.002 - 0.400 0.067 0.001 3. Cubeful 2-ply 13/3 8/3 6/1* Eq.: +0.307 (-0.015) 0.561 0.181 0.005 - 0.439 0.075 0.002 4. Cubeful 2-ply 20/15(2) 8/3(2) Eq.: +0.306 (-0.016) 0.590 0.112 0.003 - 0.410 0.074 0.001 5. Cubeful 0-ply 13/3(2) Eq.: +0.162 (-0.160) 0.525 0.147 0.006 - 0.475 0.073 0.002


Next: Format Directive Interface, Previous: Pretty Printer Concepts, Up: Pretty Printer Concepts
The actions of the pretty printer when a piece of output is too large to fit in the space available can be precisely controlled. Three concepts underlie the way these operations work—logical blocks , conditional newlines , and sections . Before proceeding further, it is important to define these terms.
The first line of Figure 22–3 shows a schematic piece of output. Each of the characters in the output is represented by "-". The positions of conditional newlines are indicated by digits. The beginnings and ends of logical blocks are indicated by "<" and ">" respectively.
The output as a whole is a logical block and the outermost section. This section is indicated by the 0’s on the second line of Figure 1. Logical blocks nested within the output are specified by the macro pprint-logical-block. Conditional newline positions are specified by calls to pprint-newline. Each conditional newline defines two sections (one before it and one after it) and is associated with a third (the section immediately containing it).
The section after a conditional newline consists of: all the output up to, but not including, (a) the next conditional newline immediately contained in the same logical block; or if (a) is not applicable, (b) the next newline that is at a lesser level of nesting in logical blocks; or if (b) is not applicable, (c) the end of the output.
The section before a conditional newline consists of: all the output back to, but not including, (a) the previous conditional newline that is immediately contained in the same logical block; or if (a) is not applicable, (b) the beginning of the immediately containing logical block. The last four lines in Figure 1 indicate the sections before and after the four conditional newlines.
The section immediately containing a conditional newline is the shortest section that contains the conditional newline in question. In Figure 22–3, the first conditional newline is immediately contained in the section marked with 0’s, the second and third conditional newlines are immediately contained in the section before the fourth conditional newline, and the fourth conditional newline is immediately contained in the section after the first conditional newline.
<-1---<--<--2---3->--4-->-><PHONE_NUMBER>00000000000000000 11<PHONE_NUMBER>11111111111111 22<PHONE_NUMBER><PHONE_NUMBER>4444 44444
Figure 22–2: Example of Logical Blocks, Conditional Newlines, and Sections
Whenever possible, the pretty printer displays the entire contents of a section on a single line. However, if the section is too long to fit in the space available, line breaks are inserted at conditional newline positions within the section.
Next: Format Directive Interface, Previous: Pretty Printer Concepts, Up: Pretty Printer Concepts


The websocket connection to the Signal K server.
More...
#include <ws_client.h>
|
| | WSClient (String config_path, SKDelta *sk_delta, String server_address, uint16_t server_port, String sk_permission="readwrite") |
| |
| void | enable () |
| |
| void | on_disconnected () |
| |
| void | on_error () |
| |
| void | on_connected (uint8_t *payload) |
| |
| void | on_receive_delta (uint8_t *payload) |
| |
| void | on_receive_updates (DynamicJsonDocument &message) |
| |
| void | on_receive_put (DynamicJsonDocument &message) |
| |
| void | connect () |
| |
| void | loop () |
| |
| bool | is_connected () |
| |
| void | restart () |
| |
| void | send_delta () |
| |
| void | sendTXT (String &payload) |
| |
| const String | get_server_address () const |
| |
| const uint16_t | get_server_port () const |
| |
| const WSConnectionState | get_connection_state () const |
| |
| virtual void | get_configuration (JsonObject &doc) override final |
| |
| virtual bool | set_configuration (const JsonObject &config) override final |
| |
| virtual String | get_config_schema () override |
| |
| ValueProducer< int > & | get_delta_count_producer () |
| |
| | Configurable (String config_path) |
| |
| virtual void | save_configuration () |
| |
| | ValueProducer () |
| |
| virtual const WSConnectionState & | get () const |
| |
| void | connect_to (ValueConsumer< WSConnectionState > *consumer, uint8_t input_channel=0) |
| |
| Transform< WSConnectionState, T2 > * | connect_to (Transform< WSConnectionState, T2 > *consumer_producer, uint8_t input_channel=0) |
| |
| void | connectTo (ValueConsumer< WSConnectionState > *consumer, uint8_t input_channel=0) |
| |
| Transform< WSConnectionState, T2 > * | connectTo (Transform< WSConnectionState, T2 > *consumer_producer, uint8_t input_channel=0) |
| |
| void | emit (WSConnectionState new_value) |
| |
| | Observable () |
| |
| | Observable (Observable &&other) |
| | Move constructor. More...
|
| |
| void | notify () |
| |
| void | attach (std::function< void()> observer) |
| |
The websocket connection to the Signal K server.
- See also
- SensESPApp
Definition at line 27 of file ws_client.h.
◆ WSClient()
| WSClient::WSClient |
( |
String |
config_path, |
|
|
SKDelta * |
sk_delta, |
|
|
String |
server_address, |
|
|
uint16_t |
server_port, |
|
|
String |
sk_permission = "readwrite" |
|
) |
| |
◆ connect()
| void WSClient::connect |
( |
| ) |
|
◆ enable()
| void WSClient::enable |
( |
| ) |
|
◆ get_config_schema()
| String WSClient::get_config_schema |
( |
| ) |
|
|
overridevirtual |
◆ get_configuration()
| void WSClient::get_configuration |
( |
JsonObject & |
configObject | ) |
|
|
finaloverridevirtual |
Returns the current configuration data as a JsonObject. In general, the current state of local member variables are saved to a new object created with JsonDocument::as<JsonObject>() and returned.
Reimplemented from Configurable.
Definition at line 525 of file ws_client.cpp.
◆ get_connection_state()
◆ get_delta_count_producer()
◆ get_server_address()
| const String WSClient::get_server_address |
( |
| ) |
const |
|
inline |
◆ get_server_port()
| const uint16_t WSClient::get_server_port |
( |
| ) |
const |
|
inline |
◆ is_connected()
| bool WSClient::is_connected |
( |
| ) |
|
◆ loop()
◆ on_connected()
| void WSClient::on_connected |
( |
uint8_t * |
payload | ) |
|
◆ on_disconnected()
| void WSClient::on_disconnected |
( |
| ) |
|
◆ on_error()
| void WSClient::on_error |
( |
| ) |
|
◆ on_receive_delta()
| void WSClient::on_receive_delta |
( |
uint8_t * |
payload | ) |
|
◆ on_receive_put()
| void WSClient::on_receive_put |
( |
DynamicJsonDocument & |
message | ) |
|
◆ on_receive_updates()
| void WSClient::on_receive_updates |
( |
DynamicJsonDocument & |
message | ) |
|
◆ restart()
| void WSClient::restart |
( |
| ) |
|
◆ send_delta()
| void WSClient::send_delta |
( |
| ) |
|
◆ sendTXT()
| void WSClient::sendTXT |
( |
String & |
payload | ) |
|
Sends the specified payload to the server over the websocket this client is connected to. If no connection currently exist, the call is safely ignored.
Definition at line 232 of file ws_client.cpp.
◆ set_configuration()
| bool WSClient::set_configuration |
( |
const JsonObject & |
config | ) |
|
|
finaloverridevirtual |
Sets the current state of local member variables using the data stored in config.
Reimplemented from Configurable.
Definition at line 567 of file ws_client.cpp.
◆ test_auth_on_each_connect_
| bool WSClient::test_auth_on_each_connect_ = true |
|
static |
If set to TRUE, the authentication token will be tested each time the device connects to the server. If set to false, the authentication token will not be retested on subsequent connections.
Definition at line 73 of file ws_client.h.
The documentation for this class was generated from the following files:


{% extends 'base.html' %}
{% block title %}
Prediction
{% endblock title %}
{% block content %}
Disease Prediction
Our system {{percent}} % sure that patient has the selected disease
{% else %}
Our system {{safe}} % sure that patient is safe
{% endif %}


Command
Documentation
engine
system
input
command
Command
Description
Public
Protected
Private
Related
All
Inheritance
All Members
Brief description
Command
Variants
Brief description
()
(const Command &)
(basic::String, basic::String, KEY, KEY, KEY, BUTTON)
GetControlCount
GetControlString
GetDescription
GetFirstKey
GetMouse
GetName
GetSecondKey
GetThirdKey
operator=
SetDescription
SetName
Update
~Command


Knock knock!
Who's there?
A broken pencil
A broken pencil who?
Nevermind, it's pointless!
...
One morning, the sun came up...
The birds were chirping...
I decided to turn on the TV.
The Pirates were winning!
It was then I realized...
My video game was still on!


Turtle Tab
Turtle Tab is a Chrome extension with a minimalist design and additional tools to help you be more productive.
Features
Turtle Tab features at a glance
- Search Google from the homepage
- See the local weather, or weather at any location
- Write notes and todo lists
- See your bookmarks
- See and clear your history
- Enable and disable Chrome extensions
Demo
Install
Free and open source browser extension
Download and install now
Subscribe to the Turtles Tab newsletter
Your email will never be given to third parties or sent spam.


| Methods' Details |
getAllKeyEvents
| sequence< ::com::sun::star::awt::KeyEvent > |
| getAllKeyEvents(); |
- Description
- return the list of all key events, which
are available at this configration set.
The key events are the "primary keys" of this configuration sets.
Means: Commands are registerd for key events.
Such key event can be mapped to its bound command,
using the method getCommandForKeyEvent().
- Returns
- A list of key events.
- See also
- getCommandForKeyEvent().
|
|
getCommandByKeyEvent
- Description
- return the registered command for the specified key event.
This function can be used to:
- by a generic service, which can execute commands if a
keyboard event occures.
- or to iterate over the whole container and change some
accelerator bindings.
- Parameter aKeyEvent
- the key event, where the registered command is searched for.
- Returns
- The registered command for the specified key event.
- Throws
- ::com::sun::star::container::NoSuchElementException
if the key event is an invalid one or does not exists
inside this configuration set.
|
|
setKeyEvent
- Description
- modify or create a key - command - binding.
If the specified key event does not already exists inside this
configuration access, it will be created and the command will be
registered for it.
If the specified key event already exists, its command will
be overwritten with the new command. There is no warning nor any error
about that! The outside code has to use the method getCommandForKeyEvent()
to check for possible collisions.
Note: This method cant be used to remove entities from the configuration set.
Empty parameters will result into an exception!
Use the method removeKeyEvent() instead.
- Parameter aKeyEvent
- specify the key event, which must be updated or new created.
- Parameter sCommand
- the new command for the specified key event.
- Throws
- ::com::sun::star::lang::IllegalArgumentException
if the key event isnt a valid one. Commands can be
checked only, if they are empty. Because every URL schema can be used
by commands in general, so its not possible to validate it.
- See also
- removeKeyEvent()
|
|
removeKeyEvent
- Description
- remove a key-command-binding from this configuration set.
- Parameter aKeyEvent
- the key event, which should be removed.
- Throws
- ::com::sun::star::container::NoSuchElementException
if the key event does not exists inside this configuration set.
|
|
getKeyEventsByCommand
- Description
- optimized access to the relation "command-key" instead
of "key-command" which is provided normaly by this interface.
It can be used to implement collision handling, if more then one
key event match to the same command. The returned list contains all
possible key events - and the outside code can select an possible one.
Of course - mostly this list will contain only one key event ...
- Parameter sCommand
- the command, where key bindings are searched for.
- Returns
- A list of ::com::sun::star::awt::KeyEvent structures,
where the pecified command is registered for.
- Throws
- ::com::sun::star::lang::IllegalArgumentException
if the specified command is empty. It cant be checked, if a command
is valid - because every URL schema can be used here.
- Throws
- ::com::sun::star::container::NoSuchElementException
if the specified command isnt empty but does not
occure inside this configuration set.
|
|
getPreferredKeyEventsForCommandList
| sequence< any > |
| getPreferredKeyEventsForCommandList( |
[in] sequence< string > |
lCommandList ) |
| raises( |
::com::sun::star::lang::IllegalArgumentException ); |
- Description
- optimized function to map a list of commands to a corresponding
list of key events.
It provides a fast mapping, which is e.g. needed by a menu or toolbar implementation.
E.g. a sub menu is described by a list of commands - and the implementation of the menu
must show the corresponding shortcuts. Iteration over all items of this configuration
set can be very expensive.
Instead to the method getKeyEventsForCommand() the returned list contains only
one(!) key event bound to one(!) requested command. If more then one key event
is bound to a command - a selection is done inside this method.
This internal selection cant be influenced from outside.
@attention Because its not defined, that any command (e.g. configured inside a menu)
must have an accelerator - we cant reject the call if at least one command
does not occure inside this configuration set ...
We handle it more gracefully - and return an empty item instead of throwing
and exception.
- Parameter lCommandList
- a list of commands
- Returns
- A (non packed!) list of key events, where every item match by index
directly to a command of the specified CommandList.
If a command does not exists inside this configuration set, the
corresponding any value will be empty.
- Throws
- ::com::sun::star::lang::IllegalArgumentException
if at least one of the specified commands is empty.
It cant be checked, if a command is valid -
because every URL schema can be used here.
|
|
removeCommandFromAllKeyEvents
- Description
- search for an key-command-binding inside this configuration set,
where the specified command is used.
If such binding could be located, the command will be removed
from it. If as result of that the key binding will be empty,
if will be removed too.
This is an optimized method, which can perform removing of commands
from this configuration set. Because normaly Commands are "foreign keys"
and key identifier the "primary keys" - it needs some work to remove
all commands outside this container ...
- Parameter sCommand
- the command, which should be removed from any key binding.
- Throws
- ::com::sun::star::lang::IllegalArgumentException
if the specified command is empty.
- Throws
- ::com::sun::star::container::NoSuchElementException
if the specified command isnt used inside this configuration set.
|
|
Copyright © 2013, The Apache Software Foundation, Licensed under the Apache License, Version 2.0. Apache, the Apache feather logo, Apache OpenOffice and OpenOffice.org are trademarks of The Apache Software Foundation. Other names may be trademarks of their respective owners.


Delete the Email Address of a Hotel Group
Give the Hotel Group ID you want it's Email Address Deleted
Hotel Group ID


Members
(inner) count :Number
Type:
- Source:
(inner) element :Number
Type:
- Source:
(inner) lengths :Array.<Number>
Type:
- Source:
(inner) noOfShips :Number
Type:
- Source:
Methods
(inner) dragEnd(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) dragEnter(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) dragOver(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) dragStart(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) drop(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) newGame(event)
Parameters:
| Name |
Type |
Description |
event |
Object
|
|
- Source:
(inner) newGameEvent()
Attaches event listener to button
- Source:
(inner) record(e)
Parameters:
| Name |
Type |
Description |
e |
Object
|
|
- Source:
(inner) registerCellClick(event)
Parameters:
| Name |
Type |
Description |
event |
Object
|
|
- Source:
(inner) removeTdEvent()
Removes event listener from table cells
- Source:
(inner) tdEvent()
Attaches event listener to table cells
- Source:
(inner) toggleDirection(event)
Parameters:
| Name |
Type |
Description |
event |
Object
|
|
- Source:
(inner) toggleDirectionEvent()
Adds drag event listeners
- Source:


Maintenance Tracker
Login
Signup
Facilities don't need to go bad any longer, request a repair or maintenance schedule from us today.
Get Started Today


This is a vis.js network visualization. Selecting a node/edge and then showing a magic trick makes it disappear. The second button reverts this. Doesn't work on legend, it;s static. Doubleclicking on nodes updates the input.


At a safe withdrawal rate of {{safeWithdrawalRate}}%, Financial Independence is reached at a Net Worth of {{safeWithdrawalTimes}} times annual expenses.
With annual expenses of {{calculateInput.annualExpenses | currency:calculateInput.currencyIsoCode}}, we're aiming for a Net Worth of {{fiNumber | currency:calculateInput.currencyIsoCode}}.
At {{expectedAnnualGrowthRate}}% returns, that Net Worth is forecasted to be {{fiDate}}; {{dateDistance}} from the first month. By that point, Net Worth is at {{fiMonthForecast.netWorth | currency:calculateInput.currencyIsoCode}}. Of that total, contributions account for {{fiMonthForecast.totalContributions | currency:calculateInput.currencyIsoCode}} while {{fiMonthForecast.totalReturns | currency:calculateInput.currencyIsoCode}} is earned returns.


Under dev
Feel like to helpout a little bit? Or if you request support, press the plus button below!


Links are created using the a element, which has an attribute called href. I dont know what it means but it holds a quote of the link that we want to point to. Here are some websites that i use frequently:
The previous links were given using their absolute urls. It is also possible to link to pages using relative urls.Here's a link to another page in this same directory: Links2 It is however, possible to also link to page in parent and child directories using relative file location descriptors
When linking to the same file from different relative locations on the website it is necessary to write two different urls
Its possible to create mail links by using the a tag and an href atribute. In order to make it different from a regular link however, you have to start the href attribute with a "mailto:". You can try clicking the following link to email github support: github support.Be forewarned that I haven't verified whether that is a valid email. It was only meant to illustrate a point.
You can open a link ina new window by adding another attribute to the 'a' element. This link opens the Links2 page in a new window.
Its also possible to link to specific parts in the same page. The following links take you different sections of this webpage, in no particular order
96/490


The Northeastern Associate Chapter of Pi Kappa Phi was founded in early 2019 and has since grown to 69 initiated brothers. We are a self-governed, social fraternity which prides itself on its commitment to the community and philanthropic endeavors. Much of our efforts are directed at our national philanthropic foundation, The Ability Experience, which creates experiences that promote the abilities of all people and works to eliminate labels that have unfairly come to define others. We also participate in many community service and fundraising initiatives, such as the annual Relay for Life fundraiser and other smaller events on campus.
Learn More


Please type in the name of the user you would like to authorize and click "Authorize User".
{{ string }}


Welcome to my website
Home
Interest
Friend List
Gallery
Contact Me
Contact
For more information
First Name:
Last Name:
Country:
Nepal
China
India
Japan
Subject:


Pepe's Pizzeria
Home
Menu
MENU
First Name
Last Name
Street Address
City
Enter additional information for our delivery driver ....
Submit
NEXT ---->


"""Provide access to Python's configuration information. The specific configuration variables available depend heavily on the platform and configuration. The values may be retrieved using get_config_var(name), and the list of variables is available via get_config_vars().keys(). Additional convenience functions are also available. Written by: Fred L. Drake, Jr. Email<EMAIL_ADDRESS>""" import _imp import os import re import sys from .errors import DistutilsPlatformError IS_PYPY = '__pypy__' in sys.builtin_module_names # These are needed in a couple of spots, so just compute them once. PREFIX = os.path.normpath(sys.prefix) EXEC_PREFIX = os.path.normpath(sys.exec_prefix) BASE_PREFIX = os.path.normpath(sys.base_prefix) BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix) # Path to the base directory of the project. On Windows the binary may # live in project/PCbuild/win32 or project/PCbuild/amd64. # set for cross builds if "_PYTHON_PROJECT_BASE" in os.environ: project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"]) else: if sys.executable: project_base = os.path.dirname(os.path.abspath(sys.executable)) else: # sys.executable can be empty if argv[0] has been changed and Python is # unable to retrieve the real program name project_base = os.getcwd() # python_build: (Boolean) if true, we're either building Python or # building an extension with an un-installed Python, so we use # different (hard-wired) directories. def _is_python_source_dir(d): for fn in ("Setup", "Setup.local"): if os.path.isfile(os.path.join(d, "Modules", fn)): return True return False _sys_home = getattr(sys, '_home', None) if os.name == 'nt': def _fix_pcbuild(d): if d and os.path.normcase(d).startswith( os.path.normcase(os.path.join(PREFIX, "PCbuild"))): return PREFIX return d project_base = _fix_pcbuild(project_base) _sys_home = _fix_pcbuild(_sys_home) def _python_build(): if _sys_home: return _is_python_source_dir(_sys_home) return _is_python_source_dir(project_base) python_build = _python_build() # Calculate the build qualifier flags if they are defined. Adding the flags # to the include and lib directories only makes sense for an installation, not # an in-source build. build_flags = '' try: if not python_build: build_flags = sys.abiflags except AttributeError: # It's not a configure-based build, so the sys module doesn't have # this attribute, which is fine. pass def get_python_version(): """Return a string containing the major and minor Python version, leaving off the patchlevel. Sample return values could be '1.5' or '2.2'. """ return '%d.%d' % sys.version_info[:2] def get_python_inc(plat_specific=0, prefix=None): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely pyconfig.h). If 'prefix' is supplied, use it instead of sys.base_prefix or sys.base_exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX if IS_PYPY: return os.path.join(prefix, 'include') elif os.name == "posix": if python_build: # Assume the executable is in the build directory. The # pyconfig.h file should be in the same directory. Since # the build directory may not be the source directory, we # must use "srcdir" from the makefile to find the "Include" # directory. if plat_specific: return _sys_home or project_base else: incdir = os.path.join(get_config_var('srcdir'), 'Include') return os.path.normpath(incdir) python_dir = 'python' + get_python_version() + build_flags return os.path.join(prefix, "include", python_dir) elif os.name == "nt": if python_build: # Include both the include and PC dir to ensure we can find # pyconfig.h return (os.path.join(prefix, "include") + os.path.pathsep + os.path.join(prefix, "PC")) return os.path.join(prefix, "include") else: raise DistutilsPlatformError( "I don't know where Python installs its C header files " "on platform '%s'" % os.name) def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.base_prefix or sys.base_exec_prefix -- i.e., ignore 'plat_specific'. """ if IS_PYPY: # PyPy-specific schema if prefix is None: prefix = PREFIX if standard_lib: return os.path.join(prefix, "lib-python", sys.version[0]) return os.path.join(prefix, 'site-packages') if prefix is None: if standard_lib: prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX else: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": if plat_specific or standard_lib: # Platform-specific modules (any module from a non-pure-Python # module distribution) or standard Python library modules. libdir = getattr(sys, "platlibdir", "lib") else: # Pure Python libdir = "lib" libpython = os.path.join(prefix, libdir, "python" + get_python_version()) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: return os.path.join(prefix, "Lib", "site-packages") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name) def customize_compiler(compiler): """Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile. """ if compiler.compiler_type == "unix": if sys.platform == "darwin": # Perform first-time customization of compiler-related # config vars on OS X now that we know we need a compiler. # This is primarily to support Pythons from binary # installers. The kind and paths to build tools on # the user system may vary significantly from the system # that Python itself was built on. Also the user OS # version and build tools may not support the same set # of CPU architectures for universal builds. global _config_vars # Use get_config_var() to ensure _config_vars is initialized. if not get_config_var('CUSTOMIZED_OSX_COMPILER'): import _osx_support _osx_support.customize_compiler(_config_vars) _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' (cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \ get_config_vars('CC', 'CXX', 'CFLAGS', 'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS') if 'CC' in os.environ: newcc = os.environ['CC'] if (sys.platform == 'darwin' and 'LDSHARED' not in os.environ and ldshared.startswith(cc)): # On OS X, if CC is overridden, use that as the default # command for LDSHARED as well ldshared = newcc + ldshared[len(cc):] cc = newcc if 'CXX' in os.environ: cxx = os.environ['CXX'] if 'LDSHARED' in os.environ: ldshared = os.environ['LDSHARED'] if 'CPP' in os.environ: cpp = os.environ['CPP'] else: cpp = cc + " -E" # not always if 'LDFLAGS' in os.environ: ldshared = ldshared + ' ' + os.environ['LDFLAGS'] if 'CFLAGS' in os.environ: cflags = cflags + ' ' + os.environ['CFLAGS'] ldshared = ldshared + ' ' + os.environ['CFLAGS'] if 'CPPFLAGS' in os.environ: cpp = cpp + ' ' + os.environ['CPPFLAGS'] cflags = cflags + ' ' + os.environ['CPPFLAGS'] ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] if 'AR' in os.environ: ar = os.environ['AR'] if 'ARFLAGS' in os.environ: archiver = ar + ' ' + os.environ['ARFLAGS'] else: archiver = ar + ' ' + ar_flags cc_cmd = cc + ' ' + cflags compiler.set_executables( preprocessor=cpp, compiler=cc_cmd, compiler_so=cc_cmd + ' ' + ccshared, compiler_cxx=cxx, linker_so=ldshared, linker_exe=cc, archiver=archiver) compiler.shared_lib_extension = shlib_suffix def get_config_h_filename(): """Return full pathname of installed pyconfig.h file.""" if python_build: if os.name == "nt": inc_dir = os.path.join(_sys_home or project_base, "PC") else: inc_dir = _sys_home or project_base else: inc_dir = get_python_inc(plat_specific=1) return os.path.join(inc_dir, 'pyconfig.h') def get_makefile_filename(): """Return full pathname of installed Makefile from the Python build.""" if python_build: return os.path.join(_sys_home or project_base, "Makefile") lib_dir = get_python_lib(plat_specific=0, standard_lib=1) config_file = 'config-{}{}'.format(get_python_version(), build_flags) if hasattr(sys.implementation, '_multiarch'): config_file += '-%s' % sys.implementation._multiarch return os.path.join(lib_dir, config_file, 'Makefile') def parse_config_h(fp, g=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if g is None: g = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") # while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 return g # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") def parse_makefile(fn, g=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ from distutils.text_file import TextFile fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape") if g is None: g = {} done = {} notdone = {} while True: line = fp.readline() if line is None: # eof break m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # Variables with a 'PY_' prefix in the makefile. These need to # be made available without that prefix through sysconfig. # Special care is needed to ensure that variable expansion works, even # if the expansion uses the name without a prefix. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') # do variable interpolation here while notdone: for name in list(notdone): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] elif n in renamed_variables: if name.startswith('PY_') and name[3:] in renamed_variables: item = "" elif 'PY_' + n in notdone: found = False else: item = str(done['PY_' + n]) else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value del notdone[name] if name.startswith('PY_') \ and name[3:] in renamed_variables: name = name[3:] if name not in done: done[name] = value else: # bogus variable reference; just drop it since we can't deal del notdone[name] fp.close() # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary g.update(done) return g def expand_makefile_vars(s, vars): """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in 'string' according to 'vars' (a dictionary mapping variable names to values). Variables not present in 'vars' are silently expanded to the empty string. The variable values in 'vars' should not contain further variable expansions; if 'vars' is the output of 'parse_makefile()', you're fine. Returns a variable-expanded version of 's'. """ # This algorithm does multiple expansion, so if vars['foo'] contains # "${bar}", it will expand ${foo} to ${bar}, and then expand # ${bar}... and so forth. This is fine as long as 'vars' comes from # 'parse_makefile()', which takes care of such expansions eagerly, # according to make's variable expansion semantics. while True: m = _findvar1_rx.search(s) or _findvar2_rx.search(s) if m: (beg, end) = m.span() s = s[0:beg] + vars.get(m.group(1)) + s[end:] else: break return s _config_vars = None def _init_posix(): """Initialize the module as appropriate for POSIX systems.""" # _sysconfigdata is generated at build time, see the sysconfig module name = os.environ.get('_PYTHON_SYSCONFIGDATA_NAME', '_sysconfigdata_{abi}_{platform}_{multiarch}'.format( abi=sys.abiflags, platform=sys.platform, multiarch=getattr(sys.implementation, '_multiarch', ''), )) try: _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0) except ImportError: # Python 3.5 and pypy 7.3.1 _temp = __import__( '_sysconfigdata', globals(), locals(), ['build_time_vars'], 0) build_time_vars = _temp.build_time_vars global _config_vars _config_vars = {} _config_vars.update(build_time_vars) def _init_nt(): """Initialize the module as appropriate for NT""" g = {} # set basic install directories g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1) g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1) # XXX hmmm.. a normal install puts include files here g['INCLUDEPY'] = get_python_inc(plat_specific=0) g['EXT_SUFFIX'] = _imp.extension_suffixes()[0] g['EXE'] = ".exe" g['VERSION'] = get_python_version().replace(".", "") g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable)) global _config_vars _config_vars = g def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. Generally this includes everything needed to build extensions and install both pure modules and extensions. On Unix, this means every variable defined in Python's installed Makefile; on Windows it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ global _config_vars if _config_vars is None: func = globals().get("_init_" + os.name) if func: func() else: _config_vars = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _config_vars['prefix'] = PREFIX _config_vars['exec_prefix'] = EXEC_PREFIX if not IS_PYPY: # For backward compatibility, see issue19555 SO = _config_vars.get('EXT_SUFFIX') if SO is not None: _config_vars['SO'] = SO # Always convert srcdir to an absolute path srcdir = _config_vars.get('srcdir', project_base) if os.name == 'posix': if python_build: # If srcdir is a relative path (typically '.' or '..') # then it should be interpreted relative to the directory # containing Makefile. base = os.path.dirname(get_makefile_filename()) srcdir = os.path.join(base, srcdir) else: # srcdir is not meaningful since the installation is # spread about the filesystem. We choose the # directory containing the Makefile since we know it # exists. srcdir = os.path.dirname(get_makefile_filename()) _config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir)) # Convert srcdir into an absolute path if it appears necessary. # Normally it is relative to the build directory. However, during # testing, for example, we might be running a non-installed python # from a different directory. if python_build and os.name == "posix": base = project_base if (not os.path.isabs(_config_vars['srcdir']) and base != os.getcwd()): # srcdir is relative and we are not in the same directory # as the executable. Assume executable is in the build # directory and make srcdir absolute. srcdir = os.path.join(base, _config_vars['srcdir']) _config_vars['srcdir'] = os.path.normpath(srcdir) # OS X platforms require special customization to handle # multi-architecture, multi-os-version installers if sys.platform == 'darwin': import _osx_support _osx_support.customize_config_vars(_config_vars) if args: vals = [] for name in args: vals.append(_config_vars.get(name)) return vals else: return _config_vars def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ if name == 'SO': import warnings warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2) return get_config_vars().get(name)


React Kaltura Resumable JS
Uploader with ReactResumableJS to upload file into Kaltura
Install
npm i react-kaltura-resumablejs
Options
- filetypes: Set the video extensions to upload. Ex: ['mp4','avi'].
- chunksize: Set in KB the size to upload the file in chunks. Ex: 1024.
- simultaneousUploads: amount of upload at same time. Ex: 1.
- onError: Catch the upload error. Must be a function. Ex: (error) => { return error; }.
- onSuccess: Catch the file success when finish the upload. Ex: (success) => { return success}
- uploaderID: Container ID to render the ReactResumableJS. Ex: "video-uploader",
- textLabel: "Uploaded files",
- fileAddedMessage: "Started",
- completedMessage: "Complete!:"
Changelog
- 1.0.1
- updated react-resumablejs
Example
export default class Example extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<ReactKalturaResumableJs
server="http://www.kaltura.com/api_v3"
ks="0_asdfafdvsdbsdgsdgsdgs"
onSuccess={(success) => { console.log(success); }}
onError={(error) => { console.log(error); }}
/>
</div>
);
}
}
Demo
npm run demo


Downloads
Always make sure you're using the latest version!
Date
Version
Links
12/12/2021
Alpha-0
Download
page not done yet


I was born in Latvia in a small town of Salaspils. It's a shame to say that I never visited after I moved from there. I always wanted to revisit but haven't had a chance yet. So here I will talk about several places that I remember visiting as a kid. Latvia is a lively little European country these days. But even during the soviet times it was considered a "little piece of Europe" in the soviet reality. We had better made furniture, cute cafes and luxury to walk through the medieval streets of Riga, the capital.


SKY UX components are assembled from a small set of core design elements. These design elements act as the building blocks for the components and allow you to build user interfaces that incorporate SKY UX styles and patterns.
To ensure consistency with SKY UX design elements, add


|
PCD8544_Simple
Arduino Library for Nokia 5110 Display Modules
|
There are of course many ways to shift voltage levels. You only need to shift in one direction, from the Arduino to the Display.
You need at a minimum 4 level shifted channels (as well as a 3v3 power source of course), the CE pin can be connected directly to ground (provided you only have this display on the SPI bus).
Experiments have shown that even simply a voltage-divider on each signal appears to be sufficient for level shifting this device as a bare minimum. Shown here are a 330R and 620R combination (untested, actual tests conducted with 2.44k and 4.7k, which worked but seemed sensitive to electrical noise).
If you have some 3v3 Zener Diodes lying around, they can be used to accomplish the one-directional level shifting, as shown.
Another common way to accomplish one-directional level shifting such as required here is using a CD4050BE Non Inverting Hex Buffer IC.
Note below that a 100nF Capacitor (ceramic) is placed across the CD4050's Power and Ground, that the 4050 is powered from the 3.3V Supply (this is what makes it level shift for you), and again we have a 100K Resistor pulling RST down until it's driven by the Arduino.
Note also that the unused inputs on the CD4050 are connected to 3v3, in accordance with the datasheet (it is common on logic chips to "tie" unused inputs to either Vcc or Ground, otherwise they may oscillate uncontrollably and cause the chip to be damaged).


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from odo import odo
import talib
from quantopian.pipeline import Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume, SimpleMovingAverage, RSI, SimpleBeta, AverageDollarVolume, AnnualizedVolatility, ExponentialWeightedMovingAverage
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline import CustomFactor
class ATR(CustomFactor):
inputs = [USEquityPricing.close,USEquityPricing.high,USEquityPricing.low]
window_length = 14
def compute(self, today, assets, out, close, high, low):
hml = high - low
hmpc = np.abs(high - np.roll(close, 1, axis=0))
lmpc = np.abs(low - np.roll(close, 1, axis=0))
tr = np.maximum(hml, np.maximum(hmpc, lmpc))
atr = np.mean(tr[1:], axis=0) #skip the first one as it will be NaN
out[:] = atr
class ADX_Dir_Ind(CustomFactor):
inputs=[USEquityPricing.high, USEquityPricing.low, USEquityPricing.close]
true_length=14
window_length=true_length+true_length
def compute(self, today, assets, out, high, low, close):
anynan =np.isnan(close).any(axis=0)
for col_ix, have_nans in enumerate(anynan):
if have_nans:
out[col_ix] = np.nan
continue
results = talib.ADX(
high[:, col_ix],
low[:, col_ix],
close[:, col_ix],
timeperiod=self.true_length)
out[col_ix] = results[-1]
# how to do static asset
# https://www.quantopian.com/posts/how-to-get-static-assets-in-research
# basically just picking some stocks from the DJIA, along with a few others
my_assets = StaticAssets(symbols([
'GDOT', 'CSCO', 'MSFT', 'BA', 'LMT', 'XOM', 'O', 'MMM', 'CAT', 'INTC',
'CVX', 'HD', 'EXPE', 'UNH', 'UTX', 'WMT', 'DIS', 'TRV', 'PG', 'GE', 'MCD']
))
# how to do factors:
# https://www.quantopian.com/tutorials/pipeline#lesson4
# list of factors = https://www.quantopian.com/help#built-in-factors
def make_pipeline():
sma50 = SimpleMovingAverage(
inputs=[USEquityPricing.close],
window_length=50
)
sma100 = SimpleMovingAverage(
inputs=[USEquityPricing.close],
window_length=100
)
sma150 = SimpleMovingAverage(
inputs=[USEquityPricing.close],
window_length=150
)
adx = ADX_Dir_Ind()
atr = ATR()
close = USEquityPricing.close.latest
atr_ratio = atr / close
rsi = RSI()
buy_signal = sma50 > sma100 > sma150
sell_signal = sma50 < sma100 < sma150
sma_diff_1 = (sma50 - sma150) / sma150
sma_diff_2 = (sma50 - sma100) / sma100
## (8554, 'SPY'), --> https://www.quantopian.com/posts/sid-slash-ticker-set
spy_beta = SimpleBeta(target=symbols('SPY'),regression_length=150)
avg_vol = AverageDollarVolume(window_length=1)
volatility = AnnualizedVolatility()
volatility_short = AnnualizedVolatility(annualization_factor=150)
return Pipeline(
columns={
'sma50': sma50,
'sma100': sma100,
'sma150': sma150,
'sma_diff_1': sma_diff_1,
'sma_diff_2': sma_diff_2,
'spy_beta': spy_beta,
'adx': adx,
'atr': atr,
'atr_ratio': atr_ratio,
'close': close,
'rsi': rsi,
'buy_signal': buy_signal,
'sell_signal': sell_signal,
'avg_vol': avg_vol,
'volatility': volatility,
'volatility_short': volatility_short
},
screen=my_assets
)
my_pipe = make_pipeline()
result = run_pipeline(my_pipe, '2011-01-01', '2017-01-01')
result.head()
And I extract the symbols from the multi-index that I want.
Pandas dataframes a little bit confusing. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html
# multiindex =
result.index.get_level_values(0)
#result[['close']].values
stock_ids = result.index.get_level_values(1).values[:21]
print(stock_ids[0].symbol, stock_ids[0].sid)
print(len(stock_ids), stock_ids)
#result[['close']].values
#result[['close']].at(1)
# access a single result -- multi index as tuple and then column name.
#result.loc[('2016-12-15', 24)]['adx']
# another way to do the same thing
#result.xs(['2016-12-15', 24])
# https://www.somebits.com/~nelson/pandas-multiindex-slice-demo.html
# here is how you get the columns you want for a secondary index. slice(None) on 1st index.
#result.loc[(slice(None), slice(24, 24)), :]['close']
# now do this to just get the values.
# .cumsum() seems to do something with plottin
#print(result.loc[(slice(None), slice(5061, 5061)), :]['close'])
df = result.loc[(slice(None), slice(5061, 5061)), :]['close']
df.index.get_level_values(0)
legend = []
for stock in stock_ids:
close_tbl = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['close']
idx = close_tbl.index.get_level_values(0)
plt.plot(idx.values, close_tbl)
legend.append(stock.symbol)
plt.ylabel('Asset price')
plt.legend(legend)
plt.show()
for stock in stock_ids:
adx_tbl = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['adx']
adx_idx = adx_tbl.index.get_level_values(0)
atr_tbl = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['atr']
atr_idx = atr_tbl.index.get_level_values(0)
rsi_tbl = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['rsi']
rsi_idx = rsi_tbl.index.get_level_values(0)
volatility_short = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['volatility_short']
volatility_short_idx = volatility_short.index.get_level_values(0)
# plt.plot(volatility_short_idx.values, volatility_short)
# plt.legend(['volatility'])
# plt.ylabel('volatility indicator value')
# plt.show()
# plt.plot(adx_idx.values, adx_tbl)
# plt.legend(['adx'])
# plt.ylabel('adx indicator value')
# plt.show()
# plt.plot(atr_idx.values, atr_tbl)
# plt.legend(['atr'])
# plt.ylabel('atr indicator value')
# plt.show()
# plt.plot(rsi_idx.values, rsi_tbl)
# plt.legend(['rsi'])
# plt.ylabel('rsi indicator value')
# plt.show()
def formatRow(row, signal):
return {'signal': signal,
'price': row['close'],
'profitable': None,
'profits': 0.0,
'adx': row['adx'],
'atr': row['atr'],
'atr_ratio': row['atr_ratio'],
'avg_vol': row['avg_vol'],
'volatility': row['volatility'],
'volatility_short': row['volatility_short'],
'rsi': row['rsi'],
'sma50': row['sma50'],
'sma100': row['sma100'],
'sma150': row['sma150'],
'spy_beta': row['spy_beta'],
'sma_diff_1': row['sma_diff_1'],
'sma_diff_2': row['sma_diff_2']
}
def recordSignals(dataframe):
buy_pts = []
sell_pts = []
trade_dict = {}
last_buy = False
last_sell = False
i = 0
for index, row in dataframe.iterrows():
i += 1
if last_buy == False and row['buy_signal'] == True:
buy_pts.append(index[0])
trade_dict[index[0]] = formatRow(row, 'buy')
if last_sell == False and row['sell_signal'] == True:
sell_pts.append(index[0])
trade_dict[index[0]] = formatRow(row, 'sell')
last_sell = row['sell_signal']
last_buy = row['buy_signal']
#print row['close'], row['buy_signal']
return {
'buy_pts': buy_pts,
'sell_pts': sell_pts,
'trade_dict': trade_dict
}
signals = {}
for stock in stock_ids:
df = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]
signals[stock.symbol] = recordSignals(df)
signals.keys()
I do this by plotting colored avxlines over the charts
for stock in stock_ids:
close = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['close']
close_idx = close.index.get_level_values(0)
sma50 = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['sma50']
sma50_idx = sma50.index.get_level_values(0)
sma150 = result.loc[(slice(None), slice(stock.sid, stock.sid)), :]['sma150']
sma150_idx = sma150.index.get_level_values(0)
plt.plot(close_idx.values, close)
plt.plot(sma50_idx.values, sma50)
plt.plot(sma150_idx.values, sma150)
for xc in signals[stock.symbol]['buy_pts']:
plt.axvline(x=xc, color="green")
for xc in signals[stock.symbol]['sell_pts']:
plt.axvline(x=xc, color="red")
plt.ylabel(stock.symbol + ' price')
plt.legend([stock.symbol, 'sma50', 'sma100', 'sma150'])
plt.show()
It's OK, we are not necessarily going to be overall profitable. More importantly I just want to know what other indicators are doing when I enter these positions.
# now I need to compute the profit of this algo.
def tradeCalc(signal_list):
trading_size = 10000.0
currentValue = 0
port = {
'last_price': 0,
'last_signal': None,
'current_value': 0,
'shares_held': 0,
}
trade_dict = signal_list['trade_dict']
keylist = trade_dict.keys()
keylist.sort()
#print keylist
total = 0
wins = 0
total_profit = 0
for key in keylist:
value = trade_dict[key]
signal = value['signal']
price = value['price']
# what is the new value, or start it out a current value
if port['last_signal'] == None:
port['current_value'] = trading_size
elif port['last_signal'] == 'buy' and signal == 'sell':
value['profitable'] = price > port['last_price']
last_qty = trading_size / port['last_price']
last_val = trading_size
this_val = last_qty * price
value['profits'] = this_val - last_val
elif port['last_signal'] == 'sell' and signal == 'buy':
value['profitable'] = price < port['last_price']
last_qty = trading_size / port['last_price']
last_val = trading_size
this_val = last_qty * price
value['profits'] = -1* (this_val - last_val)
port['last_signal'] = signal
port['last_price'] = price
print 'on', key, signal, 'at', price, 'was good:', value['profitable'], '->profit', value['profits']
if value['profitable']:
wins += 1
total +=1
total_profit += value['profits']
print "winrate: ", float(wins) / float(total)
print "total profitability", total_profit, ' trading size: ', trading_size
print 'total return 7 yrs: %', ((total_profit) / trading_size) * 100
for k, v in signals.items():
print("Computing trades for " + k)
tradeCalc(v)
Unfortunately, I don't see many obviously linear relationships between indicator values and magnitude of loss or profit!
If I see an rsquared that is high, I plot it. Otherwise I just print the rsquared.
Interestingly it seems that there is some negative correlation between volatility and profitable outcomes. I might have predicted the opposite.
from scipy.stats import linregress
def plotWithRegression(indicator, symbol, x, y):
slope, intercept, r_value, p_value, std_err = linregress(x, y)
rsquared = r_value**2
print('doing regression on ', symbol, indicator)
print('rvalue, r-squared results: ', r_value, str(rsquared))
if rsquared > 0.4:
fit = np.polyfit(x, y, 1)
fit_fn = np.poly1d(fit)
plt.title(indicator + ' at entry of trade vs profit on trade for' + symbol)
#plt.scatter(x_adx, y_profit)
plt.plot(x, y, 'yo', x, fit_fn(x), '--k')
plt.show()
def plotIndicators(symbol, signal_list):
trade_dict = signal_list['trade_dict']
keylist = trade_dict.keys()
keylist.sort()
#print keylist
y_profit = []
x_adx = []
x_atr = []
x_rsi = []
x_spy_beta = []
x_sma_diff_1 = []
x_sma_diff_2 = []
x_volatility = []
x_volatility_short = []
x_avg_vol = []
x_atr_ratio = []
for key in keylist:
value = trade_dict[key]
y_profit.append(value['profits'])
x_adx.append(value['adx'])
x_atr.append(value['atr'])
x_rsi.append(value['rsi'])
x_spy_beta.append(value['spy_beta'])
x_sma_diff_1.append(value['sma_diff_1'])
x_sma_diff_2.append(value['sma_diff_2'])
x_volatility.append(value['volatility'])
x_volatility_short.append(value['volatility_short'])
x_avg_vol.append(value['avg_vol'])
x_atr_ratio.append(value['atr_ratio'])
plotWithRegression('ATR', symbol, x_atr, y_profit)
plotWithRegression('RSI', symbol, x_rsi, y_profit)
plotWithRegression('ADX', symbol, x_adx, y_profit)
plotWithRegression('SMA Difference 1', symbol, x_sma_diff_1, y_profit)
plotWithRegression('SMA Difference 2', symbol, x_sma_diff_2, y_profit)
plotWithRegression('SPY Beta', symbol, x_spy_beta, y_profit)
plotWithRegression('ATR Ratio', symbol, x_atr_ratio, y_profit)
plotWithRegression('Avg Vol', symbol, x_avg_vol, y_profit)
plotWithRegression('Volatility', symbol, x_volatility, y_profit)
plotWithRegression('Volatility Shorter Duration', symbol, x_volatility_short, y_profit)
for k, v in signals.items():
print("plotting indicators for " + k)
plotIndicators(k, v)
I will use a simple classifier where there are 2 states:
I will use an algorithm that can sniff out nonlinear relationships. First I build a set of features then I scale the features using a min/max scaler. The learning algorithm I am using (SVC) works best with feature scaling.
from sklearn import preprocessing
# will take this structure price, ma1, ma2, ma3, adx, rsi, spy_beta, sma_diff_1
features = []
labels = [] # 0 == not profitable, 1 == profitable
for k, v in signals.items():
trade_dict = v['trade_dict']
keylist = trade_dict.keys()
keylist.sort()
i = 0
for key in keylist:
i += 1
if i == 1: # skip the first row
continue
value = trade_dict[key]
# i use only features that can be scaled together and are independent of a given security price.
features.append([
# value['price'],
# value['sma50'],
# value['sma100'],
# value['sma150'],
value['adx'],
# value['atr'],
value['rsi'],
value['spy_beta'],
value['sma_diff_1'],
value['sma_diff_2'],
value['volatility'],
value['volatility_short'],
value['atr_ratio'],
value['avg_vol']
])
if value['profitable']:
labels.append(1)
else:
labels.append(0)
# Each set of features should be scaled independently (?)
# min_max_scaler = preprocessing.MinMaxScaler()
# features = min_max_scaler.fit_transform(features)
#print features, labels
print "Len trades: ", len(features)
train_size = int(float(len(features)) * 0.85)
# feature scaling should be done by group of security *probably*, for now I am only using features
# that are in the same range for every security and can be scaled all together.
# The exception is perhaps average volume.
min_max_scaler = preprocessing.MinMaxScaler()
features = min_max_scaler.fit_transform(features)
training_features = features[:train_size]
training_labels = labels[:train_size]
test_features = features[train_size:]
test_labels = labels[train_size:]
print "len training", len(training_features), " len test", len(test_features)
from sklearn import svm
clf = svm.SVC(C=1000, kernel='rbf')
clf.fit(training_features, training_labels)
pred = clf.predict(test_features)
print('predicted: ', pred)
print('test labels', test_labels)
from sklearn.metrics import accuracy_score
accuracy_score(test_labels, pred)
from sklearn.neighbors import KNeighborsClassifier
neighbors = KNeighborsClassifier()
neighbors.fit(training_features, training_labels)
prediction = neighbors.predict(test_features)
print('predicted: ', prediction)
print('test labels', test_labels)
accuracy_score(test_labels, prediction)
Unsurprisingly, because I did not find any obviously strong linear relationships between any of the indicators and the resulting profitability of my trades, I was not able to build a predictive system that would predict outcomes with a high degree of accuracy.
The majority of the tests I ran I got an accuracy only slighly better than 50% so that means there was not much success in the ML model fitting.
I think the one indicator that did seem to have some correlation with good entry points was volatility. The volatility indicator I am using the one build into Quantopian Factors which is based on annualized volatility calculated from the standard deviation of the stock price. I believe this should related the volatility guage you will see in options pricing.
Given that volatility was useful, I would also like to look at options pricing as a way of learning information about the underlying value. At the very least it would be interesting to look at put/call ratio to see if there is some predictive power there.
Volume also seemed to have some some correlation with good entry points in some tests. I want to try to refine that in the future.
In some tests ATR ratio also seemed to have some correlation with good entry points. I believe that because ATR to price ratio is essentially a measure of volatility that this makes sense, given that volatility also has some correlation with good entry points.


scip-lib
This is a simple Smart Contract Invocation Protocol compliant parser and generator library written in Typescript for Node.js. It was built out as an extension of the jsonrpc-lib since SCIP is made out as an extension of JSON-RPC.
The package can be simply installed via npm, a suggestion is to import the package locally as follow:
npm install --save @toolscip/scip-lib
In order to use this module you just have to import it like any other npm package:
JavaScript import
const scip = require('@toolscip/scip-lib');
Typescript import
import scip from '@toolscip/scip-lib';
// or
import { scip } from '@toolscip/scip-lib';
One of the main functionality that this package provides is the parse function that allows a client to parse a string message, checks whether it a SCIP-compliant message and then if valid it generates the corresponding SCIP object, otherwise it throws an exception (i.e. ErrorObject
) containing information about what is invalid in the string message.
Suppose to have received a message request as the following one:
{
"jsonrpc": "2.0",
"id": "abcdefg",
"method": "Invoke",
"params": {
"functionId": "send",
"inputs": [
{
"type": {
"type": "number"
},
"name": "amount",
"value": 50
}
],
"outputs": []
}
}
Now you just have to invoke the parse function providing the message as input, if the message is valid the function will return the object instance of a SCIP message (i.e. ScipInvocation
, ScipSubscription
, ScipUnsubscription
, ScipQuery
, ScipCallback
, ScipSuccess
and ScipError
).
try {
const obj = scip.parse(msg);
// `obj` will be an instance of a ScipInvocation class
} catch (err) {
console.log('Error message: ' + err.message); // error description
console.log('Error code: ' + err.code); // scip error code
console.log('Error data: ' + err.data); // scip error additional data
}
Note: the input message must be in string format.
There are two different flavours of the parse
function, the parseRequest
and the parseResponse
, which act exactly as the parse function, providing additional check over the specific SCIP message by throwing an error if the parsed data is not a request or a response respectively.
This package provides also other function that are mainly used to create new SCIP messages instances, all of them require an id
(i.e. json-rpc id) and a params
object that must be a valid SCIP params object in according to the specific invoked function (i.e. Invocation
, FunctionSubscription
, EventSubscription
, FunctionUnsubscription
, EventUnsubscription
, FunctionQuery
, EventQuery
, QueryResult
and Callback
).
The params object can be directly provided as instance of one of the aforementioned classes or as generic JSON object.
const param = {
functionId: 'send',
inputs: [
{
type: {
type: 'number',
},
name: 'amount',
value: 50,
},
],
outputs: [],
};
try {
const invObj = scip.invoke('abcdefg', param);
// 'invObj' will be an instance of a ScipInvocation
} catch (err) {
console.log('Error message: ' + err.message); // error description
console.log('Error code: ' + err.code); // scip error code
console.log('Error data: ' + err.data); // scip error additional data
}
The Smart Contract Invocation Protocol is a protocol intended to provide a protocol specification in the context of blockchains integration that allows external consumer applications to invoke smart contract functions in a uniform manner regardless of the underlying blockchain technology. Moreover it provides the capability to monitor smart contracts at runtime. Its core consists of a set of methods that can be used by blockchain-external consumer application to interact with smart contracts.
In particular the protocol defines four different methods which are used to perform the following operations:
This method allows an external application to invoke a specific smart contract's function. It requires a synchronous response notifying the success or not of the request and then an asynchronous message notifying the result of the function invocation.
This method allows to monitor smart contract's functions and/or events, in particular can be used to be notified whenever an event is triggered by the smart contract or a specific function has been invoked. It requires a synchronous response notifying the success or not of the request and then one or more asynchronous responses notifying the occurrences of what the consumer have subscribed.
This method is simply used to cancel previously established subscription, this can be used to cancel one or more subscription in according to the request parameters.
This is a fully synchronous request method which is used to retrieve past event occurrences or function invocations. This method does not have asynchronous responses from the gateway.
SCIP does not force to use a specific protocol for carrying all these messages, hence different bindings could be used. Here, we have decided to propose a JSON-RPC binding for SCIP, which is a stateless transport-agnostic remote procedure call protocol that uses JSON as its data format. A complete binding can be found at scip binding.
In according to the binding proposed in the specification we have built this library out of a JSON-RPC parser library since every SCIP message is also a JSON-RPC 2.0 compliant message. Hence the SCIP can be seen as a restriction of the JSON-RPC protocol:
Reference: A complete protocol specification can be found in the Github repository.
This library was built in an OOP perspective, providing a class definition for each SCIP message.
| Request | Class | Method | Params | Description |
|---|---|---|---|---|
| Invocation | ScipInvocation |
Invoke | Invocation |
Function invocation request object |
| Subscription | ScipSubscription |
Subscribe | EventSubscription or FunctionSubscription |
Function/event subscription request object |
| Unsubscription | ScipUnsubscription |
Unsubscribe | EventUnsubscription or FunctionUnsubscription |
Cancel subscription request object |
| Query | ScipQuery |
Query | EventQuery or FunctionQuery |
Function/event query request object |
Note: the params objects are specific class objects
| Response | Class | Description |
|---|---|---|
| Success (sync) | ScipSuccess |
Generic synchronous success response object |
| Error (sync) | ScipError |
Synchronous error response object |
| Query Response (sync) | ScipQueryResult |
Synchronous response of a Query request, extension of ScipSuccess |
| Callback (async) | ScipCallback |
Asynchronous response of a SCIP gateway, in a json-rpc context it acts as a Notification |
Reference: a complete class documentation can be found at scip-lib.
This library provides a set of tools that allows a client to easily handle and generates SCIP messages, in particular it provides the following functions:
| Function | Return | Description |
|---|---|---|
parse |
ScipMessage |
Parse a generic object checking its validity, if so it returns the specific SCIP object instance, otherwise it throws an ErrorObject |
parseRequest |
ScipRequest |
Same as parse function, which, in addition, throws an error even if the parsed data is a valid SCIP message but not a valid request (e.g. a response) |
parseResponse |
ScipResponse |
Same as parse function, which, in addition, throws an error even if the parsed data is a valid SCIP message but not a valid async or sync response (e.g. a request) |
invoke |
ScipInvocation |
Generates a ScipInvocation message if the params is a valid Invocation object. |
subscribeEvent |
ScipSubscription |
Generates a ScipSubscription message if the params is a valid EventSubscription object. |
subscribeFunction |
ScipSubscription |
Generates a ScipSubscription message if the params is a valid FunctionSubscription object. |
unsubscribeEvent |
ScipUnsubscription |
Generates a ScipUnsubscription message if the params is a valid EventUnsubscription object. |
unsubscribeFunction |
ScipUnsubscription |
Generates a ScipUnsubscription message if the params is a valid FunctionUnsubscription object. |
queryEvent |
ScipQuery |
Generates a ScipQuery message if the params is a valid EventQuery object. |
queryFunction |
ScipQuery |
Generates a ScipQuery message if the params is a valid FunctionQuery object. |
A simple example of scip-lib usage is inside a SCIP server.
Note: express
and body-parser
are external packages, which are strictly correlated to the following example of usage, but they are not mandatory, you can use whatever you prefer.
import * as express from 'express';
import * as bodyParser from 'body-parser';
import scip, { ScipMessage, types } from '@toolscip/scip-lib';
const PORT = 8000;
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
/* Handle POST request */
app.post('/', (req, res) => {
const body = req.body;
try {
const request = scip.parseRequest(body);
const result = handleRequest(request);
const response = scip.success(request.id, result); // SCIP success response
res.json(response);
} catch (err) {
// notice that err is already a valid jsonrpc ErrorObject
const error = scip.error(req.body.id, err); // SCIP error response
res.json(error);
}
});
/* Start the server */
app.listen(PORT, () => {
console.log(`Server started at port ${PORT}`);
});
The handleRequest
can be written as follows:
/**
* Executes some task in according to the specific kind of the SCIP request, hence in 'jsonrpc' context, it performs the code directly associated with the called 'method'.
* @param msg: message request
* @returns the result of the specific message invocation
*/
function handleRequest(msg: ScipMessage): any {
if (msg instanceof types.ScipInvocation) {
// ...
} else if (msg instanceof types.ScipInvocation) {
} else if (msg instanceof types.ScipSubscription) {
} else if (msg instanceof types.ScipUnsubscription) {
} else if (msg instanceof types.ScipQuery) {
} // ...
}
If you want to see another, completely different, example of usage please take a look at the clisc, a Node.js command line interface, which was built for automating the SCIP request invocations.
Feel free to post questions and problems on the issue tracker. Pull requests are welcome!
Feel free to fork and modify or add new features and functionality to the library
Generated using TypeDoc


This uses a syntax of:
variable_name=variable_value variable_name2=variable_value2
Seperated by newlines. Variables will be analyzed, and returned in the second box. Quotation marks are not required in string declarations.
Parse


{% extends "base.html" %} {% block title %}Err 500: Server Error{% endblock %} {% block content %}
Internal server error, something bad went down.