--- title: Prepare your variables weight: 26 ---
As always, start by opening a new script file, give your file a “good name” and save it in our folder (POL2045). Remove everything from RStudio’s memory and set your working directory
rm(list=ls())
setwd("~POLXXXX") # Remember XXXXis the code of your module
Although many data manipulation function exist in basic R sometimes it is easier to use packages build for the sole purpose of making data manipulation easier. dplyr
is such a package (https://dplyr.tidyverse.org/)
dplyr
is providing a consistent set of verbs that help you solve the most common data manipulation challenges:
mutate( ) : adds new variables that are functions of existing variables
select( ) : picks variables based on their names
filter( ) : picks cases based on their values
arrange( ) : changes the ordering of the rows
summarise( ) : reduces multiple values down to a single summary
library(dplyr)
Although not required dplyr
make use of the pipe operator %>%
. The main value of the pipe operator is the ability to connect multiple functions together. To give you an example:
filter(my_data, my_variable == variable_value)
or
my_data %>% filter(my_variable == variable_value)
{{% notice tip %}} If you use RStudio, you can type the pipe (\[%>%\]) with Ctrl + Shift + M if you have a PC or Cmd + Shift + M if you have a Mac. {{% /notice %}}
We will use the European Value Survey (EVS) which includes a series of continuous and categorical variables.
select( )
functionselect ()
will keep only those variables in the dataset you are interested in. Sometimes, especially when we re working with big datasets we want to reduce the number of variables.
In our seminar we will work again with the European Value Study (2019). As you already know the dataset contains many variables.Our goal is to explore what predicts attitudes towards immigration. The exact wording of the question is the following:
Please look at the following statements and indicate where you would place your views on this scale? (scale of 1 to 10)
Where 1 means that immigrants take jobs away from [Nationality] and 10 that immigrants DO NOT take jobs away from [Nationality].load("EVS_UK_full.RData")
library(dplyr)
Our dependent variable is attitudes towards immigration (v185), our main idependent variables are: self-placement on the left-right spectrum (v102), attitudes towards nationality (v189,v190, v191, v192, v193), and finally three control variables namely age (v226), education (v243_edulvlb), and gender (v225). We also need the variable describing the name of the country in the dataset (country).
sub.sample<-EVS_UK_full %>% select(v102, v185, v189,v190, v191, v192, v193, v225, v226,v243_edulvlb,country)
head(sub.sample)
EVS includes all European countries, for our excercise we want to analyse data examining attitudes towards immigration in GB. To exclude all other countries from our dataset we need a) to know the value of the variable that corresponds to Great Britain (country==826) b) to delete all other values of the country variable from our dataset. To do so we will use the filter ()
function.
sub.sample %>% filter(country == 826)
Our next step is to let R know which values represent missing cases. According to the codebook all values ranging from -10 to -1 describe missing cases (Don’t know, No answer, not applicable)
sub.sample[sub.sample <=-1] <- NA
sub.sample[sub.sample <=-2] <- NA
Our dependent variable is a continuous variable with a range from 1 to 10, where 1 means that the respondent hold anti-immigration attitudes (Immigrants take jobs) and 10 that the respondent doesn’t hold anti-immigration attitudes. When the large number, in our example (10), indicate lower agreement with the phenomenon under study, then we say that the variables are negatively coded. This is not really wrong but it makes more sense, is more intuitive, to reverse the order of the coding. It is the case that readers and researchers expect higher values to indicate higher levels of agreement with the phenomenon under study, in this case anti-immigration attitudes.
Using the arrange( )
function we can reverse the order of the code of the values. In our example what we want is instead of 10
representing positive attitudes towards immigration to represent negative ones.
sub.sample<-sub.sample %>% mutate(immi.jobs=(max(v185,na.rm=TRUE)-(v185)))
Note: I used the na.rm=T function inside the max function max()
. This is because otherwise due to NAs R cannot make the maths.
To make sure we did everything correctly we use the table ()
function to compare the two variables- before and after reversing the codes.
table(sub.sample$immi.jobs)
table(sub.sample$v185)
We should apply the same method to reverse the order of three more variables v189 to v193.
sub.sample<-sub.sample %>% mutate(born.country=(max(v189,na.rm=TRUE)-(v189)))
sub.sample<-sub.sample %>% mutate(respect.inst=(max(v190,na.rm=TRUE)-(v190)))
sub.sample<-sub.sample %>% mutate(country.ancestry=(max(v191,na.rm=TRUE)-(v191)))
sub.sample<-sub.sample %>% mutate(speak.lang=(max(v192,na.rm=TRUE)-(v192)))
sub.sample<-sub.sample %>% mutate(share.cultr=(max(v193,na.rm=TRUE)-(v193)))
head(sub.sample)
Our next step is to create the age
variable, we know the year of birth and that the survey administrated in 2017. To calculate the responder’s name when the survey took place we substract respondents year of birth from the year the survey took place (2017- year of birth).
sub.sample<-sub.sample %>% mutate(age=2017-v226)
table(sub.sample$age)
Our last step is to use the rename( )
function, part of dplyr
to give meaningful names to our variables.
sub.sample<-sub.sample %>%
rename(education=v243_edulvlb, gender=v225, left_right=v102)
head(sub.sample)


ReleaseManager.Plugin behaviour
This module provide a simple way to add additional steps to the release task.
You can define your own plugins using the sample definition below. Note that
the module namespace must be nested under ReleaseManager.Plugin.*
.
defmodule ReleaseManager.Plugin.Hello do
use ReleaseManager.Plugin
def before_release(%Config{} = config) do
info "This is executed just prior to compiling the release"
end
def after_release(%Config{} = config) do
info "This is executed just after compiling the release"
end
def after_cleanup(_args) do
info "This is executed just after running cleanup"
end
end
A couple things are imported or aliased for you. Those things are:
- The ReleaseManager.Config struct is aliased for you to just Config
debug/1
,info/1
,warn/1
,notice/1
, anderror/1
are imported for you. These should be used to do any output for the user.
before_release/1
and after_release/1
are required callbacks, and will each be passed a
Config
struct, containing the configuration for the release task. You can choose
to return the config struct modified or unmodified, or not at all. In the former case,
any modifications you made will be passed on to the remaining plugins and the final
release task. The required callback after_cleanup/1
is passed the command line arguments.
The return value is not used.
All plugins are executed just prior, and just after compiling the release, as the name of
the callbacks reflect. The before_release/1
callback is called after some internal tasks,
such as generating the sys.config and others.
Summary↑
| load_all() | Loads all plugins in all code paths |
| load_plugins(paths) | Loads all plugins in the given |
Functions
Specs:
- load_all :: [] | [atom]
Loads all plugins in all code paths.
Specs:
- load_plugins([binary]) :: [] | [atom]
Loads all plugins in the given paths
.
Callbacks
Specs:
- after_release(ReleaseManager.Config.t) :: any
Specs:
- before_release(ReleaseManager.Config.t) :: any
A plugin needs to implement before_release/1
, and after_release/1
both of which receive a %ReleaseManager.Config struct


A dynamic self-driving buggy capable of proving
calibrated cinematographic
shots as good as two world-class pilots combined. Currently, under
development, this buggy will automate the need of the two pilots by
intelligently moving and detecting an object to provide the best possible
cinematographic shot.


An administrative panel, upload photos and descriptions, generate and print the QR Code
An administrative panel, upload photos and descriptions, generate and print the QR Code
Create an account
Dishes, pictures, descriptions and you are on the way!
See instantly the menu on the smartphone
Take your dishes shots. Just real shots!
RealMenu could be offered to your customers as a service
In few clicks you spread your entire menu on the socials!
Vuoi provare gratis Real Menu? Scrivici
Have you got some custom need? We are happy to hear that from your voice!


{{ define "main" }}
Verification code sent again to<EMAIL_ADDRESS>Verification code sent to<EMAIL_ADDRESS>Enter the 6-digit verification code sent to xyz@gmail.com


