Thomas de Groot<EMAIL_ADDRESS>Joe Raad<EMAIL_ADDRESS>Stefan Schlobach<EMAIL_ADDRESS>It is simple to find an inconsistent knowledge graph, but not simple to find all justifications
We want to develop an approach that allows us to:
minimal subset of the KG that is sufficient for the contradiction to hold
Contradicting anti-pattern containing the essence of the justification
Can we define a more general explanation for contradictions, that categorises the most common mistakes in a KG, independently from its domain?
Can we retrieve these generalised explanations from any KG, independently from its size?
How can these generalised explanations help analysing and comparing certain characteristics between the most commonly used KGs in the Web?
Definition 1 (Anti-Pattern)
(P) is an anti-pattern of a Knowledge Graph(G)
if there is a substitution μ(P) s.t. μ(P)⊆G,
and μ(P) is minimally inconsistent w.r.t some entailment relation (E),
i.e. @P′ s.t. P′⊂P and μ(P′) is inconsistent.
Retrieval of the anti-pattern from an explanation
Retrieval of the anti-pattern from an explanation
Retrieval of subgraphs from the knowledge graph with a max limit of $G_{max}$ triples
Retrieval of the detected inconsistencies with their justifications
Generalization of each justification to a distinct anti-pattern
From knowledge graph to a list of anti-patterns via the retrieval and generalization procedure
| $G_{max}$ | Anti-patterns | Subgraphs | Total Runtime(s) |
|---|---|---|---|
| 500 | 0 | 101,673 | 1,783 |
| 1,000 | 2 | 50,960 | 3,505 |
| 2,500 | 31 | 20,436 | 4,329 |
| 5,000 | 39 | 10,218 | 4,525 |
| 7,500 | 39 | 6,812 | 4,977 |
| 10,000 | 39 | 5,109 | 5,106 |
| 25,000 | 39 | 2,041 | 5,347 |
| 50,000 | 39 | 1,014 | 5,497 |
| 100,000 | 39 | 507 | 5,758 |
| $G_{max}$ | Anti-patterns | Subgraphs | Total Runtime(s) | Step 1 Runtime | Step 2 Runtime | Step 3 Runtime |
|---|---|---|---|---|---|---|
| 500 | 0 | 18,203,648 | 3,403 | 649 | 2,753 | 1 |
| 1,000 | 0 | 9,123,936 | 3,941 | 1,223 | 2,717 | 1 |
| 5,000 | 135 | 1,829,442 | 14,342 | 2,125 | 12,004 | 214 |
| 10,000 | 135 | 914,721 | 18,283 | 2,265 | 15,739 | 279 |
| 25,000 | 135 | 365,422 | 19,174 | 2,938 | 16,013 | 223 |
| 50,000 | 135 | 181,547 | 34,177 | 3,289 | 30,684 | 204 |
| 100,000 | 135 | 90,773 | 68,264 | 3,976 | 64,081 | 206 |
The Goldilock zone($G_{max}$) in our experiments is 5,000
| LOD-a-lot | DBpedia | YAGO | |
|---|---|---|---|
| number of triples | 28,362,198,927 | 1,040,358,853 | 158,991,568 |
| number of distinct namespaces | 9,619 | 20 | 11 |
| number of distinct anti-patterns | 222 | 13 | 135 |
| largest anti-pattern size | 19 | 12 | 16 |
| runtime (in hours) | 157.56 | 13.01 | 3.98 |
Size distribution for all three knowledge graphs of the anti-pattern support
Sample of three anti-pattern types, with SPARQL queries to locate them
Distribution of the anti-pattern support.
Where we show the amount of distinct justifications per anti-pattern
Thomas de Groot<EMAIL_ADDRESS>Joe Raad<EMAIL_ADDRESS>Stefan Schlobach (k.s.schlobach@vu.nl)


@import views.html.helpers.phpBlock @import org.joda.time.DateTime @(title: String, publishDate: DateTime, tags: List[String])
I ran into a a problem using PDO for a long running PHP script the other day. I kept getting a "MySQL server went away" exception that would crash my script.
Well I looked up this issue online and found that the PDO connection was timing out and causing statement execution to throw that error: StackOverflow
One proposed solution was to catch that exception and attempt to reconnect to the database. But now my problem is that I have abstracted away the database implementation details and am working off an abstract data repository in my script.
So my long running script looks like this:
@phpBlock( """ $pdo = new PDO(...connection details...); $repository = new ItemRepository($pdo); while (! $terminationRequested) { $item = findNextItem(); $repository->save($item); // ...delay for some time... } """ )And the problem is $repository->save($item)
can throw an exception if the MySQL database server
"goes away" (in other words times out). One solution is to renew the PDO
database connection every
loop so that is never times out:
And that works, but it doesn't feel right - why does my calling code need to be changed in order to accommodate a
leaky abstraction? A better solution is to handle the reconnect at the data access layer, inside the
Repository
class itself. Unfortunately that is not all that simple.
For one, PDO
has no option for reconnecting to the database if a connection is lost. It also does not
save the connection parameters in the object itself, so you cannot just extend the class and add reconnecting to it.
You also can't extend the PDOStatement
object PDO
returns because it is hard coded into
the PDO
class. It seems like the best thing you can do is put try/catch blocks everywhere you get a
PDOStatement
:


|
upkeeper 1
|
Upkeeper is a process control, monitor, with auditing system.
Upkeeper consists of 4 logical components
upkeeper's is almost between DJB's daemontools, and freedesktop's systemd, in terms of functionality and capabilities. However, it adds the additional capability of recording state changes of monitored processes to a data store, which can then be interogated, preferably via the API, for the purpose troubleshooting, event correlation, metrics collection, trending, and analysis.
A high-level view of the interaction between components is as follows:
Controller is responsible for maintaining the configuration of buddy process, establishing the environment in which buddy runs, and invoking buddies. Once a buddy has been invoked, it runs autonymously until terminated. Excessive care has been taken to ensure that a buddy will not terminate under normal, and even some rather extraordinary, circumstances.
Buddy is a simplistic-by-design component that primarily just sits in a loop and waits for the process its monitoring to change terminate, or otherwise catch a signal. To communicate status changes with controller, buddy listens to a socket, which controller polls at a configurable interval. If controller dies for some reason, buddy has a user-configurably sized ringbuffer which will backlog status events, and report them once a controller becomes available. If a ringbuffer becomes >= 75% full, or if a buddy is attempting to terminate while having events in its ringbuffer, the buddy will attempt to contact a controller on the controller's domain socket, as a last-resort.
The environment buddy runs in is a directory structure with files and symlinks that buddy uses to invoke actions, and log output.
Clients consist of things like "uptop", which is a status reporting tool that is similar to the common "top" utility. Clients communicate with controller via the API provided in libupkeeper. Hence, you can easily create any client you require, including metrics reporting and/or monitoring and alerting systems.
To explain this, the following sequence chart demonstrates how the components interact:
Start a managed process:
Whereas a read-only process, such as subscribing to, and receiving events over time would look like this:
{ // StateDir // Path to variable state-dir for controller and buddies "StateDir": "/usr/var/upkeeper", // SvcConfigPath // Path to location of service configuration files "SvcConfigPath": "/usr/etc/upkeeper.d", // SvcRunPath // Path to location to setup and run buddies "SvcRunPath": "/usr/var/upkeeper/buddies", // Path to the buddy executable "UpkBuddyPath": "/usr/libexec/upk_buddy", // How frequently buddy sockets should be polled for events // in seconds and fractions of a second "BuddyPollingInterval": 0.5, // ServiceDefaults: "ServiceDefaults": { // An array of strings (['foo','bar']) describing what this service provides. These are then used in ordering service // startup via prerequisites. Service name, package, and UUID are implicitely added to the list of Provides. "Provides": [], // A valid UUID for the service, will be automatically generated if not provided. "UUID": Null, // A brief description of the service "ShortDescription": Null, // A longer and more complete description of the service "LongDescription": Null, // An array of strings (['foo','uuid#<...>']) of what must already be running (as named in 'Provides') // before this service should start. The syntax <package-name>:<service-name> may be used to specify a service from // a specific package. The syntax 'uuid#<uuid-string>' can be used to specify an explicit UUID. "Prerequisites": [], // Numeric start priority, used in lieu of, or in conjunction with Provides/Prerequisites to determine start order "StartPriority": 0, // Shutdown timeout before resorting to SIGKILL, Values < 0 will never SIGKILL "KillTimeout": 60, // Maximum number of times a process may fail in-a-row before its state is changed to down // a negative value indicates to restart forever (and is the default) "MaxConsecutiveFailures": -1, // user-defined max number of restarts within restart window "UserMaxRestarts": Null, // User-defined restart window, in seconds "UserRestartWindow": Null, // duration, in seconds, to wait between respawn attempts "UserRateLimit": Null, // a flag to enable/disable adding a randomized jitter to the user_ratelimit "RandomizeRateLimit": false, // if controller and/or buddy is run euid root; which uid to run the service as "SetUID": 0, // if controller and/or buddy is run euid root; which gid to run the service as "SetGID": 0, // size of the ringbuffer to maintain in the buddy "RingbufferSize": 64, // number of times to retry connections to the controler when emergent actions // occur in the buddy; (-1 for indefinate) "ReconnectRetries": 10, // command to exec for start, see 'StartScript' "ExecStart": Null, // script to start the monitored process; The default is 'exec %(EXEC_START)' "StartScript": "#!/bin/sh\nexec %(EXEC_START)\n", // command to exec for stop. Default: 'kill', see 'StopScript' "ExecStop": "kill", // Script to stop the monitored process. The default is 'exec %(EXEC_STOP) $1'; where $1 passed // to it will be the pid of monitored process (and also the pgrp, and sid, unless the monitored process changed them "StopScript": "#!/bin/sh\nexec %(EXEC_STOP) $1\n", // command to exec for reload. Default: 'kill -HUP', see 'ReloadScript' "ExecReload": "kill -HUP", // Script to reload the monitored process. The default is 'exec %(EXEC_RELOAD) $1'; where $1 passed // to it will be the pid of monitored process (and also the pgrp, and sid, unless the monitored process changed them "ReloadScript": "#!/bin/sh\nexec %(EXEC_RELOAD) $1\n", // A collection of key/value (JSON Object: {"foo":"bar"}) pairs where the key is the name of the action, and // the value is the contents of a script script to run for that action "CustomActions": {}, // optional script to pipe stdout to. For example: 'exec logger -p local0.notice' "PipeStdoutScript": Null, // optional script to pipe stderr to. For example: 'exec logger -p local0.warn' "PipeStderrScript": Null, // optional place to direct stdout. // Note that if you pipe stdout elsewhere, this might never be written to, unless the thing you pipe to prints // to stdout itself "RedirectStdout": Null, // optional place to direct stderr. // Note that if you pipe stderr elsewhere, this might never be written to, unless the thing you pipe to prints // to stderr itself "RedirectStderr": Null, // state the service should be set to initially. this is used only when a service is first configured. "InitialState": "stopped", // May be used by a package to instruct the controler to remove a configured service // if the file defining that service ever disappears. Possibly useful in packaging // to cleanup the controller on package removal. The default behavior is to ignore // file removal, and require explicit manual removal of configured services "UnconfigureOnFileRemoval": false, // If the controller starts/restarts, and buddy has a service state set to 'stopped', // but controller's data-store believes the service should be running, prefer // buddy's world view, and update the data-store to reflect the stopped state. // The default is to trust the data-store; which would cause the service to be started "PreferBuddyStateForStopped": false, // if the controller starts/restarts, and buddy has a service state set to 'running', // but controller's data-store believes the service should be stopped, prefer // buddy's world view, and update the data-store to reflect the running state. // The default is to trust the buddy, which would leave the service running "PreferBuddyStateForRunning": true, }, }


--- layout: default title : Experience permalink: /experience/ ---
I've been fortunate enough to be in the co-op program at Waterloo, which means I'll be graduating in 5 years with 6 internship opportunites. I've learned a lot in my time at all these companies, both technically and personally!
I've tried my hand at contracting only once, and it was a great learning experience for me! Working full-remote was also really fun and led to an understanding that communication is crucial in general, regardless of remote or in-person work.


Preface
Introduction
Lesson 6
Lesson 7
Hurricane Andrew
State Population Demo
Temperature Wave Demo
Bouncing Tiger and King Tut
Colophon


--- layout: post status: publish published: true title: FXCop author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 343 wordpress_url: http://winterdom.com/2004/12/fxcop date: '2004-12-02 04:05:37 +0000' date_gmt: '2004-12-02 04:05:37 +0000' categories: - ".NET" tags: [] comments: [] ---
I hadn't looked at FXCop in a while, and decided to check it out again (in part because I'm setting up a new set of build tools for our project including things like CruiseControl.NET). Wow, FXCop has improved a lot since then.
I do have a problem with it, though, that perhaps someone can answer. Is there a way to disable the identifier spelling rules?
See, the thing is our code throws hundreds of errors with those rules, mostly because our code is written in spanish (and a mix of english on some parts, don't ask). I did see a way to check the dictionary language in the settings dialogs, but that's not what I want, I just want to ignore the rule altogether. Any clues?


|
AADC
v1.3.4
Audi Autonmous Driving Cup
|
class of filter for the communication with the jury More...
#include <cStateController.h>
Public Member Functions | |
| cStateController (const tChar *) | |
| virtual tResult | Init (tInitStage eStage, __exception=NULL) |
| virtual tResult | Start (__exception=NULL) |
| virtual tResult | Stop (__exception=NULL) |
| virtual tResult | Shutdown (tInitStage eStage, __exception=NULL) |
| tResult | OnPinEvent (IPin *pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample *pMediaSample) |
| tResult | Run (tInt nActivationCode, const tVoid *pvUserData, tInt szUserDataSize, ucom::IException **__exception_ptr=NULL) |
| tResult | SendState (stateCar state, tInt16 i16ManeuverEntry) |
| tResult | createTimer () |
| tResult | destroyTimer (__exception=NULL) |
| tResult | incrementManeuverID () |
| tResult | resetSection () |
| tResult | changeState (stateCar newState) |
| tResult | setManeuverID (tInt maneuverId) |
| tResult | loadManeuverList () |
Private Member Functions | |
| ADTF_DECLARE_FILTER_VERSION (__guid,"AADC State Controller", OBJCAT_Tool,"State Controller", 1, 0, 0,"Beta Version") | |
class of filter for the communication with the jury
Der Inhalt bzw. die StateMachine dieses Filters sollte von jedem Team in den eigenen Code übernommen werden.
Definition at line 33 of file cStateController.h.
| tResult cStateController::changeState | ( | stateCar | newState | ) |
changes the state of the car
| newState | the new state of the car |
Definition at line 392 of file cStateController.cpp.
| tResult cStateController::createTimer | ( | ) |
creates the timer for the cyclic transmits
Definition at line 430 of file cStateController.cpp.
| tResult cStateController::destroyTimer | ( | __exception | = NULL | ) |
destroys the timer for the cyclic transmits
Definition at line 447 of file cStateController.cpp.
| tResult cStateController::incrementManeuverID | ( | ) |
increments the id of the maneuver id by one and updates the list indexes
Definition at line 480 of file cStateController.cpp.
|
virtual |
overrides cFilter
Definition at line 41 of file cStateController.cpp.
| tResult cStateController::loadManeuverList | ( | ) |
this functions loads the maneuver list given in the properties
Definition at line 324 of file cStateController.cpp.
| tResult cStateController::OnPinEvent | ( | IPin * | pSource, |
| tInt | nEventCode, | ||
| tInt | nParam1, | ||
| tInt | nParam2, | ||
| IMediaSample * | pMediaSample | ||
| ) |
overrides cFilter
Definition at line 158 of file cStateController.cpp.
| tResult cStateController::resetSection | ( | ) |
resets the counters to the start of the current section
Definition at line 522 of file cStateController.cpp.
| tResult cStateController::Run | ( | tInt | nActivationCode, |
| const tVoid * | pvUserData, | ||
| tInt | szUserDataSize, | ||
| ucom::IException ** | __exception_ptr = NULL |
||
| ) |
overrides cFilter
Definition at line 134 of file cStateController.cpp.
| tResult cStateController::SendState | ( | stateCar | state, |
| tInt16 | i16ManeuverEntry | ||
| ) |
signal for sending the state
| i8StateID | state to be sent; -1: error, 0: Ready, 1: Running |
| i16ManeuverEntry | current entry to be sent |
Definition at line 274 of file cStateController.cpp.
| tResult cStateController::setManeuverID | ( | tInt | maneuverId | ) |
set the maneuver id and find the correct indexes
| maneuverId | the id of the maneuver which has to be set |
Definition at line 533 of file cStateController.cpp.
|
virtual |
overrides cFilter
Definition at line 153 of file cStateController.cpp.
|
virtual |
overrides cFilter
Definition at line 129 of file cStateController.cpp.
|
virtual |
overrides cFilter
Definition at line 144 of file cStateController.cpp.
| tBool cStateController::m_bDebugModeEnabled |
whether output to console is enabled or not
Definition at line 139 of file cStateController.h.
| cOutputPin cStateController::m_DriverStructOutputPin |
output pin for state from driver
Definition at line 136 of file cStateController.h.
| tHandle cStateController::m_hTimer |
handle for the timer
Definition at line 160 of file cStateController.h.
| tInt16 cStateController::m_i16CurrentManeuverID |
holds the current maneuver id of the car
Definition at line 151 of file cStateController.h.
| tInt16 cStateController::m_i16ManeuverListIndex |
holds the current index of the maneuvers in the list in the section
Definition at line 154 of file cStateController.h.
| tInt16 cStateController::m_i16SectionListIndex |
holds the current index in the lists of sections
Definition at line 157 of file cStateController.h.
| cInputPin cStateController::m_JuryStructInputPin |
input pin for the run command
Definition at line 115 of file cStateController.h.
| cFilename cStateController::m_maneuverListFile |
this is the filename of the maneuver list
Definition at line 142 of file cStateController.h.
| cCriticalSection cStateController::m_oCriticalSectionTimerSetup |
the critical section of the timer setup
Definition at line 166 of file cStateController.h.
| cCriticalSection cStateController::m_oCriticalSectionTransmit |
the critical section of the transmit
Definition at line 163 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescDriverStruct |
Coder Descriptor for output driver struct
Definition at line 94 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescIncrementManeuver |
Coder Descriptor for input restart section
Definition at line 112 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescJuryStruct |
Coder Descriptor for input jury struct
Definition at line 91 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescRestartSection |
Coder Descriptor for input restart section
Definition at line 109 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescSetStateComplete |
Coder Descriptor for input set state stop
Definition at line 103 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescSetStateError |
Coder Descriptor for input set state error
Definition at line 97 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescSetStateReady |
Coder Descriptor for input set state ready
Definition at line 106 of file cStateController.h.
| cObjectPtr<IMediaTypeDescription> cStateController::m_pCoderDescSetStateRunning |
Coder Descriptor for input set state running
Definition at line 100 of file cStateController.h.
| std::vector<tSector> cStateController::m_sectorList |
this is the list with all the loaded sections from the maneuver list
Definition at line 145 of file cStateController.h.
| stateCar cStateController::m_state |
holds the current state of the car
Definition at line 148 of file cStateController.h.
| cInputPin cStateController::m_StateCompleteInputPin |
input pin for the set state stop command
Definition at line 124 of file cStateController.h.
| cInputPin cStateController::m_StateErrorInputPin |
input pin for the set state error command
Definition at line 118 of file cStateController.h.
| cInputPin cStateController::m_StateIncrementManeuverInputPin |
input pin for the set state ready command
Definition at line 133 of file cStateController.h.
| cInputPin cStateController::m_StateReadyInputPin |
input pin for the set state ready command
Definition at line 127 of file cStateController.h.
| cInputPin cStateController::m_StateRestartSectionInputPin |
input pin for the set state ready command
Definition at line 130 of file cStateController.h.
| cInputPin cStateController::m_StateRunningInputPin |
input pin for the set state running command
Definition at line 121 of file cStateController.h.


This is a post generator for my Nimble Slides slide resource / blog project using Blogger. Once I fell into a format for posts, I wanted a quicker way to generate the html for my posts.
Output:


ChartBase Class
The ChartBase class is an abstract class used to create charts.
Item Index
Methods
- _addTooltip
- _dataProviderChangeHandler
- _getAxisClass
- _getGraph
- _getTooltip
- _itemRendered
- _markerEventDispatcher
- _planarLabelFunction
- _positionTooltip
- _setAriaElements
- _setDataValues
- _setOffscreen
- _setText
- _showTooltip
- _tooltipChangeHandler
- _tooltipLabelFunction
- _updateTooltip
- bindUI
- getAxisByKey
- getCategoryAxis
- getSeries
- hideTooltip
- initializer
- renderUI
- syncUI
- toggleTooltip
Attributes
Methods
_addTooltip
()
private
Adds a tooltip to the dom.
_dataProviderChangeHandler
-
e
Event handler for dataProviderChange.
Parameters:
-
e
ObjectEvent object.
_getAxisClass
-
t
Helper method that returns the axis class that a key references.
Parameters:
-
t
StringThe type of axis.
Returns:
_getGraph
()
private
Default value function for the Graph
attribute.
Returns:
_getTooltip
()
private
Default getter for tooltip
attribute.
Returns:
_itemRendered
-
e
Handler for itemRendered event.
Parameters:
-
e
ObjectEvent object.
_markerEventDispatcher
-
e
Event handler for marker events.
Parameters:
-
e
ObjectEvent object.
_planarLabelFunction
-
categoryAxis
-
valueItems
-
index
-
seriesArray
-
seriesIndex
Formats tooltip text when interactionType
is planar
.
Parameters:
-
categoryAxis
AxisReference to the categoryAxis of the chart.
-
valueItems
ArrayArray of objects for each series that has a data point in the coordinate plane of the event. Each object contains the following data:
- axis
- The value axis of the series.
- key
- The key for the series.
- value
- The value for the series item.
- displayName
- The display name of the series. (defaults to key if not provided)
-
index
NumberThe index of the item within its series.
-
seriesArray
ArrayArray of series instances for each value item.
-
seriesIndex
NumberThe index of the series in the
seriesCollection
.
Returns:
_positionTooltip
-
e
Positions the tooltip
Parameters:
-
e
ObjectEvent object.
_setAriaElements
-
cb
Creates an aria live-region
, aria-label
and aria-describedby
for the Chart.
Parameters:
-
cb
NodeReference to the Chart's
contentBox
attribute.
_setDataValues
-
val
Setter method for dataProvider
attribute.
Parameters:
-
val
ArrayArray to be set as
dataProvider
.
Returns:
_setOffscreen
()
private
Sets a node offscreen for use as aria-description or aria-live-regin.
Returns:
_setText
-
label
-
val
Updates the content of text field. This method writes a value into a text field using
appendChild
. If the value is a String
, it is converted to a TextNode
first.
Parameters:
-
label
HTMLElementlabel to be updated
-
val
Stringvalue with which to update the label
_showTooltip
-
msg
-
x
-
y
Shows a tooltip
Parameters:
-
msg
StringMessage to dispaly in the tooltip.
-
x
Numberx-coordinate
-
y
Numbery-coordinate
_tooltipChangeHandler
-
e
Event handler for the tooltipChange.
Parameters:
-
e
ObjectEvent object.
_tooltipLabelFunction
-
categoryItem
-
valueItem
-
itemIndex
-
series
-
seriesIndex
Formats tooltip text when interactionType
is marker
.
Parameters:
-
categoryItem
ObjectAn object containing the following:
- axis
- The axis to which the category is bound.
- displayName
- The display name set to the category (defaults to key if not provided)
- key
- The key of the category.
- value
- The value of the category
-
valueItem
ObjectAn object containing the following:
- axis
- The axis to which the item's series is bound.
- displayName
- The display name of the series. (defaults to key if not provided)
- key
- The key for the series.
- value
- The value for the series item.
-
itemIndex
NumberThe index of the item within the series.
-
series
CartesianSeriesThe
CartesianSeries
instance of the item. -
seriesIndex
NumberThe index of the series in the
seriesCollection
.
Returns:
_updateTooltip
-
val
Updates the tooltip attribute.
Parameters:
-
val
ObjectObject containing properties for the tooltip.
Returns:
bindUI
()
private
getAxisByKey
-
val
Returns an Axis
instance by key reference. If the axis was explicitly set through the axes
attribute,
the key will be the same as the key used in the axes
object. For default axes, the key for
the category axis is the value of the categoryKey
(category
). For the value axis, the default
key is values
.
Parameters:
-
val
StringKey reference used to look up the axis.
Returns:
getCategoryAxis
()
Returns the category axis for the chart.
Returns:
getSeries
-
val
Returns a series instance by index or key value.
Parameters:
-
val
Object
Returns:
hideTooltip
()
Hides the default tooltip
initializer
()
private
renderUI
()
private
syncUI
()
private
toggleTooltip
-
e
Event listener for toggling the tooltip. If a tooltip is visible, hide it. If not, it will create and show a tooltip based on the event object.
Parameters:
-
e
ObjectEvent object.
Properties
_axes
Array
private
Collection of axes.
_axisClass
Object
private
Key value pairs of axis types.
_dataProvider
Array
private
Storage for the dataProvider
attribute.
_direction
String
private
Default direction of the chart.
Default: horizontal
_seriesCollection
Array
private
Storage for seriesCollection
attribute.
_setSeriesCollection
Unknown
private
Setter method for seriesCollection
attribute.
Sub-properties:
-
val
ArrayArray of either
CartesianSeries
instances or objects containing series attribute key value pairs.
Attributes
categoryType
String
Indicates the type of axis to use for the category axis.
- category
- Specifies a
CategoryAxis
. - time
- Specifies a `TimeAxis
Default: category
groupMarkers
Boolean
Indicates whether or not markers for a series will be grouped and rendered in a single complex shape instance.
interactionType
String
Indicates the the type of interactions that will fire events.
- marker
- Events will be broadcasted when the mouse interacts with individual markers.
- planar
- Events will be broadcasted when the mouse intersects the plane of any markers on the chart.
- none
- No events will be broadcasted.
Default: marker
seriesKeys
Array
A collection of keys that map to the series axes. If no keys are set, they will be generated automatically depending on the data structure passed into the chart.
tooltip
Object
Reference to the default tooltip available for the chart.
Contains the following properties:
- node
- Reference to the actual dom node
- showEvent
- Event that should trigger the tooltip
- hideEvent
- Event that should trigger the removal of a tooltip (can be an event or an array of events)
- styles
- A hash of style properties that will be applied to the tooltip node
- show
- Indicates whether or not to show the tooltip
- markerEventHandler
- Displays and hides tooltip based on marker events
- planarEventHandler
- Displays and hides tooltip based on planar events
- markerLabelFunction
- Reference to the function used to format a marker event triggered tooltip's text. The method contains
the following arguments:
- categoryItem
- An object containing the following:
- axis
- The axis to which the category is bound.
- displayName
- The display name set to the category (defaults to key if not provided).
- key
- The key of the category.
- value
- The value of the category.
- valueItem
- An object containing the following:
- axis
- The axis to which the item's series is bound.
- displayName
- The display name of the series. (defaults to key if not provided)
- key
- The key for the series.
- value
- The value for the series item.
- itemIndex
- The index of the item within the series.
- series
- The
CartesianSeries
instance of the item. - seriesIndex
- The index of the series in the
seriesCollection
.
HTMLElement
which is written into the DOM usingappendChild
. If you override this method and choose to return an html string, you will also need to override the tooltip'ssetTextFunction
method to accept an html string. - planarLabelFunction
- Reference to the function used to format a planar event triggered tooltip's text
- categoryAxis
-
CategoryAxis
Reference to the categoryAxis of the chart. - valueItems
- Array of objects for each series that has a data point in the coordinate plane of the event. Each object contains the following data:
- axis
- The value axis of the series.
- key
- The key for the series.
- value
- The value for the series item.
- displayName
- The display name of the series. (defaults to key if not provided)
- index
- The index of the item within its series.
- seriesArray
- Array of series instances for each value item.
- seriesIndex
- The index of the series in the
seriesCollection
.
HTMLElement
which is written into the DOM using appendChild
. If you override this method and choose to return an html string, you
will also need to override the tooltip's setTextFunction
method to accept an html string.
planarLabelFunction
or markerLabelFunction
into the the tooltip node.
has the following signature:
- label
- The
HTMLElement
that the content is to be added. - val
- The content to be rendered into tooltip. This can be a
String
orHTMLElement
. If an HTML string is used, it will be rendered as a string.
Events
markerEvent:click
Broadcasts when interactionType
is set to marker
and a series marker has received a click event.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- categoryItem
- Hash containing information about the category
Axis
. - valueItem
- Hash containing information about the value
Axis
. - node
- The dom node of the marker.
- x
- The x-coordinate of the mouse in relation to the Chart.
- y
- The y-coordinate of the mouse in relation to the Chart.
- pageX
- The x location of the event on the page (including scroll)
- pageY
- The y location of the event on the page (including scroll)
- series
- Reference to the series of the marker.
- index
- Index of the marker in the series.
- seriesIndex
- The
order
of the marker's series. - originEvent
- Underlying dom event.
markerEvent:mousedown
Broadcasts when interactionType
is set to marker
and a series marker has received a mousedown event.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- categoryItem
- Hash containing information about the category
Axis
. - valueItem
- Hash containing information about the value
Axis
. - node
- The dom node of the marker.
- x
- The x-coordinate of the mouse in relation to the Chart.
- y
- The y-coordinate of the mouse in relation to the Chart.
- series
- Reference to the series of the marker.
- index
- Index of the marker in the series.
- seriesIndex
- The
order
of the marker's series.
markerEvent:mouseout
Broadcasts when interactionType
is set to marker
and a series marker has received a mouseout event.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- categoryItem
- Hash containing information about the category
Axis
. - valueItem
- Hash containing information about the value
Axis
. - node
- The dom node of the marker.
- x
- The x-coordinate of the mouse in relation to the Chart.
- y
- The y-coordinate of the mouse in relation to the Chart.
- series
- Reference to the series of the marker.
- index
- Index of the marker in the series.
- seriesIndex
- The
order
of the marker's series.
markerEvent:mouseover
Broadcasts when interactionType
is set to marker
and a series marker has received a mouseover event.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- categoryItem
- Hash containing information about the category
Axis
. - valueItem
- Hash containing information about the value
Axis
. - node
- The dom node of the marker.
- x
- The x-coordinate of the mouse in relation to the Chart.
- y
- The y-coordinate of the mouse in relation to the Chart.
- series
- Reference to the series of the marker.
- index
- Index of the marker in the series.
- seriesIndex
- The
order
of the marker's series.
markerEvent:mouseup
Broadcasts when interactionType
is set to marker
and a series marker has received a mouseup event.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- categoryItem
- Hash containing information about the category
Axis
. - valueItem
- Hash containing information about the value
Axis
. - node
- The dom node of the marker.
- x
- The x-coordinate of the mouse in relation to the Chart.
- y
- The y-coordinate of the mouse in relation to the Chart.
- series
- Reference to the series of the marker.
- index
- Index of the marker in the series.
- seriesIndex
- The
order
of the marker's series.


A toolbox to assist with statistical analysis of 2-dimensional animal trajectories. It provides simple access to algorithms for calculating and assessing a variety of characteristics such as speed and acceleration, as well as multiple measures of straightness or tortuosity. McLean & Skowron Volponi (2018) <doi:10.1111/eth.12739>.
| Version: | 1.1.0 |
| Imports: | signal, utils, stats, graphics, plotrix, grDevices |
| Suggests: | knitr, rmarkdown, testthat |
| Published: | 2018-05-10 |
| Author: | Jim McLean [aut, cre] |
| Maintainer: | Jim McLean <jim_mclean at optusnet.com.au> |
| BugReports: | https://github.com/JimMcL/trajr/issues |
| License: | MIT + file LICENSE |
| URL: | https://github.com/JimMcL/trajr |
| NeedsCompilation: | no |
| Citation: | trajr citation info |
| Materials: | README |
| CRAN checks: | trajr results |
| Reference manual: | trajr.pdf |
| Vignettes: |
Introduction to trajr |
| Package source: | trajr_1.1.0.tar.gz |
| Windows binaries: | r-devel: trajr_1.1.0.zip, r-release: trajr_1.1.0.zip, r-oldrel: trajr_1.1.0.zip |
| OS X binaries: | r-release: trajr_1.1.0.tgz, r-oldrel: trajr_1.1.0.tgz |
| Old sources: | trajr archive |
Please use the canonical form https://CRAN.R-project.org/package=trajr to link to this page.


Cross Sectional Imputation¶
Imputations for cross-sectional data.
-
impyute.imputations.cs.
random_imputation
(data)[source]¶ Fill missing values in with a randomly selected value from the same column.
Parameters: data: numpy.ndarray
Data to impute.
Returns: numpy.ndarray
Imputed data.
-
impyute.imputations.cs.
mean_imputation
(data)[source]¶ Substitute missing values with the mean of that column.
Parameters: data: numpy.ndarray
Data to impute.
Returns: numpy.ndarray
Imputed data.
-
impyute.imputations.cs.
mode_imputation
(data)[source]¶ Substitute missing values with the mode of that column(most frequent).
In the case that there is a tie (there are multiple, most frequent values) for a column randomly pick one of them.
Parameters: data: numpy.ndarray
Data to impute.
Returns: numpy.ndarray
Imputed data.
-
impyute.imputations.cs.
median_imputation
(data)[source]¶ Substitute missing values with the median of that column(middle).
Parameters: data: numpy.ndarray
Data to impute.
Returns: numpy.ndarray
Imputed data.
-
impyute.imputations.cs.
mice
(data)[source]¶ Multivariate Imputation by Chained Equations
- Reference:
- Buuren, S. V., & Groothuis-Oudshoorn, K. (2011). Mice: Multivariate Imputation by Chained Equations in R. Journal of Statistical Software, 45(3). doi:10.18637/jss.v045.i03
Implementation follows the main idea from the paper above. Differs in decision of which variable to regress on (here, I choose it at random). Also differs in stopping criterion (here the model stops after change in prediction from previous prediction is less than 10%).
Parameters: data: numpy.ndarray
Data to impute.
Returns: numpy.ndarray
Imputed data.
-
impyute.imputations.cs.
em
(data, loops=50, dtype='cont')[source]¶ Imputes given data using expectation maximization.
E-step: Calculates the expected complete data log likelihood ratio. M-step: Finds the parameters that maximize the log likelihood of the complete data.
Parameters: data: numpy.nd.array
Data to impute.
loops: int
Number of em iterations to run before breaking.
dtype: (“cont”,”disc”)
Indicates whether the possible values will come from a continuous range or categorical range.
Returns: numpy.nd.array
Imputed data.


|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES |
| Packages that use org.pdfbox.pdmodel.common | |
| org.pdfbox.cos | These are the low level objects that make up a PDF document. |
| org.pdfbox.encoding | This package contains the implementations for all of the encodings that are used in PDF documents. |
| org.pdfbox.pdfparser | The pdfparser package contains classes to parse PDF documents and objects within the document. |
| org.pdfbox.pdmodel | The PDModel package represents a high level API for creating and manipulating PDF documents. |
| org.pdfbox.pdmodel.common | High level PD classes that are used throughout several packages are placed in the PDModel common package. |
| org.pdfbox.pdmodel.common.filespecification | The file specification package defines classes that are used for the PDF File Specification logic. |
| org.pdfbox.pdmodel.common.function | This package contains functions that are available in the PDF specification. |
| org.pdfbox.pdmodel.documentinterchange.logicalstructure | The logical structure package provides a mechanism for incorporating structural information about a document's content into a PDF file. |
| org.pdfbox.pdmodel.documentinterchange.prepress | This package contains classes for prepress support in PDFBox. |
| org.pdfbox.pdmodel.fdf | The fdf package will handle all of the logic used for FDF objects inside of the PDF/FDF document. |
| org.pdfbox.pdmodel.font | Classes to deal with font functionality in a PDF Document. |
| org.pdfbox.pdmodel.graphics | The PDModel graphics package deals with graphics states, operations, and parameters within the PDF document. |
| org.pdfbox.pdmodel.graphics.color | This package deals with colors that are stored in a PDF document. |
| org.pdfbox.pdmodel.graphics.xobject | This package deals with images that are stored in a PDF document. |
| org.pdfbox.pdmodel.interactive.action | This package represents actions that can be performed in a PDF document. |
| org.pdfbox.pdmodel.interactive.action.type | This package contains all of the available PDF action types. |
| org.pdfbox.pdmodel.interactive.annotation | The annotation package contains classes that work with PDF annotation elements. |
| org.pdfbox.pdmodel.interactive.digitalsignature | The digitial signature library will manage signatures that are stored in the PDF document. |
| org.pdfbox.pdmodel.interactive.documentnavigation.destination | The destination package allows destinations into a pdf document to be specified. |
| org.pdfbox.pdmodel.interactive.documentnavigation.outline | The outline package allows for a PDF outline(bookmarks) to be created. |
| org.pdfbox.pdmodel.interactive.form | The interactive package contains classes that deal with interactive annotations such as textfields and buttons. |
| org.pdfbox.pdmodel.interactive.pagenavigation | A package to allow provide access to PDF page navigation functionality. |
| org.pdfbox.pdmodel.interactive.viewerpreferences | A package to allow access to document viewing preferences. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.cos | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.encoding | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdfparser | |
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDDestinationOrAction
This is an interface used for some elements such as the document OpenAction that can be either a Destination or an Action. |
|
| PDMetadata
This class represents metadata for various objects in a PDF document. |
|
| PDNameTreeNode
This class represends a PDF Name tree. |
|
| PDRectangle
This represents a rectangle in a PDF document. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.common | |
| COSDictionaryMap
This is a Map that will automatically sync the contents to a COSDictionary. |
|
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| DualCOSObjectable
This is an interface to represent a PDModel object that holds two COS objects. |
|
| PDMetadata
This class represents metadata for various objects in a PDF document. |
|
| PDNameTreeNode
This class represends a PDF Name tree. |
|
| PDObjectStream
A PDStream represents a stream in a PDF document. |
|
| PDRectangle
This represents a rectangle in a PDF document. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
|
| PDTextStream
A PDTextStream class is used when the PDF specification supports either a string or a stream for the value of an object. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.common.filespecification | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.common.function | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDRange
This class will be used to signify a range. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.documentinterchange.logicalstructure | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.documentinterchange.prepress | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.fdf | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDRange
This class will be used to signify a range. |
|
| PDTextStream
A PDTextStream class is used when the PDF specification supports either a string or a stream for the value of an object. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.font | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDMatrix
This class will be used for matrix manipulation. |
|
| PDRectangle
This represents a rectangle in a PDF document. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.graphics | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.graphics.color | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDMatrix
This class will be used for matrix manipulation. |
|
| PDRange
This class will be used to signify a range. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.graphics.xobject | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDMetadata
This class represents metadata for various objects in a PDF document. |
|
| PDStream
A PDStream represents a stream in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.action | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.action.type | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDDestinationOrAction
This is an interface used for some elements such as the document OpenAction that can be either a Destination or an Action. |
|
| PDTextStream
A PDTextStream class is used when the PDF specification supports either a string or a stream for the value of an object. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.annotation | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDRectangle
This represents a rectangle in a PDF document. |
|
| PDTextStream
A PDTextStream class is used when the PDF specification supports either a string or a stream for the value of an object. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.digitalsignature | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.documentnavigation.destination | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDDestinationOrAction
This is an interface used for some elements such as the document OpenAction that can be either a Destination or an Action. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.documentnavigation.outline | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.form | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.pagenavigation | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
| PDRectangle
This represents a rectangle in a PDF document. |
| Classes in org.pdfbox.pdmodel.common used by org.pdfbox.pdmodel.interactive.viewerpreferences | |
| COSObjectable
This is an interface used to get/create the underlying COSObject. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES |


{% extends "base/content.html" %} {% block scripts %} {%- endblock %} {%- block pagenav %} {% if editable %}
You aren't quite done, though. Read through your listing, add some flair, and publish it!
Before you publish it, you should at least edit your description.


May 29, 2020
1 min read
This post is aimed to share someone's experience of getting a job in the hope of helping other fellow students.
Hi guys, Harvard has an open position. Anyone interested?


CallState
public enum CallState
CallState
represents the state of the call
-
New call has been created in the client.
Declaration
Swift
case NEW
-
The outbound call is being sent to the server.
Declaration
Swift
case CONNECTING
-
Call is pending to be answered. Someone is attempting to call you.
Declaration
Swift
case RINGING
-
Call is active when two clients are fully connected.
Declaration
Swift
case ACTIVE
-
Call has been held.
Declaration
Swift
case HELD
-
Call has ended.
Declaration
Swift
case DONE


Welcome!
The Office of Lorem Ipsum is a completely fake department dedicated to helping people learn about developing mobile websites.
The Office of Lorem Ipsum is a completely fake department dedicated to helping people learn about developing mobile websites.


Criando um novo tema
Aprenda como criar um novo tema no Hugo
Introdução
Neste tutorial irei mostrar como criar um simples tema para o Hugo. Assumo que você esteja familiarizado com HTML, linha de comando bash e sinta-se confortável usando Markdown para formatar o conteúdo. Eu vou explicar como o Hugo utiliza templates e como você pode organizar seus templates para criar um tema. Não irei abordar como utilizar CSS para estilizar o seu tema.
Iniciaremos com a criação de um novo site com um template básico. Então iremos adicionar algumas páginas e posts. Com pequenas variaçoes, você será capaz de criar vários tipos diferentes de sites.
Neste tutorial, os comandos que você utilizará irão começar com “$”. A saída aparecerá na linha seguinte. Linhas que iniciam com “#” são comentários que eu adicionei para explicar aquele ponto. Quando eu mostrar atualizações em um arquivo, o “:wq” na última linha indica para salvar o arquivo.
Aqui um exemplo:
## isto é um comentário
$ echo isto eh um comando
isto eh um comando
## editando o arquivo
$vi foo.md
+++
date = "2014-09-28"
title = "criando um novo tema"
+++
bah and humbug
:wq
## exibindo-o
$ cat foo.md
+++
date = "2014-09-28"
title = "criadno um novo tema"
+++
bah and humbug
$
Algumas definições
Existem alguns conceitos que você deve entender antes de criar um tema.
Skins
Skins são responsáveis pela aparência do seu site. É o CSS que controla cores e fontes, é o Javascript que determina as ações e reações. E também algumas regras que o Hugo utiliza para transformar o seu conteúdo no HTML que será exibido aos visitantes do site.
Você tem duas maneiras de criar uma skin. A mais simples é criar no diretório layouts/
. Se for assim, você não precisa se preocupar em configurar o Hugo para reconhecê-las. O primeiro lugar que o Hugo irá procurar pelas regras e arquivos é no diretório layouts/
e então irá encontrar a skin.
Sua segunda opção é criar um sub-diretório dentro do themes/
diretório. Se for assim, então você deve informar ao Hugo onde encontrar a skin. É um trabalho extra, então, por que se preocupar com isso?
A diferença entre criar uma skin em layouts/
e criá-la dentro de themes/
é sutil. Uma skin em layouts/
não pode ser customizada sem atualização do template e arquivos estáticos dos quais foram construídos. A skin criada em themes/
, por outro lado, pode ser e facilita para que outras pessoas a utilizem.
O restante deste tutorial irá chamar a skin criada no diretório themes/
de tema.
Note que você pode usar este tutorial para criar uma skin dentro do diretório layouts/
se quiser. A principal diferença será que você não precisará atualizar a configura’˜cao do seu site para usar o tema.
A Home Page
A home page, or landing page, é a primeira página que os visitantes do seu site veem. É o arquivo index.html no diretório raiz do seu site. Já que o Hugo gera os arquivo no diretório public/, nossa home para é public/index.html.
Arquivo de configuração do site
Quando o Hugo executa, ele procura pelo arquivo de configuração que contém as opções que fazem override dos valores default para todo o site. O arquivo utilizado pode ser TOML, YAML ou JSON. Eu prefiro TOML para os meus arquivos de configuração. Se você prefere JSON ou YAML, irá precisar traduzir os meus exemplos. Também irá precisar trocar o nome do arquivo, já que o Hugo utiliza a extensão para determinar como processá-lo.
Hugo traduz os arquivos Markdown para HTML. Por padrão, Hugo espera encontrar arquivos Markdown no diretório content/
e arquivos de template no seu diretório
### Conteúdo
Conteúdo é armazenado em arquivos de text que possuem duas seções. A primeira é a "front matter", que é a meta-informa'˜cao do conteúdo. A segunda contém o Markdown que será convertido para HTML.
#### Front Matter
A front matter é a informação sobre o conteúdo. Assim como o arquivo de configuração
, ela pode ser escrita em TOML, YAML ou JSON. Diferente do arquivo de configuração, Hugo não utiliza a extensão do arquivo para descobrir o formato. Ele procura por marcações para sinalizar o tipo. TOML é cercado por “`+++`”, YAML por “`---`” e JSON fechado por chaves "`{}`". Eu prefiro usar TOML, então você precisará traduzir os meus exemplos se preferir YAML ou JSON.
A informação na front matter é passada para o template antes do conteúdo ser renderizado em HTML.
#### Markdown
Conteúdo é escrito em Markdown o que torna fácil a criação. Hugo executa o conteúdo direto do Markdown para criar o HTML que será escrito no arquivo de saída.
### Arquivos de Template
Hugo utiza arquivos de template para renderizar o conteúdo no HTML. Arquivos de template são a ponte entre o conteúdo e a apresentação. Regras no template definem qual conteúdo será publicado, onde ele será publicado e como será renderizado para o arquivo HTML. O template orienta a apresentação especificando o estilo a ser utilizado.
Há três tipos de template: single, list e partial. Cada tipo pega um pouco do conteúdo como entrada e transforma-o baseado em comandos no template.
Hugo usa seu conhecimento sobre o conteúdo para encontrar o arquivo de template para renderizar o conteúdo. Se ele não encontrar o correspondente, ele troca para um nível acima e busca à partir de lá. Ele irá continuar até encontrar o template ou ficar sem templates para tentar. Caso ele não encontre, irá utilizar template default do site.
Observe que você pode usar a front matter para influenciar a escolha do Hugo por templates.
#### Single Template
Um single template é usado para renderizar um único pedaço de conteúdo. Por exemplo, um artigo ou post podem ser um único pedaço de conteúdo e utilizar um single template.
#### List Template
Uma list template renderiza um grupo de conteúdos relacionados. Pode ser um sumário de posts recentes ou todos os artigos de uma categoria. List templates podem conter múltiplos grupos.
O template da homepage é um tipo especial list template. Hugo assumo que a homepage do seu site irá atuar como um portal para o resto do conteúdo do seu site.
#### Partial Template
Um partial template é um template que pode ser incluído dentro de outro template. Partial templates devem ser chamados utilizando o comando "partial". Eles são muito úteis para criar um comportamento comum. Por exemplo, seu site pode ter um banner que é utilizado por todas as páginas. Ao invés de copiar o texto do banner para cada um dos single e list templates, você pode criar um partial com o banner. Desta forma, se decidir mudar o banner, apenas terá que alterar apenas o partial template.
## Criando um novo site
Vamos usar Hugo para criar um novo site. Eu utilizo o Mac, então irei criar no meu diretório home, na pasta Sites. Se você está usando Linux, talvez tenha que criar a pasta primeiro.
O comando "new site" irá criar o esqueleto do site. Ele fornecerá uma estrutura de diretório básica e arquivos de configuração utilizáveis.
$ hugo new site ~/Sites/zafta $ cd ~/Sites/zafta $ ls -l total 8 drwxr-xr-x 7 quoha staff 238 Sep 29 16:49 . drwxr-xr-x 3 quoha staff 102 Sep 29 16:49 .. drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes -rw-r–r– 1 quoha staff 82 Sep 29 16:49 config.toml drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static $
Olhe o diretório content/ para confirmar que está vazio.
Os outros diretórios (archetypes/, layouts/, and static/) são usados para customização do tema. Este é um tópico para um tutorial diferente, então por favor, ignore-os por enquanto.
### Gerando o HTML do novo site
Executando o comando `hugo` sem opções, irá ler todo o conteúdo disponível e gerar os arquivos HTML. E também copiará todos os arquivos estáticos (tudo aquilo que não é conteúdo). Como temos um site vazio, ele não fará muito, mas será bem rápido.
$ hugo –verbose INFO: 2014/09/29 Using config file: config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] WARN: 2014/09/29 Unable to locate layout: [404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 2 ms $
The "`--verbose`" flag gives extra information that will be helpful when we build the template. Every line of the output that starts with "INFO:" or "WARN:" is present because we used that flag. The lines that start with "WARN:" are warning messages. We'll go over them later.
We can verify that the command worked by looking at the directory again.
$ ls -l total 8 drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes -rw-r–r– 1 quoha staff 82 Sep 29 16:49 config.toml drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static $
See that new public/ directory? Hugo placed all generated content there. When you're ready to publish your web site, that's the place to start. For now, though, let's just confirm that we have what we'd expect from a site with no content.
$ ls -l public total 16 -rw-r–r– 1 quoha staff 416 Sep 29 17:02 index.xml -rw-r–r– 1 quoha staff 262 Sep 29 17:02 sitemap.xml $
Hugo created two XML files, which is standard, but there are no HTML files.
### Test the New Site
Verify that you can run the built-in web server. It will dramatically shorten your development cycle if you do. Start it by running the "server" command. If it is successful, you will see output similar to the following:
$ hugo server –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] WARN: 2014/09/29 Unable to locate layout: [404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 2 ms Serving pages from /Users/quoha/Sites/zafta/public Web Server is available at http://localhost:1313 Press Ctrl+C to stop
Connect to the listed URL (it's on the line that starts with "Web Server"). If everything is working correctly, you should get a page that shows the following:
index.xml sitemap.xml
That's a listing of your public/ directory. Hugo didn't create a home page because our site has no content. When there's no index.html file in a directory, the server lists the files in the directory, which is what you should see in your browser.
Let’s go back and look at those warnings again.
WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] WARN: 2014/09/29 Unable to locate layout: [404.html]
That second warning is easier to explain. We haven’t created a template to be used to generate “page not found errors.” The 404 message is a topic for a separate tutorial.
Now for the first warning. It is for the home page. You can tell because the first layout that it looked for was “index.html.” That’s only used by the home page.
I like that the verbose flag causes Hugo to list the files that it's searching for. For the home page, they are index.html, _default/list.html, and _default/single.html. There are some rules that we'll cover later that explain the names and paths. For now, just remember that Hugo couldn't find a template for the home page and it told you so.
At this point, you've got a working installation and site that we can build upon. All that’s left is to add some content and a theme to display it.
## Create a New Theme
Hugo doesn't ship with a default theme. There are a few available (I counted a dozen when I first installed Hugo) and Hugo comes with a command to create new themes.
We're going to create a new theme called "zafta." Since the goal of this tutorial is to show you how to fill out the files to pull in your content, the theme will not contain any CSS. In other words, ugly but functional.
All themes have opinions on content and layout. For example, Zafta uses "post" over "blog". Strong opinions make for simpler templates but differing opinions make it tougher to use themes. When you build a theme, consider using the terms that other themes do.
### Criando um Esqueleto
Use the hugo "new" command to create the skeleton of a theme. This creates the directory structure and places empty files for you to fill out.
$ hugo new theme zafta
$ ls -l total 8 drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes -rw-r–r– 1 quoha staff 82 Sep 29 16:49 config.toml drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes
$ find themes -type f | xargs ls -l -rw-r–r– 1 quoha staff 1081 Sep 29 17:31 themes/zafta/LICENSE.md -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/archetypes/default.md -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/ list.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/ single.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/index.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/ footer.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/ header.html -rw-r–r– 1 quoha staff 93 Sep 29 17:31 themes/zafta/theme.toml $
The skeleton includes templates (the files ending in .html), license file, a description of your theme (the theme.toml file), and an empty archetype.
Please take a minute to fill out the theme.toml and LICENSE.md files. They're optional, but if you're going to be distributing your theme, it tells the world who to praise (or blame). It's also nice to declare the license so that people will know how they can use the theme.
$ vi themes/zafta/theme.toml author = “michael d henderson” description = “a minimal working template” license = “MIT” name = “zafta” source_repo = “” tags = [“tags”, “categories”] :wq
also edit themes/zafta/LICENSE.md and change
the bit that says “YOUR_NAME_HERE”
Note that the the skeleton's template files are empty. Don't worry, we'll be changing that shortly.
$ find themes/zafta -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/ list.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/ single.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/ index.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/ footer.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/ header.html $
### Update the Configuration File to Use the Theme
Now that we've got a theme to work with, it's a good idea to add the theme name to the configuration file. This is optional, because you can always add "-t zafta" on all your commands. I like to put it the configuration file because I like shorter command lines. If you don't put it in the configuration file or specify it on the command line, you won't use the template that you're expecting to.
Edit the file to add the theme, add a title for the site, and specify that all of our content will use the TOML format.
$ vi config.toml theme = “zafta” baseurl = “” languageCode = “en-us” title = “zafta - totally refreshing” MetaDataFormat = “toml” :wq
$
### Generate the Site
Now that we have an empty theme, let's generate the site again.
$ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 2 ms $
Did you notice that the output is different? The warning message for the home page has disappeared and we have an additional information line saying that Hugo is syncing from the theme's directory.
Let's check the public/ directory to see what Hugo's created.
$ ls -l public total 16 drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 css -rw-r–r– 1 quoha staff 0 Sep 29 17:56 index.html -rw-r–r– 1 quoha staff 407 Sep 29 17:56 index.xml drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 js -rw-r–r– 1 quoha staff 243 Sep 29 17:56 sitemap.xml $
Notice four things:
1. Hugo created a home page. This is the file public/index.html.
2. Hugo created a css/ directory.
3. Hugo created a js/ directory.
4. Hugo claimed that it created 0 pages. It created a file and copied over static files, but didn't create any pages. That's because it considers a "page" to be a file created directly from a content file. It doesn't count things like the index.html files that it creates automatically.
#### The Home Page
Hugo supports many different types of templates. The home page is special because it gets its own type of template and its own template file. The file, layouts/index.html, is used to generate the HTML for the home page. The Hugo documentation says that this is the only required template, but that depends. Hugo's warning message shows that it looks for three different templates:
WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html]
If it can't find any of these, it completely skips creating the home page. We noticed that when we built the site without having a theme installed.
When Hugo created our theme, it created an empty home page template. Now, when we build the site, Hugo finds the template and uses it to generate the HTML for the home page. Since the template file is empty, the HTML file is empty, too. If the template had any rules in it, then Hugo would have used them to generate the home page.
$ find . -name index.html | xargs ls -l -rw-r–r– 1 quoha staff 0 Sep 29 20:21 ./public/index.html -rw-r–r– 1 quoha staff 0 Sep 29 17:31 ./themes/zafta/layouts/index.html $
#### The Magic of Static
Hugo does two things when generating the site. It uses templates to transform content into HTML and it copies static files into the site. Unlike content, static files are not transformed. They are copied exactly as they are.
Hugo assumes that your site will use both CSS and JavaScript, so it creates directories in your theme to hold them. Remember opinions? Well, Hugo's opinion is that you'll store your CSS in a directory named css/ and your JavaScript in a directory named js/. If you don't like that, you can change the directory names in your theme directory or even delete them completely. Hugo's nice enough to offer its opinion, then behave nicely if you disagree.
$ find themes/zafta -type d | xargs ls -ld drwxr-xr-x 7 quoha staff 238 Sep 29 17:38 themes/zafta drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes/zafta/archetypes drwxr-xr-x 5 quoha staff 170 Sep 29 17:31 themes/zafta/layouts drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/_default drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/partials drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/static drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/css drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/js $
## The Theme Development Cycle
When you're working on a theme, you will make changes in the theme's directory, rebuild the site, and check your changes in the browser. Hugo makes this very easy:
1. Purge the public/ directory.
2. Run the built in web server in watch mode.
3. Open your site in a browser.
4. Update the theme.
5. Glance at your browser window to see changes.
6. Return to step 4.
I’ll throw in one more opinion: never work on a theme on a live site. Always work on a copy of your site. Make changes to your theme, test them, then copy them up to your site. For added safety, use a tool like Git to keep a revision history of your content and your theme. Believe me when I say that it is too easy to lose both your mind and your changes.
Check the main Hugo site for information on using Git with Hugo.
### Purge the public/ Directory
When generating the site, Hugo will create new files and update existing ones in the ```public/``` directory. It will not delete files that are no longer used. For example, files that were created in the wrong directory or with the wrong title will remain. If you leave them, you might get confused by them later. I recommend cleaning out your site prior to generating it.
Note: If you're building on an SSD, you should ignore this. Churning on a SSD can be costly.
### Hugo's Watch Option
Hugo's "`--watch`" option will monitor the content/ and your theme directories for changes and rebuild the site automatically.
### Live Reload
Hugo's built in web server supports live reload. As pages are saved on the server, the browser is told to refresh the page. Usually, this happens faster than you can say, "Wow, that's totally amazing."
### Development Commands
Use the following commands as the basis for your workflow.
purge old files. hugo will recreate the public directory.
## $ rm -rf public ##
run hugo in watch mode
## $ hugo server –watch –verbose
Here's sample output showing Hugo detecting a change to the template for the home page. Once generated, the web browser automatically reloaded the page. I've said this before, it's amazing.
$ rm -rf public $ hugo server –watch –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 2 ms Watching for changes in /Users/quoha/Sites/zafta/content Serving pages from /Users/quoha/Sites/zafta/public Web Server is available at http://localhost:1313 Press Ctrl+C to stop INFO: 2014/09/29 File System Event: [“/Users/quoha/Sites/zafta/themes/zafta/ layouts/index.html”: MODIFY|ATTRIB] Change detected, rebuilding site
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 1 ms
## Update the Home Page Template
The home page is one of a few special pages that Hugo creates automatically. As mentioned earlier, it looks for one of three files in the theme's layout/ directory:
1. index.html
2. _default/list.html
3. _default/single.html
We could update one of the default templates, but a good design decision is to update the most specific template available. That's not a hard and fast rule (in fact, we'll break it a few times in this tutorial), but it is a good generalization.
### Make a Static Home Page
Right now, that page is empty because we don't have any content and we don't have any logic in the template. Let's change that by adding some text to the template.
$ vi themes/zafta/layouts/index.html <!DOCTYPE html>
hugo says hello!
:wq$
Build the web site and then verify the results.
$ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 0 pages created 0 tags created 0 categories created in 2 ms
$ find public -type f -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 78 Sep 29 21:26 public/index.html
$ cat public/index.html <!DOCTYPE html>
hugo says hello!
#### Live Reload
Note: If you're running the server with the `--watch` option, you'll see different content in the file:
$ cat public/index.html <!DOCTYPE html>
hugo says hello!
When you use `--watch`, the Live Reload script is added by Hugo. Look for live reload in the documentation to see what it does and how to disable it.
### Build a "Dynamic" Home Page
"Dynamic home page?" Hugo's a static web site generator, so this seems an odd thing to say. I mean let's have the home page automatically reflect the content in the site every time Hugo builds it. We'll use iteration in the template to do that.
#### Create New Posts
Now that we have the home page generating static content, let's add some content to the site. We'll display these posts as a list on the home page and on their own page, too.
Hugo has a command to generate a skeleton post, just like it does for sites and themes.
$ hugo –verbose new post/first.md
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 attempting to create post/first.md of post
INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/
default.md
ERROR: 2014/09/29 Unable to Cast
$
That wasn't very nice, was it?
The "new" command uses an archetype to create the post file. Hugo created an empty default archetype file, but that causes an error when there's a theme. For me, the workaround was to create an archetypes file specifically for the post type.
$ vi themes/zafta/archetypes/post.md +++ Description = “” Tags = [] Categories = [] +++ :wq
$ find themes/zafta/archetypes -type f | xargs ls -l -rw-r–r– 1 quoha staff 0 Sep 29 21:53 themes/zafta/archetypes/default.md -rw-r–r– 1 quoha staff 51 Sep 29 21:54 themes/zafta/archetypes/post.md
$ hugo –verbose new post/first.md INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 attempting to create post/first.md of post INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/ post.md INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/first.md /Users/quoha/Sites/zafta/content/post/first.md created
$ hugo –verbose new post/second.md INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 attempting to create post/second.md of post INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/ post.md INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/second.md /Users/quoha/Sites/zafta/content/post/second.md created
$ ls -l content/post total 16 -rw-r–r– 1 quoha staff 104 Sep 29 21:54 first.md -rw-r–r– 1 quoha staff 105 Sep 29 21:57 second.md
$ cat content/post/first.md +++ Categories = [] Description = “” Tags = [] date = “2014-09-29T21:54:53-05:00” title = “first”
+++ my first post
$ cat content/post/second.md +++ Categories = [] Description = “” Tags = [] date = “2014-09-29T21:57:09-05:00” title = “second”
+++ my second post
$
Build the web site and then verify the results.
$ rm -rf public $ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 found taxonomies: map[string]string{“category”:“categories”, “tag”:“tags”} WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 2 pages created 0 tags created 0 categories created in 4 ms $
The output says that it created 2 pages. Those are our new posts:
$ find public -type f -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 78 Sep 29 22:13 public/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:13 public/post/first/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:13 public/post/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:13 public/post/second/index.html $
The new files are empty because because the templates used to generate the content are empty. The homepage doesn't show the new content, either. We have to update the templates to add the posts.
### List and Single Templates
In Hugo, we have three major kinds of templates. There's the home page template that we updated previously. It is used only by the home page. We also have "single" templates which are used to generate output for a single content file. We also have "list" templates that are used to group multiple pieces of content before generating output.
Generally speaking, list templates are named "list.html" and single templates are named "single.html."
There are three other types of templates: partials, content views, and terms. We will not go into much detail on these.
### Add Content to the Homepage
The home page will contain a list of posts. Let's update its template to add the posts that we just created. The logic in the template will run every time we build the site.
$ vi themes/zafta/layouts/index.html <!DOCTYPE html>
{{ range first 10 .Data.Pages }}{{ .Title }}
{{ end }} :wq$
Hugo uses the Go template engine. That engine scans the template files for commands which are enclosed between "{{" and "}}". In our template, the commands are:
1. range
2. .Title
3. end
The "range" command is an iterator. We're going to use it to go through the first ten pages. Every HTML file that Hugo creates is treated as a page, so looping through the list of pages will look at every file that will be created.
The ".Title" command prints the value of the "title" variable. Hugo pulls it from the front matter in the Markdown file.
The "end" command signals the end of the range iterator. The engine loops back to the top of the iteration when it finds "end." Everything between the "range" and "end" is evaluated every time the engine goes through the iteration. In this file, that would cause the title from the first ten pages to be output as heading level one.
It's helpful to remember that some variables, like .Data, are created before any output files. Hugo loads every content file into the variable and then gives the template a chance to process before creating the HTML files.
Build the web site and then verify the results.
$ rm -rf public $ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 found taxonomies: map[string]string{“tag”:“tags”, “category”:“categories”} WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 2 pages created 0 tags created 0 categories created in 4 ms $ find public -type f -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 94 Sep 29 22:23 public/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:23 public/post/first/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:23 public/post/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:23 public/post/second/index.html $ cat public/index.html <!DOCTYPE html>
<h1>second</h1>
<h1>first</h1>
$
Congratulations, the home page shows the title of the two posts. The posts themselves are still empty, but let's take a moment to appreciate what we've done. Your template now generates output dynamically. Believe it or not, by inserting the range command inside of those curly braces, you've learned everything you need to know to build a theme. All that's really left is understanding which template will be used to generate each content file and becoming familiar with the commands for the template engine.
And, if that were entirely true, this tutorial would be much shorter. There are a few things to know that will make creating a new template much easier. Don't worry, though, that's all to come.
### Add Content to the Posts
We're working with posts, which are in the content/post/ directory. That means that their section is "post" (and if we don't do something weird, their type is also "post").
Hugo uses the section and type to find the template file for every piece of content. Hugo will first look for a template file that matches the section or type name. If it can't find one, then it will look in the _default/ directory. There are some twists that we'll cover when we get to categories and tags, but for now we can assume that Hugo will try post/single.html, then _default/single.html.
Now that we know the search rule, let's see what we actually have available:
$ find themes/zafta -name single.html | xargs ls -l -rw-r–r– 1 quoha staff 132 Sep 29 17:31 themes/zafta/layouts/_default/ single.html
We could create a new template, post/single.html, or change the default. Since we don't know of any other content types, let's start with updating the default.
Remember, any content that we haven't created a template for will end up using this template. That can be good or bad. Bad because I know that we're going to be adding different types of content and we're going to end up undoing some of the changes we've made. It's good because we'll be able to see immediate results. It's also good to start here because we can start to build the basic layout for the site. As we add more content types, we'll refactor this file and move logic around. Hugo makes that fairly painless, so we'll accept the cost and proceed.
Please see the Hugo documentation on template rendering for all the details on determining which template to use. And, as the docs mention, if you're building a single page application (SPA) web site, you can delete all of the other templates and work with just the default single page. That's a refreshing amount of joy right there.
#### Update the Template File
$ vi themes/zafta/layouts/_default/single.html <!DOCTYPE html>
{{ .Title }}
{{ .Content }} :wq$
Build the web site and verify the results.
$ rm -rf public $ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 found taxonomies: map[string]string{“tag”:“tags”, “category”:“categories”} WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 2 pages created 0 tags created 0 categories created in 4 ms
$ find public -type f -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 94 Sep 29 22:40 public/index.html -rw-r–r– 1 quoha staff 125 Sep 29 22:40 public/post/first/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:40 public/post/index.html -rw-r–r– 1 quoha staff 128 Sep 29 22:40 public/post/second/index.html
$ cat public/post/first/index.html <!DOCTYPE html>
first
my first post
$ cat public/post/second/index.html <!DOCTYPE html>
second
my second post
$
Notice that the posts now have content. You can go to localhost:1313/post/first to verify.
### Linking to Content
The posts are on the home page. Let's add a link from there to the post. Since this is the home page, we'll update its template.
$ vi themes/zafta/layouts/index.html <!DOCTYPE html>
{{ range first 10 .Data.Pages }}{{ .Title }}
{{ end }}
Build the web site and verify the results.
$ rm -rf public $ hugo –verbose INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ INFO: 2014/09/29 found taxonomies: map[string]string{“tag”:“tags”, “category”:“categories”} WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] 0 draft content 0 future content 2 pages created 0 tags created 0 categories created in 4 ms
$ find public -type f -name ‘*.html’ | xargs ls -l -rw-r–r– 1 quoha staff 149 Sep 29 22:44 public/index.html -rw-r–r– 1 quoha staff 125 Sep 29 22:44 public/post/first/index.html -rw-r–r– 1 quoha staff 0 Sep 29 22:44 public/post/index.html -rw-r–r– 1 quoha staff 128 Sep 29 22:44 public/post/second/index.html
$ cat public/index.html <!DOCTYPE html>
<h1><a href="/post/second/">second</a></h1>
<h1><a href="/post/first/">first</a></h1>
$
### Create a Post Listing
We have the posts displaying on the home page and on their own page. We also have a file public/post/index.html that is empty. Let's make it show a list of all posts (not just the first ten).
We need to decide which template to update. This will be a listing, so it should be a list template. Let's take a quick look and see which list templates are available.
$ find themes/zafta -name list.html | xargs ls -l -rw-r–r– 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/ list.html
As with the single post, we have to decide to update _default/list.html or create post/list.html. We still don't have multiple content types, so let's stay consistent and update the default list template.
## Creating Top Level Pages
Let's add an "about" page and display it at the top level (as opposed to a sub-level like we did with posts).
The default in Hugo is to use the directory structure of the content/ directory to guide the location of the generated html in the public/ directory. Let's verify that by creating an "about" page at the top level:
$ vi content/about.md +++ title = “about” description = “about this site” date = “2014-09-27” slug = “about time” +++
about us
i’m speechless :wq
Generate the web site and verify the results.
$ find public -name ‘*.html’ | xargs ls -l -rw-rw-r– 1 mdhender staff 334 Sep 27 15:08 public/about-time/index.html -rw-rw-r– 1 mdhender staff 527 Sep 27 15:08 public/index.html -rw-rw-r– 1 mdhender staff 358 Sep 27 15:08 public/post/first-post/ index.html -rw-rw-r– 1 mdhender staff 0 Sep 27 15:08 public/post/index.html -rw-rw-r– 1 mdhender staff 342 Sep 27 15:08 public/post/second-post/ index.html
Notice that the page wasn't created at the top level. It was created in a sub-directory named 'about-time/'. That name came from our slug. Hugo will use the slug to name the generated content. It's a reasonable default, by the way, but we can learn a few things by fighting it for this file.
One other thing. Take a look at the home page.
$ cat public/index.html <!DOCTYPE html>
creating a new theme
about
second
first
Notice that the "about" link is listed with the posts? That's not desirable, so let's change that first.
$ vi themes/zafta/layouts/index.html <!DOCTYPE html>
posts
{{ range first 10 .Data.Pages }} {{ if eq .Type “post”}}{{ .Title }}
{{ end }} {{ end }}pages
{{ range .Data.Pages }} {{ if eq .Type “page” }}{{ .Title }}
{{ end }} {{ end }} :wq
Generate the web site and verify the results. The home page has two sections, posts and pages, and each section has the right set of headings and links in it.
But, that about page still renders to about-time/index.html.
$ find public -name ‘*.html’ | xargs ls -l -rw-rw-r– 1 mdhender staff 334 Sep 27 15:33 public/about-time/index.html -rw-rw-r– 1 mdhender staff 645 Sep 27 15:33 public/index.html -rw-rw-r– 1 mdhender staff 358 Sep 27 15:33 public/post/first-post/ index.html -rw-rw-r– 1 mdhender staff 0 Sep 27 15:33 public/post/index.html -rw-rw-r– 1 mdhender staff 342 Sep 27 15:33 public/post/second-post/ index.html
Knowing that hugo is using the slug to generate the file name, the simplest solution is to change the slug. Let's do it the hard way and change the permalink in the configuration file.
$ vi config.toml [permalinks] page = “/:title/” about = “/:filename/”
Generate the web site and verify that this didn't work. Hugo lets "slug" or "URL" override the permalinks setting in the configuration file. Go ahead and comment out the slug in content/about.md, then generate the web site to get it to be created in the right place.
## Sharing Templates
If you've been following along, you probably noticed that posts have titles in the browser and the home page doesn't. That's because we didn't put the title in the home page's template (layouts/index.html). That's an easy thing to do, but let's look at a different option.
We can put the common bits into a shared template that's stored in the themes/zafta/layouts/partials/ directory.
### Create the Header and Footer Partials
In Hugo, a partial is a sugar-coated template. Normally a template reference has a path specified. Partials are different. Hugo searches for them along a TODO defined search path. This makes it easier for end-users to override the theme's presentation.
$ vi themes/zafta/layouts/partials/header.html <!DOCTYPE html>
$ vi themes/zafta/layouts/partials/footer.html :wq
### Update the Home Page Template to Use the Partials
The most noticeable difference between a template call and a partials call is the lack of path:
{{ template “theme/partials/header.html” . }}
versus
{{ partial “header.html” . }}
Both pass in the context.
Let's change the home page template to use these new partials.
$ vi themes/zafta/layouts/index.html {{ partial “header.html” . }}
posts
{{ range first 10 .Data.Pages }} {{ if eq .Type “post”}}{{ .Title }}
{{ end }} {{ end }}pages
{{ range .Data.Pages }} {{ if or (eq .Type “page”) (eq .Type “about”) }}{{ .Type }} - {{ .Title }} - {{ .RelPermalink }}
{{ end }} {{ end }}{{ partial “footer.html” . }} :wq
Generate the web site and verify the results. The title on the home page is now "your title here", which comes from the "title" variable in the config.toml file.
### Update the Default Single Template to Use the Partials
$ vi themes/zafta/layouts/_default/single.html {{ partial “header.html” . }}
{{ .Title }}
{{ .Content }}{{ partial “footer.html” . }} :wq
Generate the web site and verify the results. The title on the posts and the about page should both reflect the value in the markdown file.
## Add “Date Published” to Posts
It's common to have posts display the date that they were written or published, so let's add that. The front matter of our posts has a variable named "date." It's usually the date the content was created, but let's pretend that's the value we want to display.
### Add “Date Published” to the Template
We'll start by updating the template used to render the posts. The template code will look like:
{{ .Date.Format “Mon, Jan 2, 2006” }}
Posts use the default single template, so we'll change that file.
$ vi themes/zafta/layouts/_default/single.html {{ partial “header.html” . }}
{{ .Title }}
{{ .Date.Format “Mon, Jan 2, 2006” }}
{{ .Content }}{{ partial “footer.html” . }} :wq
Generate the web site and verify the results. The posts now have the date displayed in them. There's a problem, though. The "about" page also has the date displayed.
As usual, there are a couple of ways to make the date display only on posts. We could do an "if" statement like we did on the home page. Another way would be to create a separate template for posts.
The "if" solution works for sites that have just a couple of content types. It aligns with the principle of "code for today," too.
Let's assume, though, that we've made our site so complex that we feel we have to create a new template type. In Hugo-speak, we're going to create a section template.
Let's restore the default single template before we forget.
$ mkdir themes/zafta/layouts/post $ vi themes/zafta/layouts/_default/single.html {{ partial “header.html” . }}
{{ .Title }}
{{ .Content }}{{ partial “footer.html” . }} :wq
Now we'll update the post's version of the single template. If you remember Hugo's rules, the template engine will use this version over the default.
$ vi themes/zafta/layouts/post/single.html {{ partial “header.html” . }}
{{ .Title }}
{{ .Date.Format “Mon, Jan 2, 2006” }}
{{ .Content }}{{ partial “footer.html” . }} :wq
```
Note that we removed the date logic from the default template and put it in the post template. Generate the web site and verify the results. Posts have dates and the about page doesn’t.
Don’t Repeat Yourself ( Não repita você mesmo)
DRY é um bom design e o Hugo faz um grande trabalho para apoiá-lo. Parte da arte de um bom template é saber quando adicionar um novo template e quanto atualizar um já existente. Enquanto você estiver descobrindo isto, aceite que algumas vezes precisará refatorá-lo. Hugo permite isto de maneira fácil e rápida, então não tem problema atrasos na divisão do seu template.


We're a collective of highly skilled software and systems architects, user interface designers and all around crafty problem solvers.
Reach us at<EMAIL_ADDRESS>We're a collective of highly skilled software and systems architects, user interface designers and all around crafty problem solvers.
Reach us at hello@twobit.solutions


S
tart Game
H
igh Scores
C
ontrols
Game Over
Your name:
Ok
N
ew Game
High Scores
No scores available
R
estore
B
ack
Controls
Use the arrows or WASD keys to move the blob.
Space or P will pause the game.
M will trigger the sound on or off.
Use the links or keys (underline letters) to navigate throught the screens.
B
ack


Preparation time
less than 30 mins
Cooking time
30 mins to 1 hour
Serves
Serves 8
Hemsley and Hemsley’s lovely savoury tart uses homemade gluten-free pastry and a rich filling. Delicious with a green leafy salad.
Each slice provides 465 kcal, 20g protein, 5.5g carbohydrate (of which 4.5g sugars), 40g fat (of which 7g saturates), 0.5g fibre and 1.6g salt.
Preheat the oven to 200C/180C Fan/Gas 6. Grease a 24cm/10in tart case with butter.
Pulse all of the pastry ingredients except the eggs in a food processor until it resembles breadcrumbs, then add the eggs. Pulse again until the mixture starts to come together as a dough, then press the dough into a smooth ball, wrap in cling film and chill in the fridge for 10 minutes.
Turn the dough out into the prepared tart tin. Use the palm of your hand to squash the dough evenly over the base of the tin, then spread and smooth it into the edges and sides of the tin using your fingers. Trim away any excess using a sharp knife, then line this pastry case with a sheet of greaseproof paper and fill with baking beans. Return to the fridge for 20 minutes.
Blind bake the pastry case for 10 minutes, then remove the baking beans and greaseproof paper and bake for a further 8-10 minutes, or until pale golden-brown.
Meanwhile, for the filling, beat together the yoghurt and eggs until well combined. Stir in the parsley and lemon zest, and season with plenty of pepper and a little salt. Set aside.
When the pastry case is cooked, reduce the oven temperature to 190C/170C Fan/Gas 5.
Arrange the spring onions in an even layer in the bottom of the pastry case. Arrange a layer of spinach on top, then place the chunks of mackerel onto the spinach leaves.
Carefully pour over the yoghurt-and-egg mixture and dot the surface of the tart with the cherry tomato halves (cut-sides facing upwards).
Bake for 25-30 minutes, or until the filling has set and the top has turned golden-brown. Serve warm or at room temperature, with a side salad of simply dressed watercress leaves.


Dedicated and passionate, with strong analytical skills and a serious work ethic. Bringing forth excellent technical skills and the drive to bring complex projects to completion.( Download my resume by clicking on the file button )
Implemented a version of John Conway's Game of Life using JavaScript. It is a zero-player game and is Turing complete. Thus, it can simulate a universal constructor or any other Turing machine.
Made an Interactive demo of the A* algorithm using C++. The demo demonstrates how the algorithm works by gradually coloring in the squares on the grid to show how the path is being created
Developed a new platform to help the user find accommodation in a new area/locality using Django and MySQL
R&D project aiming to train the data models and find the sentiment hidden in the review; thereby, analyze and compare the performance metrics using Python.
Issued by EC Council
Issued by ICSI UK
Literature, Creative Writing, gastronomy
I am also interested in solving CTFs and Blockchain