The character end index of this token in the original string.
The character start index of this token in the original string.
The classification confidences of this token in the dictionary.
The associative confidences which classifiers have applied to this token.
The classification confidences which classifiers have applied to this token in multiple passes.
The index of this token.
The next token.
The previous token.
The stem of this token.
The original symbol of this token.
The Parts of Speech information for this token.
Generated using TypeDoc
A token which is part of a string.


I found this comic strip (pictured left) to be a very interesting take on the notion of comics. I haven't researched which form of media came first, comics, or film, but they both essentially achieve a similar purpose; tell a story associated with images (maybe the same could be said for memes).
What makes this excerpt super effective as a persuasive mode to achieve this point is that the comic sequence is stylized as a film strip. This gives the viewer a visual representation.
This comparison, however, got me thinking about modern forms of comics. Memes achieve an extremely similar style of comics (text with deliberately associated images), however they are ripe for the modern age of digital communication.
Memes, like comics, can tell a story with these things. Look below, for example, at this meme:
It has a similar form of a comic (text and associated image), it makes you chuckle (depending on if you're not a person who cringes at silly puns), and also provides a sort of commentary on the English language.
From the etimology of the word "comic", associated with comedy, the word means "a narrative with a happy ending; any composition intended for amusement". This meme fits the guise of "intended for amusement", while also staying true to Scott McCloud's definition:
This meme also succeeds in being a "juxtaposition of pictoral and other images in deliberate sequence". While also conveying information. The information it conveys, on a subsurface level, is about how odd the english language is. English speakers would understand "let that sink in" in the context of pondering a thought and having an idea materialize in your brain. However, if you literally looked at the words and visually depicted what they said, you would get an image similar to the meme.


This visualisation uses D3js to draw the shapes and sizes of cricket grounds from around the world.
The data points that feed in to each SVG image consist of ground length
, ground width
and ground name
. It was surprisingly difficult to find the dimensions of cricket grounds on the internet. I manually measured the majority of grounds myself using the 'measure distance' option in Google Maps.
To show Test Match batting and bowling records for each ground, hover over the pitch (or 'click' if on mobile device). Where a ground hasn't hosted a test match, ODI records are used. All statistics are sourced from www.howstat.com.
This visualisation was created by Conrad MacCormick | Code available here.


|
IKSDL
1.1
C++ wrapper for SDL 2 library
|
Component that is able to draw entities using hardware acceleation. More...
#include <Renderer.hpp>
Public Member Functions | |
| Renderer (const Renderer &)=delete | |
| IKSDL_EXPORT | Renderer (Renderer &&other) |
| Move constructor. More... | |
| IKSDL_EXPORT | ~Renderer () |
| Destructor. More... | |
| Renderer & | operator= (const Renderer &)=delete |
| IKSDL_EXPORT Renderer & | operator= (Renderer &&other) |
| Move assignment operator. More... | |
| IKSDL_EXPORT void | clear (const Color &clearColor=Color(0, 0, 0)) const |
| Clear the rendering area. More... | |
| IKSDL_EXPORT void | display () const |
| Render the drawn entities. More... | |
| void | draw (const Drawable &drawable) |
| Draw an entity. More... | |
| IKSDL_EXPORT void | setViewport (const Recti &viewport) |
| Change the viewport. More... | |
| IKSDL_EXPORT void | resetViewport () |
| Change to the default viewport. More... | |
Static Public Attributes | |
| static constexpr RendererOptions | DEFAULT_OPTIONS = RendererOptions().accelerated() |
| Default renderer options. More... | |
Protected Member Functions | |
| Renderer (SDL_Window &sdlWindow, const RendererOptions &options=DEFAULT_OPTIONS) | |
| Constructor that makes the renderer work in a window. More... | |
Friends | |
| class | Texture |
| class | BaseText |
Component that is able to draw entities using hardware acceleation.
|
delete |
| IKSDL_EXPORT iksdl::Renderer::Renderer | ( | Renderer && | other | ) |
Move constructor.
| other | Renderer to be moved |
| IKSDL_EXPORT iksdl::Renderer::~Renderer | ( | ) |
Destructor.
|
explicitprotected |
Constructor that makes the renderer work in a window.
| sdlWindow | Window as SDL struct |
| options | Rendering options |
Clear the rendering area.
| clearColor | Color that will fill the cleaned area |
|
inline |
Render the drawn entities.
|
inline |
Draw an entity.
| drawable | Entity to draw |
|
inline |
Change to the default viewport.
| IKSDL_EXPORT void iksdl::Renderer::setViewport | ( | const Recti & | viewport | ) |
Change the viewport.
| viewport | New viewport |
|
friend |
|
friend |
|
staticconstexpr |
Default renderer options.


Salesforce may be preparing an Alexa-esque AI assistant for the workplace
by Mike MooreSalesforce may be preparing an Alexa-esque AI assistant for the workplace
Einstein smart speaker shows the potential of AI in business applications
(Image credit: Salesforce)
Salesforce is hoping to make AI an indispensable part of every business with a range of smart tools and platforms.
At its Dreamforce 2019 event in San Francisco this week, the software giant unveiled a host of enterprise-focused services and tools it hopes will spur on AI adoption in companies of all sizes.
Salesforce also unveiled its own-brand smart speaker (pictured above) modelled on its Einstein AI mascot, although whether it will go on general sale is still unclear.
- Salesforce: Welcome to the fourth wave of computing
- What is AI? Everything you need to know
- Salesforce and Apple team up to transform your CRM
"Hey Einstein"
This growth in business-focused AI is set to be powered by a major expansion to Einstein Voice Assistant, which allows Salesforce users to communicate directly to the platform and get answers instantly.
Einstein Voice Assistant is now able to be tailored to any particular industry, allowing for custom-built skills that can cover tasks from checking order history to sentiment tracking.
“Voice is a huge shift for the industry and will be as impactful in businesses as it’s been in our homes,” said Bret Taylor, President and Chief Product Officer, Salesforce. “With Einstein, Salesforce is bringing the power of voice to every business, giving everyone an intelligent, trusted guide at work.”
During his opening keynote, Salesforce CEO Marc Benioff showed off a prototype device built to resemble the company’s Einstein mascot that was able to respond to queries and assist on a number of different use cases.
Awakened with the phrase "Hey Einstein", the device was a constant presence throughout the keynote, but there was no confirmation from Benioff that it would ever see the light of day outside of Salesforce’s offices.
The news came after Salesforce announced a partnership with AWS to use AI technology from Amazon's cloud computing arm into its Service Cloud to provide call transcription services directly to customer agents.
- The best cloud storage of 2019 online: free paid, and business options


FD: Measuring functional diversity (FD) from multiple traits, and
other tools for functional ecology
FD is a package to compute different multidimensional FD indices. It implements a distance-based framework to measure FD that allows any number and type of functional traits, and can also consider species relative abundances. It also contains other useful tools for functional ecology.
Downloads:
Reverse dependencies:
| Reverse depends: |
geosptdb, idar |
| Reverse imports: |
BioGeoBEARS, cati, ClusterR, ecospace, hillR, pez, RAM, Select, STEPCAM, SYNCSA |
| Reverse suggests: |
EcoIndR |
Linking:
Please use the canonical form
https://CRAN.R-project.org/package=FD
to link to this page.


{% extends "events/base_sidebar.html" %} {% block title %}Winter Code Jam 2020: Ancient Technology{% endblock %} {% block breadcrumb %}
The theme for the Winter Code Jam 2020, the sixth Python Discord Code Jam, was utilizing the Kivy Framework to create Ancient Technology. The jam lasted for 9 days from January 17, 2020 to January 26, 2020 with 16 teams competing against each other.
The original task description, as found in the repository, was as follows:
By popular choice, the theme for this code jam is Ancient Technology.
What you do with this theme or how you interpret it is up to you, but it will be your task to come up with something fun using this theme.
If you want to watch the original code jam judging stream, you can find it on YouTube - all of the submissions are showcased in the stream. The winning project is showcased at the 03:48:30 timestamp.
The winning team for this code jam was team Tactless Tricksters, consisting of GoBig87, Kan, sposker, DomicidalManiac, and Inventor. They created an incredible morse code chatting app, with a plethora of different features. Morse code training, morse code audio encoding/decoding, audio input sensitivity calibration, and a morse code messaging system are all features of this project. The beautiful and intuitive UI paired with all these features was what won them this jam. With the given amount of time during this jam, this was quite the impressive project.
You can check out their entry in the repository and watch us doing so in the livestream. The top 3 winning teams' projects are also displayed on the Kivy Gallery.
The Circumstantial Champions (salt-die, david987, & Music) created a game in which players go back in time to smash and carve out rocks, just like cavemen. The combination of their execellent graphical interface, animations, and satisfying sounds made this one of the most polished projects in the jam.
Check out their submission in the code jam repository and view it live on the livestream.
Team Inquisitive Investigators (f1re & Monika) ended up in third place with their retro TUI file explorer. The simple, easy-to-use file explorer along with their built-in terminal, text editor, and photo viewer made this a very feature packed project.
Feel free to view their submission on the repository and watch us review it on the livestream.
{% endblock %} {% block sidebar %} {% include "events/sidebar/code-jams/6.html" %}


public class StatsAppState extends AbstractAppState
| Modifier and Type | Field and Description |
|---|---|
protected Geometry |
darkenFps |
protected Geometry |
darkenStats |
protected BitmapText |
fpsText |
protected int |
frameCounter |
protected BitmapFont |
guiFont |
protected Node |
guiNode |
protected float |
secondCounter |
protected boolean |
showSettings |
protected StatsView |
statsView |
initialized
| Constructor and Description |
|---|
StatsAppState() |
StatsAppState(Node guiNode,
BitmapFont guiFont) |
| Modifier and Type | Method and Description |
|---|---|
void |
cleanup()
Called by
AppStateManager when transitioning this
AppState from terminating to detached. |
BitmapText |
getFpsText() |
float |
getSecondCounter() |
StatsView |
getStatsView() |
void |
initialize(AppStateManager stateManager,
Application app)
Called by
AppStateManager when transitioning this AppState
from initializing to running.This will happen on the next iteration through the update loop after AppStateManager.attach(com.jme3.app.state.AppState) was called. |
boolean |
isDarkenBehind() |
void |
loadDarken() |
void |
loadFpsText()
Attaches FPS statistics to guiNode and displays it on the screen.
|
void |
loadStatsView()
Attaches Statistics View to guiNode and displays it on the screen
above FPS statistics line.
|
void |
setDarkenBehind(boolean darkenBehind) |
void |
setDisplayFps(boolean show) |
void |
setDisplayStatView(boolean show) |
void |
setEnabled(boolean enabled)
Enable or disable the functionality of the
AppState . |
void |
setFont(BitmapFont guiFont)
Called by SimpleApplication to provide an early font
so that the fpsText can be created before init.
|
void |
toggleStats() |
void |
update(float tpf)
Called to update the
AppState . |
isEnabled, isInitialized, postRender, render, stateAttached, stateDetached
protected StatsView statsView
protected boolean showSettings
protected Node guiNode
protected float secondCounter
protected int frameCounter
protected BitmapText fpsText
protected BitmapFont guiFont
protected Geometry darkenFps
protected Geometry darkenStats
public StatsAppState()
public StatsAppState(Node guiNode, BitmapFont guiFont)
public void setFont(BitmapFont guiFont)
public BitmapText getFpsText()
public StatsView getStatsView()
public float getSecondCounter()
public void toggleStats()
public void setDisplayFps(boolean show)
public void setDisplayStatView(boolean show)
public void setDarkenBehind(boolean darkenBehind)
public boolean isDarkenBehind()
public void initialize(AppStateManager stateManager, Application app)
AppState
AppStateManager
when transitioning this AppState
from initializing to running.AppStateManager.attach(com.jme3.app.state.AppState)
was called.
AppStateManager
will call this only from the update loop
inside the rendering thread. This means is it safe to modify the scene
graph from this method.
initialize
in interface AppState
initialize
in class AbstractAppState
stateManager
- The state managerapp
- The applicationpublic void loadFpsText()
public void loadStatsView()
public void loadDarken()
public void setEnabled(boolean enabled)
AppState
AppState
.
The effect of this call depends on implementation. An
AppState
starts as being enabled by default.
A disabled AppState
s does not get calls to
AppState.update(float)
, AppState.render(RenderManager)
, or
AppState.postRender()
from its AppStateManager
.setEnabled
in interface AppState
setEnabled
in class AbstractAppState
enabled
- activate the AppState or not.public void update(float tpf)
AppState
AppState
. This method will be called
every render pass if the AppState
is both attached and enabled.update
in interface AppState
update
in class AbstractAppState
tpf
- Time since the last call to update(), in seconds.public void cleanup()
AppState
AppStateManager
when transitioning this
AppState
from terminating to detached. This
method is called the following render pass after the AppState
has
been detached and is always called once and only once for each time
initialize()
is called. Either when the AppState
is detached or when the application terminates (if it terminates normally).cleanup
in interface AppState
cleanup
in class AbstractAppState


string geoip_isp_by_name ( string $hostname )
The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to. This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.
Returns the ISP name on success, or FALSE if the address cannot be found in the database.


Join the numbers and get to the 2048 tile!
How to play:
Use your arrow keys to move tiles within each box.
Use the W,A,S,D keys to move tiles across boxes.
(I'm sorry that you can't play it on a smartphone)
When two tiles with the same number touch, they merge into one!
Created by Maigo on Mar. 18, 2014.
Based on the 2048 game by Gabriele Cirulli.
Inspired by the 2048-3D game by joppi.


Simulation of positive definite matrices constrained by an undirected or acyclic directed graph structure.
| Version: | 0.2.0 |
| Imports: | igraph, stats |
| Suggests: | testthat, covr |
| Published: | 2018-12-03 |
| Author: | Irene Córdoba [aut, cre], Gherardo Varando [aut], Concha Bielza [ths], Pedro Larrañaga [ths] |
| Maintainer: | Irene Córdoba <irene.cordoba at upm.es> |
| BugReports: | https://github.com/irenecrsn/gmat/issues |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://github.com/irenecrsn/gmat |
| NeedsCompilation: | yes |
| Citation: | gmat citation info |
| Materials: | README NEWS |
| CRAN checks: | gmat results |
| Reference manual: | gmat.pdf |
| Package source: | gmat_0.2.0.tar.gz |
| Windows binaries: | r-devel: gmat_0.2.0.zip, r-release: gmat_0.2.0.zip, r-oldrel: gmat_0.2.0.zip |
| OS X binaries: | r-release: gmat_0.2.0.tgz, r-oldrel: gmat_0.2.0.tgz |
| Old sources: | gmat archive |
Please use the canonical form https://CRAN.R-project.org/package=gmat to link to this page.


Hurricane Sandy Emergency Management Response Map
Andrew Homka | John Shaner | Siddharth Pandey | Geography 461W
Legend
Evacuation Centers
Fire Stations
Police Precincts
Hospitals
Storm Surge (1m Depth)
Storm Surge (3m Depth)
Evacuation Zones
6
5
4
3
2
1
Compare Imagery


Scripts can be compiled to executable binary (.exe) files and distributed without exposing the original source code.
To compile via commad line use the following arguments:
ironahk /out example.exe script.ahk
Special directives like #AssemblyTitle and #AssemblyVersion can be used to set additional properties of the compiled executable file.
Compiled binaries do not have the overhead of parsing syntax before execution and are therefore quicker to start up. Performance can be further improved with Ngen on Windows or Mono AOT.
While the resulting binary resembles nothing like the original source code, disassembly and reverse engineering can still be used to reveal any potentially sensitive strings or algorithms. This can be mitigated with obfuscation and encryption.
Binaries rely on IronAHK.Rusty.dll
and IronAHK.Scripting.dll
to be installed to the GAC, on the systems PATH
or present in the same working directory. ILMerge or mkbundle can be used to avoid dependence, a future version will have similar functionality built-in.


So as a Ph.D. student who studies in Computer Science, using LaTeX to render the equations in my blog is inevitable. In general, I hope the render can support the following features:
- Markdown Support: I use Jekyll and markdown to write the blogs. So the render should be integrated to this system seamlessly. Moreover, it should be able to:
- Use LaTeX code directly in the markdown without any other html/javascript notion. For example,
$$ E = mc^2 $$
should be rendered to automatically. - Work in default Github Page environment. I want to use Github Page to automatically generate the site. And due to the security reason, Github doesn’t allow running custom plugins for Jekyll. Therefore, the rendering shouldn’t depend any non-default plugin or markdown parser.
- Use LaTeX code directly in the markdown without any other html/javascript notion. For example,
- Quality: Quality is important. The render needs to be fast and output print quality typesetting.
The most popular way to render LaTeX within Jekyll is using MathJaX. There are lots of blogs (e.g. this) to show you how to configure it. But MathJaX has a huge shortage on rendering speed. It’s slow, not for a bit, but so slow that you can see the web page reflowing itself.
Recently, I came across a new project KaTeX. It’s fast as you can see the comparison below in which KaTeX is on the left and MathJax is on the right. There’s also a benchmark available here.
So how to make KaTeX work in the Jekyll? Will Drevo offers a comprehensive manual to make it work. However, it requires us to write LaTeX code inside html div
block. And I found this blog to explain how to use KaTeX with javascript. Combining both of these works, and with some extra effort, I find the approach to use KaTeX seamlessly inside Jekyll.
First of all, we need to configure Jekyll using kramdown as markdown parser and mathjax as kramdown’s math engine. In result, inline math equation will be rendered into a script block with “math/tex” as type. Like this: <script type="math/tex"> tex code </script>
. Similarly the display style math equation will turn into a script block with “math/tex; mode=display” as type. Like this: <script type="math/tex; mode=display"> tex code </script>
.
Secondly, let us put the required resources into the html head.
Finally, with the power of jQuery and KaTeX, we replace all the tex code block to rendered high quality equations fast. But remember, this javascript should be loaded at the end of html file.
Here’s the final result of rendered equation in below. Also you can do whatever custom you want in css file using class inline-equation
and equation
.


Home
About
Services
Contact us
Customer Order Form
*
Indicates a required field.
Customer Informatiom:
First Name
*
Last Name
*
Phone
*
Street Address
*
City
*
State
*
ZIP
Payment Information
Credit Card Number
*
Credit Card
*
American Express
Discover
Master Card
Visa
Expiration Date
*
January (01)
February (02)
March (03)
April (04)
May (05)
June (06)
July (07)
August (08)
September (09)
October (10)
November (11)
December (12)
2011
2012
2013
2014
2015
Order Information:
Processor Speed
2.4GHz
3.2GHz
4.0GHz
5.5GHz
Memory
1GB
2GB
4GB
8GB
12GB
Monitor Size
15-inch
17-inch
19-inch
21-inch
Hard Drive
240GB
500GB
750GB
1TB
DVD burner
LAN card
Media card reader
Extend Warranty
None
24-month
Comments
I'd like to special recieve offers from Millenium Computers.
Comments


Toggle navigation
Home
Teams
About
NCAA
conferences
American Athletic
Cincinnati
Connecticut
East Carolina
Houston
Memphis
Navy
SMU
South Florida
Temple
Tulane
Tulsa
UCF
ACC
Boston College
Clemson
Duke
Florida State
Georgia Tech
Louisville
Miami(FL)
NC State
North Carolina
Pittsburgh
Syracuse
Virginia
Virginia Tech
Wake Forest
Big 12
Baylor
Iowa State
Kansas
Kansas State
Oklahoma
Oklahoma State
TCU
Texas
Texas Tech
West Virginia
Big Ten
Illinois
Indiana
Iowa
Maryland
Michigan
Michigan State
Minnesota
Nebraska
Northwestern
Ohio State
Penn State
Purdue
Rutgers
Wisconsin
Conference USA
Florida Atlantic
Florida Intl
Louisiana Tech
Marshall
Middle Tennessee
North Texas
Old Dominion
Rice
Southern Mississippi
Texas San Antonio
UTEP
Western Kentucky
FBS Independents
Army
BYU
Notre Dame
Mid-American
Akron
Ball State
Bowling Green
Buffalo
Central Michigan
Eastern Michigan
Kent State
Massachusetts
Miami(OH)
Northern Illinois
Ohio
Toledo
Western Michigan
Mountain West
Air Force
Boise State
Colorado State
Fresno State
Hawaii
Nevada
New Mexico
San Diego State
San José State
UNLV
Utah State
Wyoming
Pac-12
Arizona
Arizona State
California
Colorado
Oregon
Oregon State
Stanford
UCLA
USC
Utah
Washington
Washington State
SEC
Alabama
Arkansas
Auburn
Florida
Georgia
Kentucky
LSU
Mississippi State
Missouri
Ole Miss
South Carolina
Tennessee
Texas A&M
Vanderbilt
Sun Belt
Appalachian State
Arkansas State
Georgia Southern
Georgia State
Idaho
Louisiana Lafayette
Louisiana Monroe
New Mexico State
South Alabama
Texas State
Troy
Statistics
table
Put table here


About
Locations
Merch
Sales Page
Insert Location Information
Location name
Minimum Customers Per Hour
Maximum Customers Per Hour
Average Cookies Sold Per Customer
Submit
Store Location Information:


Filespec
public struct Filespec : Codable
Filespec expected to store a file related information that could be not available after how a file was downloaded. Filespec object could be stored in .json format representation.
Filespec can be useful in some situations, for example, let say you have a path to a local file, but you also want to know from where that file was downloaded.
-
url** from where the file was downloaded
Declaration
Swift
public var url: URL?
-
directoryPath** where the file is located in the device
Declaration
Swift
public var directoryPath: String?
-
original given name to the file
Declaration
Swift
public var name: String?
-
filename** that stores in the device
Declaration
Swift
public var filename: String?
-
File’s extention
Declaration
Swift
public var fileExtension: String?
-
File size, in bytes
Declaration
Swift
public var size: Int64?
-
The location of the directory in the Application sandbox
Declaration
Swift
public var searchPathDirectoryId: UInt?
-
full path where the file is located in the device
Declaration
Swift
var path: String? { get }
-
Data** representation of Filespec in JSON format
Declaration
Swift
var jsonData: Data? { get }
-
Initialization of Filespec
Declaration
Swift
init?(fromJsonData jsonData: Data)
Parameters
jsonData
Data that represent Filespec in JSON format
-
Creates a Filespec
Declaration
Swift
init?(fromFilespecPath path: String)
Parameters
path
path where a Filespec file located
-
Creates a Filespec
Declaration
Swift
init(url: URL?, path: String?, name: String?, filename: String?, fileExtension: String?, size: Int64?, searchPathDirectoryId: UInt?)
Parameters
url
url from where the file was downloaded
path
path where the file is located in the device
name
original given name to the file
filename
filename that stores in the device
fileExtension
File’s extention
size
File size, in bytes
searchPathDirectoryId
The location of the directory in the Application sandbox


APC Crisis: Edo APC dissociates self from South South caucus meeting
by Rasheed SobowaleBy Gabriel Enogholase – Benin
Edo State chapter of the All Progressives Congress (APC) has dissociated itself from the proposed meeting of the South-South caucus of the party in Abuja, saying that it was called without due consultation with leaders of the party in the zone.
A statement by the State chairman of the party in Benin, Mr Anselm Ojezu stated that the meeting should be held in the zone and not at the private office of the suspended National Chairman of the APC, Comrade Adams Oshiomhole.
He said, “Our attention has been drawn to a notice of meeting of members of the South-south caucus of our party scheduled to take place at the private office of the suspended National Chairman of the All Progressives Congress (APC), Comrade Adams Oshiomhole in the Federal Capital Territory, Abuja.
“Members are by this medium advised to ignore this notice and refrain from attending the meeting which was called without due consultation of the leaders of our party in the zone.”
ALSO READ: APC Crisis: Oshiomhole’s seat non-negotiable, Omo-Agege declares
He explained that the state chapter of the party has “learnt that the purpose of the meeting is to procure and pass a vote of confidence on the embattled national chairman, Adams Oshiomhole, among other sinister motives.
“This is in spite of the series of “No Confidence” votes earlier passed by all the relevant organs of the Party in his home state where it matters the most.
“A proper meeting of the caucus members within the boundaries of the South-south region of Nigeria should be convened in due course, after due consultation with the leaders of the zone.”


--- layout: example.html title: Tiles shortdesc: Example of different tile layers rendered in Google Maps. docs: >
Shows different tile layers rendered in Google Maps. Note: the layers are displayed in the order that you enable them.
Whenever the opacity is changed on an OL3 layer, the same change is applied to the layer rendered by Google Maps. However, while Google Maps is active, all OL3 layers have their opacity set to 0. This means whenever the opacity is changed, OL3-Google-Maps changes it back to 0.
To do this, we listen to the opacity:change event. This event is not fired if the value doesn't change. This means that setting the value to 0 on the OL3 layer won't work, the value should be set to something close to 0 instead. The slider below goes from 0.01 to 1, although Number.MIN_VALUE could be used instead.
---


We're sorry, we couldn't find any flight information from {{ helperService.originAirport }} to {{ locationData.airport_code }}. You may have better luck searching with a bigger airport or for specific dates on Skyscanner or your preferred airline's website.
This Destination's airport is the same as the one you are flying out of.


Delicious
THE BEST FOOD BLOG ON THE WEB.
THE BEST FOOD BLOG ON THE WEB.
POSTED ON 15 DEC 2013 / DESSERTS
For the fig-swirl:Melt buuter over meduim heat in a saucepan.Add brown sugar and stir to dissolve.Halve all of the figs and toss in the saucepan with water and lemon juice.Cook over meduim heat, stirring frequentlym until you have a chuncky-jammy mixture.Add salt with one or two dtirs, set aside and let cool completely.
Ice cream:In small pot over meduim heat, combine milk,and granulated sugar until sugar is completely dissolved aand the milk is just barely lukewarm.Whisk in the egg yolks.Set mixture in the fridge and wait until the fig miture is cooled.
Using an ice cream machine, pour liquids into frozen basin and process according to manufacturer instructions,i.e.,let spin and thicken for 20 minutes before adding mascarpone,fig jam mixture,and the nuts.Continue to process for +/= 10 minutes.Pour semi-frozen mixture into a pyrex dish or galss tupperware.Freeze for at least two hours before serving.
Food enthusiast,photography fan.Add a pinch of raw foodism and that's pretty much who I am.


Pierce Brown spent his childhood building forts and setting traps for cousins in the woods of six states and the deserts of two. Graduating from college in 2010, he fancied the idea of continuing his studies at Hogwarts. Unfortunately, he doesn’t have a magical bone in his body. Instead, he tried to make it as a writer. He lives Los Angeles, where he scribbles tales of spaceships, wizards, ghouls, and most things old or bizarre.


nips nips2013 nips2013-242 nips2013-242-reference knowledge-graph by maker-knowledge-mining
Source: pdf
Author: Ilya O. Tolstikhin, Yevgeny Seldin
Abstract: We present a PAC-Bayes-Empirical-Bernstein inequality. The inequality is based on a combination of the PAC-Bayesian bounding technique with an Empirical Bernstein bound. We show that when the empirical variance is signiﬁcantly smaller than the empirical loss the PAC-Bayes-Empirical-Bernstein inequality is signiﬁcantly tighter than the PAC-Bayes-kl inequality of Seeger (2002) and otherwise it is comparable. Our theoretical analysis is conﬁrmed empirically on a synthetic example and several UCI datasets. The PAC-Bayes-Empirical-Bernstein inequality is an interesting example of an application of the PAC-Bayesian bounding technique to self-bounding functions. 1
[1] John Langford and John Shawe-Taylor. PAC-Bayes & margins. In Advances in Neural Information Processing Systems (NIPS), 2002.
[2] David McAllester. PAC-Bayesian stochastic model selection. Machine Learning, 51(1), 2003.
[3] John Langford. Tutorial on practical prediction theory for classiﬁcation. Journal of Machine Learning Research, 2005.
[4] Yevgeny Seldin and Naftali Tishby. PAC-Bayesian analysis of co-clustering and beyond. Journal of Machine Learning Research, 11, 2010.
[5] Matthew Higgs and John Shawe-Taylor. A PAC-Bayes bound for tailored density estimation. In Proceedings of the International Conference on Algorithmic Learning Theory (ALT), 2010. 8
[6] Yevgeny Seldin, Peter Auer, Francois Laviolette, John Shawe-Taylor, and Ronald Ortner. PAC¸ Bayesian analysis of contextual bandits. In Advances in Neural Information Processing Systems (NIPS), 2011.
[7] Matthias Seeger. PAC-Bayesian generalization error bounds for Gaussian process classiﬁcation. Journal of Machine Learning Research, 2002.
[8] Yevgeny Seldin, Francois Laviolette, Nicol` Cesa-Bianchi, John Shawe-Taylor, and Peter ¸ o Auer. PAC-Bayesian inequalities for martingales. IEEE Transactions on Information Theory, 58, 2012.
[9] Andreas Maurer and Massimiliano Pontil. Empirical Bernstein bounds and sample variance penalization. In Proceedings of the International Conference on Computational Learning Theory (COLT), 2009.
[10] Thomas M. Cover and Joy A. Thomas. Elements of Information Theory. John Wiley & Sons, 1991.
[11] Andreas Maurer. A note on the PAC-Bayesian theorem. www.arxiv.org, 2004.
[12] David McAllester. Some PAC-Bayesian theorems. Machine Learning, 37, 1999.
[13] A.W. Van Der Vaart. Asymptotic statistics. Cambridge University Press, 1998.
[14] St´ phane Boucheron, G´ bor Lugosi, and Olivier Bousquet. Concentration inequalities. In e a O. Bousquet, U.v. Luxburg, and G. R¨ tsch, editors, Advanced Lectures in Machine Learning. a Springer, 2004.
[15] A. Asuncion and D.J. Newman. UCI machine http://www.ics.uci.edu/∼mlearn/MLRepository.html. 9 learning repository, 2007.


A while back, I had two separate “issues” pop up quite independently. First, being disenchanted with the text editors in my life, I began to learn vim. Second, I began to worry about my blog; although I was regularly backing up my WordPress settings, I didn’t have archived hard copies of all my posts.
Rather esoterically, my mind began to blend the two issues together. Aaron, it said1, what if we figured out a way to use vim to write blog posts AND create an archived copy in Evernote? That would allow me to use all the beautiful power of vim, archive a copy of each post, and still get content into WordPress in an easy fashion. So, if anyone feels the need to be esoteric, here’s how I did it.
TL;DR
vim is a perfect blogging tool and, when combined with Evernote’s archival abilities, is making a case to replace my current toolset.
Step 1: Download and configure Geeknote.
The first bit of magic needed comes via Geeknote:
Are you a geek? Do you like Evernote? Geeknote – is for you! Geeknote is an opensource Evernote console client for Linux, FreeBSD and Mac OS X. Use it for system administration needs, creating notes, notebooks, sync your local directories with Evernote notebooks. Use the power of command line!
Geeknote’s website has excellent installation instructions to follow. Of particular note, let’s change the default Geeknote editor to vim:
$ geeknote settings –editor vim
Once completed, you can go ahead with the rest of the setup.
Step 2: Install the Sentinote plugin for WordPress.
Sentinote provides WordPress the ability to talk with Evernote:
Sentinote converts your notes into WordPress posts or pages. Keep using Evernote and when you’re ready to publish simply assign the “published” tag to your note. Tagging your notes lets you distinguish between posts and pages; set the note category; set the post format; assign a parent or just add normal post tags. Its like cyber magic!
Like Geeknote, Sentinote has great installation instructions. I’ll be waiting for you when you get back.
Step 3: Create a quick function for blog post creation
This step is entirely optional, but since we’re already on the command line, it’s useful to have a function that quickly creates blog posts:
Simply run bp
, enter a title for a blog post, and you’re off and running.
With the pieces in place, here’s how my workflow functions.
First, I run bp
, which places me into a new vim session:
Using vim’s excellence, I hammer out a blog post (in Markdown!) in record time:
With a quick :wq
, Geeknote saves the Markdown as HTML into a new Evernote note (using the notebook and tags defined in the bp
function):
When ready, I add the published
tag and synchronize Evernote; this is the trigger that Sentinote picks up on to create a new WordPress post. I head over to WordPress and make sure that the post imported properly:
While here, I adjust things like tags, the post’s publication date, and any other info that Sentinote can’t influence directly. Once I’m done, I head back to Evernote, remove the draft
tag, and re-synchronize. Within 5 minutes, my post becomes active:
Esoteric? Yes. But it solves two problems at once and is undeniably cool.
It certainly isn’t perfect2, but it gets the job done.


| Prime Number |
{{element.primeNumber}} |
Name of Business Segment |
{{element.businessSegment}} |
Region |
{{element.region}} |
Branch Code |
{{element.branchCode}} |
Name of Borrower |
{{element.nameOfBorrower}} |
CP Approval No |
{{element.cpApprovalNo}} |
Cp Approval Date |
{{element.cpApprovalDate|date:'dd-MM-yyyy'}} |
Date of Disbursement |
{{element.dateOfDisbursement|date:'dd-MM-yyyy'}} |
Type of Facility |
{{element.typeOfFacility}} |
Account Number |
{{element.accountNo}} |
Due Date |
{{element.dueDate|date:'dd-MM-yyyy'}} |
Tracking Date |
{{element.trackingDate|date:'dd-MM-yyyy'}} |
Action Taken or to be taken |
{{element.acctionToBeTaken}} |
Completion Date |
{{element.complianceDate|date:'dd-MM-yyyy'}} |
Created By |
{{element.createdBy}} |
Modified By |
{{element.modifiedBy}} |
Modified On |
{{element.modifiedOn}} |
Created On |
{{element.createdOn}} |
|
|
|
|


Uses of Class
org.apache.qpid.protonj2.types.Binary
Package
Description
-
Uses of Binary in org.apache.qpid.protonj2.codec
Modifier and TypeMethodDescriptionDecoder.readBinary
(ProtonBuffer buffer, DecoderState state) Reads an encodedBinary
value from the givenProtonBuffer
assuming that the next value in the byte stream is that type.StreamDecoder.readBinary
(InputStream stream, StreamDecoderState state) Reads an encodedBinary
value from the givenInputStream
assuming that the next value in the byte stream is that type.Modifier and TypeMethodDescriptionvoid
Encoder.writeBinary
(ProtonBuffer buffer, EncoderState state, Binary value) Writes the contents of the givenBinary
value into the providedProtonBuffer
instance as an AMQP Binary type. -
Uses of Binary in org.apache.qpid.protonj2.codec.decoders
Modifier and TypeMethodDescriptionProtonDecoder.readBinary
(ProtonBuffer buffer, DecoderState state) ProtonStreamDecoder.readBinary
(InputStream stream, StreamDecoderState state) -
Uses of Binary in org.apache.qpid.protonj2.codec.decoders.primitives
Modifier and TypeMethodDescriptionAbstractBinaryTypeDecoder.readValue
(InputStream stream, StreamDecoderState state) AbstractBinaryTypeDecoder.readValue
(ProtonBuffer buffer, DecoderState state) -
Uses of Binary in org.apache.qpid.protonj2.codec.encoders
Modifier and TypeMethodDescriptionvoid
ProtonEncoder.writeBinary
(ProtonBuffer buffer, EncoderState state, Binary value) -
Uses of Binary in org.apache.qpid.protonj2.codec.encoders.primitives
Modifier and TypeMethodDescriptionvoid
BinaryTypeEncoder.writeType
(ProtonBuffer buffer, EncoderState state, Binary value) -
Uses of Binary in org.apache.qpid.protonj2.engine
Modifier and TypeMethodDescriptionTransaction.getTxnId()
Returns the transaction Id that is associated with the declared transaction.Modifier and TypeMethodDescriptionTransactionManager.declared
(Transaction<TransactionManager> transaction, Binary txnId) Respond to a previousDeclare
request from the remoteTransactionController
indicating that the requested transaction has been successfully declared and that deliveries can now be enlisted in that transaction. -
Uses of Binary in org.apache.qpid.protonj2.engine.impl
Modifier and TypeMethodDescriptionProtonTransactionManager.declared
(Transaction<TransactionManager> transaction, Binary txnId) -
Uses of Binary in org.apache.qpid.protonj2.engine.util
Modifier and TypeMethodDescriptionstatic String
StringUtils.toQuotedString
(Binary buffer) Converts the Binary to a quoted string using a default max length before truncation value and appends a truncation indication if the string required truncation.static String
StringUtils.toQuotedString
(Binary buffer, boolean appendIfTruncated) Converts the Binary to a quoted string using a default max length before truncation value.static String
StringUtils.toQuotedString
(Binary buffer, int stringLength, boolean appendIfTruncated) Converts the Binary to a quoted string. -
Uses of Binary in org.apache.qpid.protonj2.types
-
Uses of Binary in org.apache.qpid.protonj2.types.messaging
-
Uses of Binary in org.apache.qpid.protonj2.types.security
Modifier and TypeMethodDescriptionSaslOutcome.setAdditionalData
(Binary additionalData) SaslChallenge.setChallenge
(Binary challenge) SaslInit.setInitialResponse
(Binary initialResponse) SaslResponse.setResponse
(Binary response) -
Uses of Binary in org.apache.qpid.protonj2.types.transactions
-
Uses of Binary in org.apache.qpid.protonj2.types.transport


Yaidom is a uniform XML query API, written in Scala. Moreover, yaidom provides several specific-purpose DOM-like tree implementations adhering to this XML query API.
In this article, the basics of element querying in yaidom are explained.
This article is the first in a series of articles introducing the yaidom library.
It is assumed that the reader knows the basics of XML, in particular XML namespaces. Some experience with XML processing in Java (e.g. JAXP) is also helpful. Finally, the reader is expected to have some familiarity with the Scala programming language, and with the Scala Collections API in particular.
This article only treats basic element querying in yaidom. The remainder of this article is organized as follows:
The queries use the ubiquitous bookstore as example XML. The specific sample XML is from the (coursera) course Introduction to Databases, by Jennifer Widom (with permission).
First we give an introductory example to querying in yaidom. Consider the following XML file: books.xml. Suppose we have parsed this document, and that the parsed document has been stored into variable doc
. Then we can query for all book author last names as follows (without removing duplicates):
import HasENameApi._
val authorLastNames =
for {
bookElem <- doc.documentElement \ withLocalName("Book")
authorElem <- bookElem \\ withLocalName("Author")
lastNameElem <- authorElem \ withLocalName("Last_Name")
} yield lastNameElem.text
Unlike querying with the standard Scala XML library, we cannot chain \
and \\
operators. It will become clear below why yaidom sacrifices a little bit of conciseness compared to XML libraries that offer a more XPath-like experience.
Still, we can write the query above in a less verbose manner, much like how the Scala compiler rewrites the for-comprehension. This is already more XPath-like, but not necessarily more readable:
val authorLastNames2 =
doc.documentElement \ withLocalName("Book") flatMap
(_ \\ withLocalName("Author")) flatMap
(_ \\ withLocalName("Last_Name")) map (_.text)
XML processing in Java has never been easy. Direct use of SAX, DOM or StAX is low-level and cumbersome. Use of XPath may be low-level in the handling of returned DOM nodes or node lists, and performance issues quickly arise. Several other (DOM-like) libraries may improve on JAXP DOM, but still do not make XML processing significantly easier. The use of O-X mapping (such as JAXB) just for XML manipulation seems the wrong tool for the job, since that would turn an XML manipulation problem into a bigger O-X mapping problem between 2 different perspectives ("Java object" and "XML") that must be kept in sync. (I'm not against O-X mapping, but I would like to stay away from O-X mapping if there is inherently no O-X mapping problem in the first place.)
Direct manipulation of XML should not be that hard. In Java (at least before version 8) not only XML processing, but data processing in general is hard (writing low level loops instead of functionally transforming collections). Scala and its expressive Collections API have a far more appealing data processing story, as most Scala programmers would agree. Shouldn't then XML processing in Scala be easier than in Java, as a consequence?
There are 3 Scala XML libraries that currently often get mentioned. There is Scales XML, which is not a DOM-like API. Then there is Anti-XML, which seems abandoned, and which aimed to be an improvement on the third library, viz. the standard Scala XML library. Unfortunately, the standard Scala XML library has some (rather annoying) issues that I find hard to accept. For example:
Node
indirectly extending Seq[Node]
, and class MetaData
representing both an attribute and a linked list of attributes.\
and \\
offering namespace-aware attribute querying but only local-name-aware element querying.\
and \\
each meaning different things, depending on the string argument passed: element querying or attribute querying.I do realize that the standard XML library tried to offer an XPath-like experience. On the other hand, this implies blurring the distinction between individual nodes and node collections. Arguably, this also means less precision and clarity (e.g., what is the type of an expression?), in the name of conciseness and XPath-like query support.
A well-known (but somewhat old) critique of the Scala XML library (by the creator of Anti-XML) can be found here.
It seems hard to find a Scala XML library having first-class namespace support. The best explanation of XML namespaces that I have come across is Understanding XML Namespaces. It distinguishes between qualified names (such as my:foo
) and expanded names (such as {http://my}foo
, in James Clark notation). Admittedly, qualified names occur in XML, and expanded names do not. Still, both concepts are important, and many XML libraries blur this fundamental distinction. Ignoring this distinction makes it hard to talk precisely about namespaces. In my view that leads to subpar namespace support. The quest for first-class namespace support, along with precise (Scala-esque) element querying, were the most important reasons to come up with yaidom.
Yaidom has been influenced by all of the 3 Scala XML libraries mentioned above, be it in very different ways. It has its own underlying design choices, however. In particular:
This article does not go deeply into the namespace support offered by yaidom. The next article on yaidom (and namespaces) will make up for this shortcoming.
All code examples below can be tried out in the Scala REPL (if the parent directory path of the example files is replaced). Scala 2.11.X is required, and yaidom 1.3.2 (or later) must be on the classpath.
Before showing some basic yaidom element queries, assume the following code to have executed:
import java.io.File
import javax.xml.parsers._
import scala.collection.immutable
import eu.cdevreeze.yaidom._
// Using a yaidom DocumentParser that used DOM internally
val docParser = parse.DocumentParserUsingDom.newInstance
// Replace the following path!
val parentDir = new File("/path/to/parentdir")
val doc: simple.Document =
docParser.parse(new File(parentDir, "books.xml"))
val docElem = doc.documentElement
Here we instantiated a yaidom parser (using DOM internally), and parsed the XML file. The document element is stored in variable docElem
, as "default" (immutable) yaidom element.
Let's get started with some basic yaidom element queries. The books.xml XML has some magazines and books. We can query for the magazines (as yaidom elements) as follows:
val magazineElems =
docElem.filterChildElems(e => e.localName == "Magazine")
In this query, we queried only for (some) child elements of the document element, knowing that all magazines are child elements of the document element. We also used no namespace in the query, knowing that in this case no ambiguity can arise. The query result consists of the following 4 XML elements:
<Magazine Month="January" Year="2009" xmlns="http://bookstore">
<Title>National Geographic</Title>
</Magazine>
<Magazine Month="Februari" Year="2009" xmlns="http://bookstore">
<Title>National Geographic</Title>
</Magazine>
<Magazine Month="Februari" Year="2009" xmlns="http://bookstore">
<Title>Newsweek</Title>
</Magazine>
<Magazine Month="March" Year="2009" xmlns="http://bookstore">
<Title>Hector and Jeff's Database Hints</Title>
</Magazine>
Analogously, we can query for the 4 books (as yaidom elements) as follows:
val bookElems1 =
docElem.filterChildElems(e => e.localName == "Book")
require(bookElems1.size == 4, "Expected 4 books")
Above, we queried for child elements with local name Book
, using method filterChildElems
. We could have queried for all descendant elements with local name Book
instead, using method filterElems
. Not surprisingly, the same elements would be returned:
val bookElems2 =
docElem.filterElems(e => e.localName == "Book")
require(
bookElems2 == bookElems1,
"Expected the same books as in bookElems1")
We could also query for all descendant-or-self elements with local name Book
, using method filterElemsOrSelf
. Again, the result would be the same:
val bookElems3 =
docElem.filterElemsOrSelf(e => e.localName == "Book")
require(
bookElems3 == bookElems1,
"Expected the same books as in bookElems1")
If we import the HasENameApi
companion object members, then we can write the element predicate more briefly using (element predicate factory) method withLocalName
, like this:
import queryapi.HasENameApi._
val bookElems4 =
docElem filterElemsOrSelf withLocalName("Book")
Now we know how to query for child elements, descendant elements or descendant-or-self elements, given an element predicate. Instead of writing filterChildElems
we can write \
, and instead of writing filterElemsOrSelf
we can write \\
, however. This would give us:
val bookElems5 = docElem \ withLocalName("Book")
and:
val bookElems6 = docElem \\ withLocalName("Book")
Most of yaidom's query API is easy to guess knowing the methods presented above. For example, method findAllElems
returns all descendant elements (excluding self), and method findAllElemsOrSelf
returns all descendant-or-self elements.
Above, we introduced basic element querying in yaidom, using the "standard" element implementation. Yaidom does not conform to the view that there is a one-size-fits-all element implementation, as we will see. Fortunately, this does not mean that there are as many yaidom element query APIs as there are element implementations. On the contrary, most element implementations mix in the ElemApi
trait, which is the most important part of the query API.
The yaidom element query API plays very well with the Scala Collections API. Typical non-trivial queries are written as for-expressions, combining Scala collections with yaidom query API methods. In a sense, the yaidom element query API is a uniform element query API, and the Scala Collections API plays the role of universal (collection) query API. Put differently, yaidom query methods turn single elements into collections of elements, and the Collections API turns collections (of elements) into other collections.
Below we show yaidom as uniform query API. Again start with the same document used above. This time using namespaces throughout the query, the book authors (separating first and last name by a space) can be found uniformly across element implementations as follows:
val ns = "http://bookstore"
import queryapi._
def findAllBookAuthors[E <: ElemApi[E] with HasText](docElem: E): immutable.IndexedSeq[String] = {
import HasENameApi._
val result =
for {
bookElem <- docElem \ withEName(ns, "Book")
authorElem <- bookElem \\ withEName(ns, "Author")
firstNameElem <- authorElem \ withEName(ns, "First_Name")
lastNameElem <- authorElem \ withEName(ns, "Last_Name")
} yield s"${firstNameElem.text} ${lastNameElem.text}"
result.distinct.sorted
}
Don't worry: typical yaidom client code does not abstract over multiple element implementations, so does not look this intimidating in the use of generics and F-bounded polymorphism. Generics are used here to show that the exact same query API works for multiple element implementations. In the function signature above, E
is the type of the element implementation itself. We also imported all members of the HasENameApi
companion object, to have the withEName
element predicate builder in scope.
Given the schema document above, we can query the book authors as follows:
val bookAuthors1 =
findAllBookAuthors(doc.documentElement)
The query result consists of the following Strings:
Hector Garcia-Molina, Jeffrey Ullman, Jennifer Widom
Prefixes are insignificant in XML. Consider schema file books2.xml, which is equivalent to books.xml, except that the default namespace has been replaced by prefix books
:
val doc2: Document =
docParser.parse(new File(parentDir, "books2.xml"))
How can we easily assert that these documents are equivalent XML documents? To that end, yaidom offers so-called "resolved" elements, which contain only expanded (element and attribute) names, and no qualified names. Indeed:
val rootElem = doc.documentElement
val rootElem2 = doc2.documentElement
// Method removeAllInterElementWhitespace makes the equality comparison
// more robust, because it removes whitespace used for formatting
require(resolved.Elem(rootElem).removeAllInterElementWhitespace ==
resolved.Elem(rootElem2).removeAllInterElementWhitespace)
To show that the yaidom query API is uniform, let's now perform the same query, but passing it a "resolved" element instead of "default" element:
val resolvedDocElem =
resolved.Elem(doc.documentElement)
val bookAuthors2 =
findAllBookAuthors(resolvedDocElem)
require(
bookAuthors2 == bookAuthors1,
"Expected the same authors as bookAuthors1")
Sometimes we have a (mutable) JAXP DOM tree, and do not want to convert it to a yaidom immutable Elem
tree. We can still use the yaidom query API to query those DOM elements. Function findAllBookAuthors
can still be called:
// Using a JAXP (DOM) DocumentBuilderFactory
val dbf = DocumentBuilderFactory.newInstance
val db = dbf.newDocumentBuilder
val d = db.parse(new File(parentDir, "books.xml"))
val wrapperDoc = dom.DomDocument(d)
val bookAuthors3 =
findAllBookAuthors(wrapperDoc.documentElement)
require(
bookAuthors3 == bookAuthors1,
"Expected the same authors as bookAuthors1")
Sometimes we want to use immutable elements, and still have access to the ancestry of each element. For example, when querying for book authors, we could then alternatively implement this by querying for all authors, followed by checking in the ancestry if the author is for a book or a magazine. With so-called "indexed" elements, each element has indeed access to its ancestry. It is beyond the scope of this first yaidom article to go into the specifics, however.
This time using "indexed" elements, we again query for book authors:
val indexedDoc = indexed.Document(doc)
val bookAuthors4 =
findAllBookAuthors(indexedDoc.documentElement)
require(
bookAuthors4 == bookAuthors1,
"Expected the same authors as bookAuthors1")
There are more element implementations offering the same query API, such as wrappers for Scala XML Elem
instances. Yaidom is extensible in this regard, since more element implementations can easily be created by mixing in some yaidom traits like ElemLike
(which conforms to the ElemApi
contract), and by implementing the methods that are abstract in those traits.
In this article a case was made for yet another Scala XML library, called yaidom. Its precise support for XML namespaces and its precise element query API may be its strongest assets. The API plays very well with the Scala Collections API, and it trades a little bit of conciseness for clarity and precision.
The basics of querying in yaidom were explained in this article. It was shown that different element implementations share the same element query API (the ElemApi
trait in particular). It was also hinted at why yaidom has different element implementations in the first place.
Succeeding articles on yaidom will treat namespaces, more advanced querying, functional updates, and configuration of yaidom.
As a concluding remark, yaidom is used in production code developed at www.ebpi.nl. Its usage in several projects has certainly helped it mature. I want to thank my colleagues Jan-Paul van der Velden, Andrea Desole, Johan Walters and Nicholas Evans for their valuable feedback on earlier versions of yaidom.


'use strict';
var observable = require('./util/observable');
/** Returns the selected `DOMRange` in `document`. */
function selectedRange(document) {
var selection = document.getSelection();
Iif (!selection.rangeCount || selection.getRangeAt(0).collapsed) {
return null;
} else {
return selection.getRangeAt(0);
}
}
/**
* Returns an Observable stream of text selections in the current document.
*
* New values are emitted when the user finishes making a selection
* (represented by a `DOMRange`) or clears a selection (represented by `null`).
*
* A value will be emitted with the selected range at the time of subscription
* on the next tick.
*
* @return Observable<DOMRange|null>
*/
function selections(document) {
// Get a stream of selection changes that occur whilst the user is not
// making a selection with the mouse.
var isMouseDown;
var selectionEvents = observable.listen(document,
['mousedown', 'mouseup', 'selectionchange'])
.filter(function (event) {
if (event.type === 'mousedown' || event.type === 'mouseup') {
isMouseDown = event.type === 'mousedown';
return false;
} else {
return !isMouseDown;
}
});
var events = observable.merge([
// Add a delay before checking the state of the selection because
// the selection is not updated immediately after a 'mouseup' event
// but only on the next tick of the event loop.
observable.buffer(10, observable.listen(document, ['mouseup'])),
// Buffer selection changes to avoid continually emitting events whilst the
// user drags the selection handles on mobile devices
observable.buffer(100, selectionEvents),
// Emit an initial event on the next tick
observable.delay(0, observable.Observable.of({})),
]);
return events.map(function () {
return selectedRange(document);
});
}
module.exports = selections;
|


This div should be in Ubuntu font (with TTF) after font loads.
This one is heavier
and
This one is even heavier
.
This another div should be in Ubuntu Light font (with WOFF) after font loads.
Check console for various events!
The Ubuntu Font Family is from
its official website
.


Life, Sans Facebook
It has been around three months since, after much back and forth in my head, I decided to permanently delete my Facebook account. In that time, I’ve been asked several times why I left, so I opted to write this short post to spell out my thoughts in a more succinct and thorough manner.
I had originally joined Facebook back in 2008 when it was the newest fad among my friends and I. As I remember, it was cool and a lot of fun. The omnipresent social network played an important part in my high-school social life and helped me keep in contact with my friends once we were unleashed onto the world after graduation. My friends were a decent group on the internet and I mostly enjoyed my interactions with them, so I do not have any horror stories to relate. Facebook helped facilitate my long distance relationships by allowing me to keep up with my friends’ new jobs, how they were doing, what classes they were taking, what day their birthday was, etc. Also, seeing something on Facebook served as a conversation springboard when offline.
So, why did I leave?
I believe there’s a need to forget, to move on. Both for me and for my friends. People naturally drift apart; Facebook undermines that and ends up creating superficial, passive connections. I also like the mysteriousness of new relationships, the process of discovering things about another person. Facebook ruins that completely by giving you immediate access to their entire social history once you “friend” them. I have no desire to see that, or for others to see mine.
I tailor myself—as almost everyone does—to the people I’m with. I do that, not because I’m disingenuous, but because I have a wide variety of passions and my friends may not share specific interests. Facebook makes the tailoring process more difficult than other social media platforms because people expect you to only have one account. On a similar note, I prefer private correspondence with friends, which contrasts with Facebook’s “share everything with everyone” attitude. That’s a big cup of no.
Futhermore, I’m somewhat a minimalist by nature. Facebook is the antithesis of minimalism; more is always more in Facebook land. I disliked having to micromanage my account, which had become almost expected of everyone. I’m also less sentimental and nostalgic than most, so Facebook’s forced persistence of my past did little to benefit me.
There are idealogical reasons as well. I dislike Facebook’s attitude towards privacy. It’s very difficult to control who can see your posts and deleting isn’t actually deleting. Also, it is very difficult to get a picture of yours—or of you—removed from Facebook. The untagging feature is simply inadequate. I understand that they need to run a business, but I disagree that it is only sustainable through intrusive data-mining and advertising.
Last but not least, Facebook has a dangerous monopoly on our online social lives. People automatically assume that you have one and when you don’t, they’re often stunned. I could not and would not support that because it hurts innovation and it could have unwanted side effects.
These were just some of the thoughts racing through my head that November night when I yanked the plug on Facebook. It wasn’t an easy decision1, but I feel like it was the right one.
Or task. Getting pictures, contacts, birthdays, etc. off of Facebook is a major pain.↩