text:
Vi Cheat Sheet
==============

\

-   [Modes](#mode)
-   [Quitting](#quit)
-   [Inserting Text](#insert)
-   [Motion](#motion)
-   [Deleting Text](#delete)
-   [Yanking](#yank)
-   [Changing Text](#change)
-   [Putting Text](#put)
-   [Buffers](#buffer)

<!-- -->

-   [Markers](#mark)
-   [Searching](#search)
-   [Replacing Text](#replace)
-   [Regular Expressions](#re)
-   [Counts](#count)
-   [Ranges](#range)
-   [Files](#file)
-   [Other](#other)

\
[Click here](http://www.lagmonster.org/docs/vi2.html) for the Advanced
VI Cheatsheet

------------------------------------------------------------------------

[]()

Modes
-----

------------------------------------------------------------------------

Vi has two modes insertion mode and command mode. The editor begins in
command mode, where the cursor movement and text deletion and pasting
occur. Insertion mode begins upon entering an insertion or change
command. \[ESC\] returns the editor to command mode (where you can quit,
for example by typing :q!). Most commands execute as soon as you type
them except for "colon" commands which execute when you press the ruturn
key.

\
\
\
[]()

Quitting
--------

------------------------------------------------------------------------

  ----- ---------------------------------------------
  :x    Exit, saving changes
  :q    Exit as long as there have been no changes
  ZZ    Exit and save changes if any have been made
  :q!   Exit and ignore any changes
  ----- ---------------------------------------------

\
\
\
[]()

Inserting Text
--------------

------------------------------------------------------------------------

i

Insert before cursor

I

Insert before line

a

Append after cursor

A

Append after line

o

Open a new line after current line

O

Open a new line before current line

r

Replace one character

R

Replace many characters

\
\
\
[]()

Motion
------

------------------------------------------------------------------------

  ---- ----------------------------------------------
  h    Move left
  j    Move down
  k    Move up
  l    Move right
  w    Move to next word
  W    Move to next blank delimited word
  b    Move to the beginning of the word
  B    Move to the beginning of blank delimted word
  e    Move to the end of the word
  E    Move to the end of Blank delimited word
  (    Move a sentence back
  )    Move a sentence forward
  {    Move a paragraph back
  }    Move a paragraph forward
  0    Move to the begining of the line
  \$   Move to the end of the line
  1G   Move to the first line of the file
  G    Move to the last line of the file
  nG   Move to nth line of the file
  :n   Move to nth line of the file
  fc   Move forward to c
  Fc   Move back to c
  H    Move to top of screen
  M    Move to middle of screen
  L    Move to botton of screen
  %    Move to associated ( ), { }, \[ \]
  ---- ----------------------------------------------

\
\
\
[]()

Deleting Text
-------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------
  Almost all deletion commands are performed by typing d followed by a motion. For example, dw deletes a word. A few other deletes are:
  ---------------------------------------------------------------------------------------------------------------------------------------

  ---- -----------------------------------------
  x    Delete character to the right of cursor
  X    Delete character to the left of cursor
  D    Delete to the end of the line
  dd   Delete current line
  :d   Delete current line
  ---- -----------------------------------------

\
\
\
[]()

Yanking Text
------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Like deletion, almost all yank commands are performed by typing y followed by a motion. For example, y\$ yanks to the end of the line. Two other yank commands are:
  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------

  ---- -----------------------
  yy   Yank the current line
  :y   Yank the current line
  ---- -----------------------

\
\
\
[]()

Changing text
-------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  The change command is a deletion command that leaves the editor in insert mode. It is performed by typing c followed by a motion. For wxample cw changes a word. A few other change commands are:
  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  ---- -------------------------------
  C    Change to the end of the line
  cc   Change the whole line
  ---- -------------------------------

\
\
\
[]()

Putting text
------------

------------------------------------------------------------------------

  --- -------------------------------------------
  p   Put after the position or after the line
  P   Put before the poition or before the line
  --- -------------------------------------------

\
\
\
[]()

Buffers
-------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Named buffers may be specified before any deletion, change, yank or put command. The general prefix has the form "c where c is any lowercase character. for example, "adw deletes a word into buffer a. It may thereafter be put back into text with an appropriate "ap.
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

\
\
\
[]()

Markers
-------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------
  Named markers may be set on any line in a file. Any lower case letter may be a marker name. Markers may also be used as limits for ranges.
  --------------------------------------------------------------------------------------------------------------------------------------------

  ----- ---------------------------------------------------
  mc    Set marker c on this line
  \`c   Go to beginning of marker c line.
  'c    Go to first non-blank character of marker c line.
  ----- ---------------------------------------------------

\
\
\
[]()

Search for strings
------------------

------------------------------------------------------------------------

  ----------- ------------------------------------------
  /*string*   Search forward for *string*
  ?*string*   Search back for *string*
  n           Search for next instance of *string*
  N           Search for previous instance of *string*
  ----------- ------------------------------------------

\
\
\
[]()

Replace
-------

------------------------------------------------------------------------

  ------------------------------------------------------------------------------------------------------------------------------------------------
  The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).
  ------------------------------------------------------------------------------------------------------------------------------------------------

  ------------------------------- -------------------------------------------------------
  :s/*pattern*/*string*/*flags*   Replace *pattern* with *string* according to *flags*.
  g                               Flag - Replace all occurences of pattern
  c                               Flag - Confirm replaces.
  &                               Repeat last :s command
  ------------------------------- -------------------------------------------------------

\
\
\
[]()

Regular Expressions
-------------------

------------------------------------------------------------------------

  ----------- -----------------------------------------------
  . (dot)     Any single character except newline
  \*          zero or more occurances of any character
  \[...\]     Any single character specified in the set
  \[\^...\]   Any single character not specified in the set
  \^          Anchor - beginning of the line
  \$          Anchor - end of line
  \\<      Anchor - begining of word
  \\>      Anchor - end of word
  \\(...\\)   Grouping - usually used to group conditions
  \\n         Contents of nth grouping
  ----------- -----------------------------------------------

\

  ------------------- -----------------------------------------------------------------------------------
  \[A-Z\]             The SET from Capital A to Capital Z

  \[a-z\]             The SET from lowercase a to lowercase z

  \[0-9\]             The SET from 0 to 9 (All numerals)

  \[./=+\]            The SET containing . (dot), / (slash), =, and +

  \[-A-F\]            The SET from Capital A to Capital F and the dash (dashes must be specified first)

  \[0-9 A-Z\]         The SET containing all capital letters and digits and a space

  \[A-Z\]\[a-zA-Z\]   In the first position, the SET from Capital A to Capital Z\
                      In the second character position, the SET containing all letters
  ------------------- -----------------------------------------------------------------------------------

  : \[...\] - Set Examples

\

Regular Expression Examples

/Hello/

Matches if the line contains the value Hello

/\^TEST\$/

Matches if the line contains TEST by itself

/\^\[a-zA-Z\]/

Matches if the line starts with any letter

/\^\[a-z\].\*/

Matches if the first character of the line is a-z and there is at least
one more of any character following it

/2134\$/

Matches if line ends with 2134

/\\(21|35\\)/

Matches is the line contains 21 or 35\
Note the use of ( ) with the pipe symbol to specify the 'or' condition

/\[0-9\]\*/

Matches if there are zero or more numbers in the line

/\^\[\^\#\]/

Matches if the first character is not a \# in the line

Notes:\
1. Regular expressions are case sensitive\
2. Regular expressions are to be used where *pattern* is specified

\
\
[]()

Counts
------

------------------------------------------------------------------------

  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Nearly every command may be preceded by a number that specifies how many times it is to be performed. For example, 5dw will delete 5 words and 3fe will move the cursor forward to the 3rd occurence of the letter e. Even insertions may be repeated conveniently with thismethod, say to insert the same line 100 times.
  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

\
\
\
[]()

Ranges
------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Ranges may precede most "colon" commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3-7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,\$s/pattern/string/g to make a replacement from the current line to the end of the file.
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  --------------- ------------------------------------------
  :n,m            Range - Lines n-m
  :.              Range - Current line
  :\$             Range - Last line
  :'c             Range - Marker c
  :%              Range - All lines in file
  :g/*pattern*/   Range - All lines that contain *pattern*
  --------------- ------------------------------------------

\
\
\
[]()

Files
-----

------------------------------------------------------------------------

  ------------- -----------------------------------------
  :w *file*     Write to *file*
  :r *file*     Read *file* in after line
  :n            Go to next file
  :p            Go to previos file
  :e *file*     Edit *file*
  !!*program*   Replace line with output from *program*
  ------------- -----------------------------------------

\
\
\
[]()

Other
-----

------------------------------------------------------------------------

  ---- -----------------------------------
  \~   Toggle upp and lower case
  J    Join lines
  .    Repeat last text-changing command
  u    Undo last change
  U    Undo all changes to line
  ---- -----------------------------------

\
\
\
[Return to the top](#formtop)

------------------------------------------------------------------------

Page produced by Lagmonster - Oct 2000
[]()

Vi Cheat Sheet {#vi-cheat-sheet align="CENTER"}
==============

\

-   [Modes](#mode)
-   [Quitting](#quit)
-   [Inserting Text](#insert)
-   [Motion](#motion)
-   [Deleting Text](#delete)
-   [Yanking](#yank)
-   [Changing Text](#change)
-   [Putting Text](#put)
-   [Buffers](#buffer)

<!-- -->

-   [Markers](#mark)
-   [Searching](#search)
-   [Replacing Text](#replace)
-   [Regular Expressions](#re)
-   [Counts](#count)
-   [Ranges](#range)
-   [Files](#file)
-   [Other](#other)

\
[Click here](http://www.lagmonster.org/docs/vi2.html) for the Advanced
VI Cheatsheet

------------------------------------------------------------------------

[]()

Modes
-----

------------------------------------------------------------------------

Vi has two modes insertion mode and command mode. The editor begins in
command mode, where the cursor movement and text deletion and pasting
occur. Insertion mode begins upon entering an insertion or change
command. \[ESC\] returns the editor to command mode (where you can quit,
for example by typing :q!). Most commands execute as soon as you type
them except for "colon" commands which execute when you press the ruturn
key.

\
\
\
[]()

Quitting
--------

------------------------------------------------------------------------

  ----- ---------------------------------------------
  :x    Exit, saving changes
  :q    Exit as long as there have been no changes
  ZZ    Exit and save changes if any have been made
  :q!   Exit and ignore any changes
  ----- ---------------------------------------------

\
\
\
[]()

Inserting Text
--------------

------------------------------------------------------------------------

i

Insert before cursor

I

Insert before line

a

Append after cursor

A

Append after line

o

Open a new line after current line

O

Open a new line before current line

r

Replace one character

R

Replace many characters

\
\
\
[]()

Motion
------

------------------------------------------------------------------------

  ---- ----------------------------------------------
  h    Move left
  j    Move down
  k    Move up
  l    Move right
  w    Move to next word
  W    Move to next blank delimited word
  b    Move to the beginning of the word
  B    Move to the beginning of blank delimted word
  e    Move to the end of the word
  E    Move to the end of Blank delimited word
  (    Move a sentence back
  )    Move a sentence forward
  {    Move a paragraph back
  }    Move a paragraph forward
  0    Move to the begining of the line
  \$   Move to the end of the line
  1G   Move to the first line of the file
  G    Move to the last line of the file
  nG   Move to nth line of the file
  :n   Move to nth line of the file
  fc   Move forward to c
  Fc   Move back to c
  H    Move to top of screen
  M    Move to middle of screen
  L    Move to botton of screen
  %    Move to associated ( ), { }, \[ \]
  ---- ----------------------------------------------

\
\
\
[]()

Deleting Text
-------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------
  Almost all deletion commands are performed by typing d followed by a motion. For example, dw deletes a word. A few other deletes are:
  ---------------------------------------------------------------------------------------------------------------------------------------

  ---- -----------------------------------------
  x    Delete character to the right of cursor
  X    Delete character to the left of cursor
  D    Delete to the end of the line
  dd   Delete current line
  :d   Delete current line
  ---- -----------------------------------------

\
\
\
[]()

Yanking Text
------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Like deletion, almost all yank commands are performed by typing y followed by a motion. For example, y\$ yanks to the end of the line. Two other yank commands are:
  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------

  ---- -----------------------
  yy   Yank the current line
  :y   Yank the current line
  ---- -----------------------

\
\
\
[]()

Changing text
-------------

------------------------------------------------------------------------

  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  The change command is a deletion command that leaves the editor in insert mode. It is performed by typing c followed by a motion. For wxample cw changes a word. A few other change commands are:
  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  ---- -------------------------------
  C    Change to the end of the line
  cc   Change the whole line
  ---- -------------------------------

\
\
\
[]()

Putting text
------------

------------------------------------------------------------------------

  --- -------------------------------------------
  p   Put after the position or after the line
  P   Put before the poition or before the line
  --- -------------------------------------------

\
\
\
[]()

Buffers
-------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Named buffers may be specified before any deletion, change, yank or put command. The general prefix has the form "c where c is any lowercase character. for example, "adw deletes a word into buffer a. It may thereafter be put back into text with an appropriate "ap.
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

\
\
\
[]()

Markers
-------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------
  Named markers may be set on any line in a file. Any lower case letter may be a marker name. Markers may also be used as limits for ranges.
  --------------------------------------------------------------------------------------------------------------------------------------------

  ----- ---------------------------------------------------
  mc    Set marker c on this line
  \`c   Go to beginning of marker c line.
  'c    Go to first non-blank character of marker c line.
  ----- ---------------------------------------------------

\
\
\
[]()

Search for strings
------------------

------------------------------------------------------------------------

  ----------- ------------------------------------------
  /*string*   Search forward for *string*
  ?*string*   Search back for *string*
  n           Search for next instance of *string*
  N           Search for previous instance of *string*
  ----------- ------------------------------------------

\
\
\
[]()

Replace
-------

------------------------------------------------------------------------

  ------------------------------------------------------------------------------------------------------------------------------------------------
  The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).
  ------------------------------------------------------------------------------------------------------------------------------------------------

  ------------------------------- -------------------------------------------------------
  :s/*pattern*/*string*/*flags*   Replace *pattern* with *string* according to *flags*.
  g                               Flag - Replace all occurences of pattern
  c                               Flag - Confirm replaces.
  &                               Repeat last :s command
  ------------------------------- -------------------------------------------------------

\
\
\
[]()

Regular Expressions
-------------------

------------------------------------------------------------------------

  ----------- -----------------------------------------------
  . (dot)     Any single character except newline
  \*          zero or more occurances of any character
  \[...\]     Any single character specified in the set
  \[\^...\]   Any single character not specified in the set
  \^          Anchor - beginning of the line
  \$          Anchor - end of line
  \\<      Anchor - begining of word
  \\>      Anchor - end of word
  \\(...\\)   Grouping - usually used to group conditions
  \\n         Contents of nth grouping
  ----------- -----------------------------------------------

\

  ------------------- -----------------------------------------------------------------------------------
  \[A-Z\]             The SET from Capital A to Capital Z

  \[a-z\]             The SET from lowercase a to lowercase z

  \[0-9\]             The SET from 0 to 9 (All numerals)

  \[./=+\]            The SET containing . (dot), / (slash), =, and +

  \[-A-F\]            The SET from Capital A to Capital F and the dash (dashes must be specified first)

  \[0-9 A-Z\]         The SET containing all capital letters and digits and a space

  \[A-Z\]\[a-zA-Z\]   In the first position, the SET from Capital A to Capital Z\
                      In the second character position, the SET containing all letters
  ------------------- -----------------------------------------------------------------------------------

  : \[...\] - Set Examples

\

Regular Expression Examples

/Hello/

Matches if the line contains the value Hello

/\^TEST\$/

Matches if the line contains TEST by itself

/\^\[a-zA-Z\]/

Matches if the line starts with any letter

/\^\[a-z\].\*/

Matches if the first character of the line is a-z and there is at least
one more of any character following it

/2134\$/

Matches if line ends with 2134

/\\(21|35\\)/

Matches is the line contains 21 or 35\
Note the use of ( ) with the pipe symbol to specify the 'or' condition

/\[0-9\]\*/

Matches if there are zero or more numbers in the line

/\^\[\^\#\]/

Matches if the first character is not a \# in the line

Notes:\
1. Regular expressions are case sensitive\
2. Regular expressions are to be used where *pattern* is specified

\
\
[]()

Counts
------

------------------------------------------------------------------------

  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Nearly every command may be preceded by a number that specifies how many times it is to be performed. For example, 5dw will delete 5 words and 3fe will move the cursor forward to the 3rd occurence of the letter e. Even insertions may be repeated conveniently with thismethod, say to insert the same line 100 times.
  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

\
\
\
[]()

Ranges
------

------------------------------------------------------------------------

  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Ranges may precede most "colon" commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3-7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,\$s/pattern/string/g to make a replacement from the current line to the end of the file.
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  --------------- ------------------------------------------
  :n,m            Range - Lines n-m
  :.              Range - Current line
  :\$             Range - Last line
  :'c             Range - Marker c
  :%              Range - All lines in file
  :g/*pattern*/   Range - All lines that contain *pattern*
  --------------- ------------------------------------------

\
\
\
[]()

Files
-----

------------------------------------------------------------------------

  ------------- -----------------------------------------
  :w *file*     Write to *file*
  :r *file*     Read *file* in after line
  :n            Go to next file
  :p            Go to previos file
  :e *file*     Edit *file*
  !!*program*   Replace line with output from *program*
  ------------- -----------------------------------------

\
\
\
[]()

Other
-----

------------------------------------------------------------------------

  ---- -----------------------------------
  \~   Toggle upp and lower case
  J    Join lines
  .    Repeat last text-changing command
  u    Undo last change
  U    Undo all changes to line
  ---- -----------------------------------

\
\
\
[Return to the top](#formtop)

------------------------------------------------------------------------

Page produced by Lagmonster - Oct 2000


text:
describe "Wiki Page Edit History" do
  let(:user) { FactoryBot.create :user }
  let(:study) { Study.order(Arel.sql("RANDOM()")).first }
  let!(:wiki_page) { FactoryBot.create :wiki_page, study: study }

  let(:query) { file_fixture("graphql/wiki_page_edit_history/get_history.gql").read }
  let(:variables) { { nctId: study.nct_id } }
  let(:context) { {} }

  let(:edits) { subject.dig("data", "study", "wikiPage", "edits") }

  subject { ClinwikiSchema.execute(query, variables: variables, context: context).to_h }

  before do
    wiki_page.updater = user
    wiki_page.content = wiki_page.content.sub("Add a pro here", "Here is a pro")
    wiki_page.save
    wiki_page.text = wiki_page.text.sub("Add a con here", "Here is a con")
    wiki_page.save
    wiki_page.front_matter = { "foo" => "bar" }
    wiki_page.save
    wiki_page.front_matter = { "foo" => "baz" }
    wiki_page.save
  end

  it "shows the initial wiki page creation as neither changed" do
    expect(edits.last["changeSet"]["bodyChanged"]).to eql false
    expect(edits.last["changeSet"]["frontMatterChanged"]).to eql false
  end

  it "shows changes to content as only content changed" do
    expect(edits[2]["changeSet"]["bodyChanged"]).to eql true
    expect(edits[2]["changeSet"]["frontMatterChanged"]).to eql false
    expect(edits[2]["changeSet"]["editLines"].find { |x| x["status"] == "DEL" && x["content"] == "* Add a con here" }).not_to be_nil
    expect(edits[2]["changeSet"]["editLines"].find { |x| x["status"] == "INS" && x["content"] == "* Here is a con" }).not_to be_nil
  end

  it "shows front matter changes as changes only to front matter" do
    expect(edits[1]["changeSet"]["bodyChanged"]).to eql false
    expect(edits[1]["changeSet"]["frontMatterChanged"]).to eql true
    expect(edits[1]["changeSet"]["editLines"].slice(0, 3).map { |x| x["status"] }).to eql(%w[UNCHANGED INS UNCHANGED])
  end
end

redpajama_set_name: RedPajamaGithub


text:
import tempfile, os
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from imageio import imread

"""
Utilities for making visualizations.
"""

def draw_layout(vocab, objs, boxes, masks=None, size=256,
                show_boxes=False, bgcolor=(0, 0, 0)):
  if bgcolor == 'white':
    bgcolor = (255, 255, 255)

  cmap = plt.get_cmap('rainbow')
  colors = cmap(np.linspace(0, 1, len(objs)))

  with torch.no_grad():
    objs = objs.cpu().clone()
    boxes = boxes.cpu().clone()
    boxes *= size

    if masks is not None:
      masks = masks.cpu().clone()

    bgcolor = np.asarray(bgcolor)
    bg = np.ones((size, size, 1)) * bgcolor
    plt.imshow(bg.astype(np.uint8))

    plt.gca().set_xlim(0, size)
    plt.gca().set_ylim(size, 0)
    plt.gca().set_aspect(1.0, adjustable='box')

    for i, obj in enumerate(objs):
      name = vocab['object_idx_to_name'][obj]
      if name == '__image__':
        continue
      box = boxes[i]

      if masks is None:
        continue
      mask = masks[i].numpy()
      mask /= mask.max()

      r, g, b, a = colors[i]
      colored_mask = mask[:, :, None] * np.asarray(colors[i])

      x0, y0, x1, y1 = box
      plt.imshow(colored_mask, extent=(x0, x1, y1, y0),
                 interpolation='bicubic', alpha=1.0)

    if show_boxes:
      for i, obj in enumerate(objs):
        name = vocab['object_idx_to_name'][obj]
        if name == '__image__':
          continue
        box = boxes[i]

        draw_box(box, colors[i], name)

def draw_box(box, color, text=None):
  """
  Draw a bounding box using pyplot, optionally with a text box label.

  Inputs:
  - box: Tensor or list with 4 elements: [x0, y0, x1, y1] in [0, W] x [0, H]
         coordinate system.
  - color: pyplot color to use for the box.
  - text: (Optional) String; if provided then draw a label for this box.
  """
  TEXT_BOX_HEIGHT = 10
  if torch.is_tensor(box) and box.dim() == 2:
    box = box.view(-1)
    assert box.size(0) == 4
  x0, y0, x1, y1 = box
  assert y1 > y0, box
  assert x1 > x0, box
  w, h = x1 - x0, y1 - y0
  rect = Rectangle((x0, y0), w, h, fc='none', lw=2, ec=color)
  plt.gca().add_patch(rect)
  if text is not None:
    text_rect = Rectangle((x0, y0), w, TEXT_BOX_HEIGHT, fc=color, alpha=0.5)
    plt.gca().add_patch(text_rect)
    tx = 0.5 * (x0 + x1)
    ty = y0 + TEXT_BOX_HEIGHT / 2.0
    plt.text(tx, ty, text, va='center', ha='center')

def draw_scene_graph(objs, triples, vocab=None, **kwargs):
  """
  Use GraphViz to draw a scene graph. If vocab is not passed then we assume
  that objs and triples are python lists containing strings for object and
  relationship names.

  Using this requires that GraphViz is installed. On Ubuntu 16.04 this is easy:
  sudo apt-get install graphviz
  """
  output_filename = kwargs.pop('output_filename', 'graph.png')
  orientation = kwargs.pop('orientation', 'V')
  edge_width = kwargs.pop('edge_width', 6)
  arrow_size = kwargs.pop('arrow_size', 1.5)
  binary_edge_weight = kwargs.pop('binary_edge_weight', 1.2)
  ignore_dummies = kwargs.pop('ignore_dummies', True)

  if orientation not in ['V', 'H']:
    raise ValueError('Invalid orientation "%s"' % orientation)
  rankdir = {'H': 'LR', 'V': 'TD'}[orientation]

  if vocab is not None:
    # Decode object and relationship names
    assert torch.is_tensor(objs)
    assert torch.is_tensor(triples)
    objs_list, triples_list = [], []
    for i in range(objs.size(0)):
      objs_list.append(vocab['object_idx_to_name'][objs[i].item()])
    for i in range(triples.size(0)):
      s = triples[i, 0].item()
      p = vocab['pred_name_to_idx'][triples[i, 1].item()]
      o = triples[i, 2].item()
      triples_list.append([s, p, o])
    objs, triples = objs_list, triples_list

  # General setup, and style for object nodes
  lines = [
    'digraph{',
    'graph [size="5,3",ratio="compress",dpi="300",bgcolor="transparent"]',
    'rankdir=%s' % rankdir,
    'nodesep="0.5"',
    'ranksep="0.5"',
    'node [shape="box",style="rounded,filled",fontsize="48",color="none"]',
    'node [fillcolor="lightpink1"]',
  ]
  # Output nodes for objects
  for i, obj in enumerate(objs):
    if ignore_dummies and obj == '__image__':
      continue
    lines.append('%d [label="%s"]' % (i, obj))

  # Output relationships
  next_node_id = len(objs)
  lines.append('node [fillcolor="lightblue1"]')
  for s, p, o in triples:
    if ignore_dummies and p == '__in_image__':
      continue
    lines += [
      '%d [label="%s"]' % (next_node_id, p),
      '%d->%d [penwidth=%f,arrowsize=%f,weight=%f]' % (
        s, next_node_id, edge_width, arrow_size, binary_edge_weight),
      '%d->%d [penwidth=%f,arrowsize=%f,weight=%f]' % (
        next_node_id, o, edge_width, arrow_size, binary_edge_weight)
    ]
    next_node_id += 1
  lines.append('}')

  # Now it gets slightly hacky. Write the graphviz spec to a temporary
  # text file
  ff, dot_filename = tempfile.mkstemp()
  with open(dot_filename, 'w') as f:
    for line in lines:
      f.write('%s\n' % line)
  os.close(ff)

  # Shell out to invoke graphviz; this will save the resulting image to disk,
  # so we read it, delete it, then return it.
  output_format = os.path.splitext(output_filename)[1][1:]
  os.system('dot -T%s %s > %s' % (output_format, dot_filename, output_filename))
  os.remove(dot_filename)
  img = imread(output_filename)
  os.remove(output_filename)

  return img

if __name__ == '__main__':
  o_idx_to_name = ['cat', 'dog', 'hat', 'skateboard']
  p_idx_to_name = ['riding', 'wearing', 'on', 'next to', 'above']
  o_name_to_idx = {s: i for i, s in enumerate(o_idx_to_name)}
  p_name_to_idx = {s: i for i, s in enumerate(p_idx_to_name)}
  vocab = {
    'object_idx_to_name': o_idx_to_name,
    'object_name_to_idx': o_name_to_idx,
    'pred_idx_to_name': p_idx_to_name,
    'pred_name_to_idx': p_name_to_idx,
  }

  objs = [
    'cat',
    'cat',
    'skateboard',
    'hat',
  ]
  objs = torch.LongTensor([o_name_to_idx[o] for o in objs])
  triples = [
    [0, 'next to', 1],
    [0, 'riding', 2],
    [1, 'wearing', 3],
    [3, 'above', 2],
  ]
  triples = [[s, p_name_to_idx[p], o] for s, p, o in triples]
  triples = torch.LongTensor(triples)

  draw_scene_graph(objs, triples, vocab, orientation='V')


text:
fig, ax = plt.subplots()
geo_df.to_crs(epsg="4326").plot(markersize=10, ax=ax) # on the fly conversion to WGS84
geo_df.buffer(500).to_crs(epsg="4326").plot(ax=ax) # on the fly conversion to WGS84
mplleaflet.display()


text:
#ifndef _CMTPACKET_H_2006_05_10
#define _CMTPACKET_H_2006_05_10

#ifndef _CMT_MONOLITHIC
#	include "cmtdef.h"
#	include "cmt2.h"
#endif

namespace xsens {

	//! Indicates that a data item is not available in the packet
#define CMT_DATA_ITEM_NOT_AVAILABLE		65535

	//! A structure containing MT data + timestamp and formatting information.
class Packet
{
protected:
		//! Contains information about data in the packet and the format of that data
	mutable struct PacketInfo {
		uint16_t m_offset;
		uint16_t m_rawData;
		uint16_t m_rawAcc;
		uint16_t m_rawGyr;
		uint16_t m_rawMag;
		uint16_t m_rawTemp;
		uint16_t m_temp;
		uint16_t m_calData;
		uint16_t m_calAcc;
		uint16_t m_calGyr;
		uint16_t m_calMag;
		uint16_t m_oriQuat;
		uint16_t m_oriEul;
		uint16_t m_oriMat;
		uint16_t m_analogIn1;
		uint16_t m_analogIn2;
		uint16_t m_posLLA;
		uint16_t m_velNEDorNWU;
		uint16_t m_status;
		uint16_t m_sc;
		uint16_t m_acc_g;
		uint16_t m_rawGpsData;
		uint16_t m_rawGpsPressure;
		uint16_t m_rawGpsPressureAge;
		uint16_t m_rawGpsGpsData;
		uint16_t m_rawGpsItow;
		uint16_t m_rawGpsLatitude;
		uint16_t m_rawGpsLongitude;
		uint16_t m_rawGpsHeight;
		uint16_t m_rawGpsVeln;
		uint16_t m_rawGpsVele;
		uint16_t m_rawGpsVeld;
		uint16_t m_rawGpsHacc;
		uint16_t m_rawGpsVacc;
		uint16_t m_rawGpsSacc;
		uint16_t m_rawGpsGpsAge;
		uint16_t m_size;
	}*	m_infoList;
	CmtDataFormat*	m_formatList;	//!< A list of the formats of the data items
	bool m_xm;						//!< Indicates that xbus-formatting is used

public:
	uint16_t	m_itemCount;	//!< The number of data items in the message
	Message			m_msg;			//!< The message
	TimeStamp		m_rtc;			//!< Sample time in ms, based on the sample counter
	TimeStamp		m_toa;			//!< Time of arrival

	Packet(uint16_t items, bool xbus);
	Packet(const Packet& pack);
	~Packet();

	void operator = (const Packet& pack);

	bool setDataFormat(const CmtDataFormat& format, const uint16_t index = 0);
	bool setDataFormat(const CmtOutputMode outputMode, const CmtOutputSettings outputSettings, const uint16_t index = 0);
	CmtDataFormat getDataFormat(const uint16_t index = 0) const;
	void setXbus(bool xbus, bool convert = false);
	bool getXbus(void) const;

	/*! \brief Return the data size.

		\param index The index of the item of which the size should be returned.
	*/
	uint16_t getDataSize(const uint16_t index=0) const;

	/*! \brief Return the floating/fixed point value size

		\param index The index of the item whose fp size should be returned.
	*/
	uint16_t getFPValueSize(const uint16_t index) const;

	/*! \brief Return the Raw Accelerometer component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtShortVector getRawAcc(const uint16_t index=0) const;
		//! Check if data item contains Raw Accelerometer data
	bool containsRawAcc(const uint16_t index=0) const;
		//! Add/update Raw Accelerometer data for the item
	bool updateRawAcc(const CmtShortVector& vec, const uint16_t index=0);
	/*! \brief Return the Raw Gyroscope component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtShortVector getRawGyr(const uint16_t index=0) const;
		//! Check if data item contains Raw Gyroscope data
	bool containsRawGyr(const uint16_t index=0) const;
		//! Add/update Raw Gyroscope data for the item
	bool updateRawGyr(const CmtShortVector& vec, const uint16_t index=0);
	/*! \brief Return the Raw Magnetometer component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtShortVector getRawMag(const uint16_t index=0) const;
		//! Check if data item contains Raw Magnetometer data
	bool containsRawMag(const uint16_t index=0) const;
		//! Add/update Raw Magnetometer data for the item
	bool updateRawMag(const CmtShortVector& vec, const uint16_t index=0);
	/*! \brief Return the Raw Temperature component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	uint16_t getRawTemp(const uint16_t index=0) const;
		//! Check if data item contains Raw Temperature data
	bool containsRawTemp(const uint16_t index=0) const;
		//! Add/update Raw Temperature data for the item
	bool updateRawTemp(uint16_t temp, const uint16_t index=0);
	/*! \brief Return the Raw Data component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtRawData getRawData(const uint16_t index=0) const;
		//! Check if data item contains Raw Data
	bool containsRawData(const uint16_t index=0) const;
		//! Add/update Raw Data for the item
	bool updateRawData(const CmtRawData& data, const uint16_t index=0);
	/*! \brief Return the Raw GpsPrint Data component of a data item.
	// TODO: Implement in COM interface!!!
	\param index The index of the item of which the data should be returned.
	*/
	CmtRawGpsData getRawGpsData(const uint16_t index=0) const;
	//! Check if data item contains Raw GpsPrint Data
	bool containsRawGpsData(const uint16_t index=0) const;
	//! Add/update Raw GpsPrint Data for the item
	bool updateRawGpsData(const CmtRawGpsData& data, const uint16_t index=0);
	/*! \brief Return the Temperature component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	double getTemp(const uint16_t index=0) const;
	//! Check if data item contains Temperature data
	bool containsTemp(const uint16_t index=0) const;
	//! Add/update Calibrated Accelerometer data for the item
	bool updateTemp(const double& temp, const uint16_t index=0);
	/*! \brief Return the Calibrated Accelerometer component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtVector getCalAcc(const uint16_t index=0) const;
		//! Check if data item contains Calibrated Accelerometer data
	bool containsCalAcc(const uint16_t index=0) const;
		//! Add/update Calibrated Accelerometer data for the item
	bool updateCalAcc(const CmtVector& vec, const uint16_t index=0);
	/*! \brief Return the Calibrated Gyroscope component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtVector getCalGyr(const uint16_t index=0) const;
		//! Check if data item contains Calibrated Gyroscope data
	bool containsCalGyr(const uint16_t index=0) const;
		//! Add/update Calibrated Gyroscope data for the item
	bool updateCalGyr(const CmtVector& vec, const uint16_t index=0);
	/*! \brief Return the Calibrated Magnetometer component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtVector getCalMag(const uint16_t index=0) const;
		//! Check if data item contains Calibrated Magnetometer data
	bool containsCalMag(const uint16_t index=0) const;
		//! Add/update Calibrated Magnetometer data for the item
	bool updateCalMag(const CmtVector& vec, const uint16_t index=0);
	/*! \brief Return the Calibrated Data component of a data item.

		\param index The index of the item of which the data should be returned.
	*/
	CmtCalData getCalData(const uint16_t index=0) const;
		//! Check if data item contains Calibrated Data
	bool containsCalData(const uint16_t index=0) const;
		//! Add/update Calibrated Data for the item
	bool updateCalData(const CmtCalData& data, const uint16_t index=0);

	/*! \brief Return the Orientation component of a data item as a Quaternion.

		\param index The index of the item of which the data should be returned.
	*/
	CmtQuat getOriQuat(const uint16_t index=0) const;
		//! Check if data item contains Quaternion Orientation data
	bool containsOriQuat(const uint16_t index=0) const;
		//! Add/update Quaternion Orientation data for the item
	bool updateOriQuat(const CmtQuat& data, const uint16_t index=0);
	/*! \brief Return the Orientation component of a data item as Euler angles.

		\param index The index of the item of which the data should be returned.
	*/
	CmtEuler getOriEuler(const uint16_t index=0) const;
		//! Check if data item contains Euler Orientation data
	bool containsOriEuler(const uint16_t index=0) const;
		//! Add/update Euler Orientation data for the item
	bool updateOriEuler(const CmtEuler& data, const uint16_t index=0);
	/*! \brief Return the Orientation component of a data item as an Orientation Matrix.

		\param index The index of the item of which the data should be returned.
	*/
	CmtMatrix getOriMatrix(const uint16_t index=0) const;
		//! Check if data item contains Matrix Orientation data
	bool containsOriMatrix(const uint16_t index=0) const;
		//! Add/update Matrix Orientation data for the item
	bool updateOriMatrix(const CmtMatrix& data, const uint16_t index=0);

	/*! \brief Return the AnalogIn 1 component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	CmtAnalogInData getAnalogIn1(const uint16_t index=0) const;
	//! Check if data item contains AnalogIn 1
	bool containsAnalogIn1(const uint16_t index=0) const;
	//! Add/update AnalogIn 1 for the item
	bool updateAnalogIn1(const CmtAnalogInData& data, const uint16_t index=0);

	/*! \brief Return the AnalogIn 2 component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	CmtAnalogInData getAnalogIn2(const uint16_t index=0) const;
	//! Check if data item contains AnalogIn 2
	bool containsAnalogIn2(const uint16_t index=0) const;
	//! Add/update AnalogIn 2 for the item
	bool updateAnalogIn2(const CmtAnalogInData& data, const uint16_t index=0);

	/*! \brief Return the Position Lat Lon Alt component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	CmtVector getPositionLLA(const uint16_t index=0) const;
	//! Check if data item contains Position Lat Lon Alt
	bool containsPositionLLA(const uint16_t index=0) const;
	//! Add/update Position Lat Lon Alt for the item
	bool updatePositionLLA(const CmtVector& data, const uint16_t index=0);

	/*! \brief Return the Velocity component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	CmtVector getVelocity(const uint16_t index=0) const;
	//! Check if data item contains Velocity
	bool containsVelocity(const uint16_t index=0) const;
	//! Add/update Velocity for the item
	bool updateVelocity(const CmtVector& data, const uint16_t index=0);

	/*! \brief Return the Status component of a data item.

	\param index The index of the item of which the data should be returned.
	*/
	uint8_t getStatus(const uint16_t index=0) const;
	//! Check if data item contains Velocity
	bool containsStatus(const uint16_t index=0) const;
	//! Add/update Status information for the item
	bool updateStatus(const uint8_t data, const uint16_t index=0);

	/*! \brief Return the Sample Counter component of the packet.

		\param index The index of the item of which the data should be returned. (ignored)
	*/
	uint16_t getSampleCounter(const uint16_t index=0) const;
		//! Check if data item contains Sample Counter
	bool containsSampleCounter(const uint16_t index=0) const;
		//! Add/update Sample Counter for all items
	bool updateSampleCounter(uint16_t counter, const uint16_t index=0);
	/*! \brief Return the RTC of the packet.

		\param index The index of the item of which the data should be returned. (ignored)
	*/
	CmtTimeStamp getRtc(const uint16_t index=0) const;

	/*! \brief Return the XKF-3 Acc-G component of the packet.

		\param index The index of the item of which the data should be returned.
	*/
	CmtVector getAccG(const uint16_t index=0) const;
		//! Check if data item contains XKF-3 Acc-G data
	bool containsAccG(const uint16_t index=0) const;
		//! Add/update XKF-3 Acc-G data for the item
	bool updateAccG(const CmtVector& g, const uint16_t index=0);

	#ifdef _CMT_DLL_EXPORT
		//! Interpolate so resulting packet is (1-f)*pa + pb OR pb if pa and pb are non-matching types
	void interpolate(const Packet& pa, const Packet& pb, const double f);
	#endif
};

}	// end of xsens namespace

#endif	// _CMTPACKET_H_2006_05_10


text:
package javax.swing;

import java.awt.Container;
import java.awt.Dimension;
import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleHyperlink;
import javax.accessibility.AccessibleHypertext;
import javax.accessibility.AccessibleStateSet;
import javax.accessibility.AccessibleText;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.plaf.TextUI;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.WrappedPlainView;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

/**
 * A powerful text editor component that can handle different types of
 * content.
 *
 * The JEditorPane text component is driven by an instance of
 * {@link EditorKit}. The editor kit is responsible for providing
 * a default {@link Document} implementation, a mechanism for loading
 * and saving documents of its supported content type and providing
 * a set of {@link Action}s for manipulating the content.
 *
 * By default the following content types are supported:
 *

 *
text/plain: Plain text, handled by
 *   {@link javax.swing.text.DefaultEditorKit}.

 *
text/html: HTML 4.0 styled text, handled by
 *   {@link javax.swing.text.html.HTMLEditorKit}.

 *
text/rtf: RTF text, handled by
 *   {@link javax.swing.text.rtf.RTFEditorKit}.

 *

 *
 * @author original author unknown
 * @author Roman Kennke (roman@kennke.org)
 * @author Anthony Balkissoon abalkiss at redhat dot com
 */
public class JEditorPane extends JTextComponent
{
  /**
   * Provides accessibility support for JEditorPane.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  protected class AccessibleJEditorPane extends AccessibleJTextComponent
  {

    /**
     * Creates a new AccessibleJEditorPane object.
     */
    protected AccessibleJEditorPane()
    {
      super();
    }

    /**
     * Returns a description of this AccessibleJEditorPane. If
     * this property is not set, then this returns the content-type of the
     * editor pane.
     *
     * @return a description of this AccessibleJEditorPane
     */
    public String getAccessibleDescription()
    {
      String descr = super.getAccessibleDescription();
      if (descr == null)
        return getContentType();
      else
        return descr;
    }

    /**
     * Returns the accessible state of this AccessibleJEditorPane.
     *
     * @return  the accessible state of this AccessibleJEditorPane
     */
    public AccessibleStateSet getAccessibleStateSet()
    {
      AccessibleStateSet state = super.getAccessibleStateSet();
      // TODO: Figure out what state must be added here to the super's state.
      return state;
    }
  }

  /**
   * Provides accessibility support for JEditorPanes, when the
   * editor kit is an instance of {@link HTMLEditorKit}.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane
  {
    /**
     * Returns the accessible text of the JEditorPane. This will
     * be an instance of
     * {@link JEditorPaneAccessibleHypertextSupport}.
     *
     * @return the accessible text of the JEditorPane
     */
    public AccessibleText getAccessibleText()
    {
      return new JEditorPaneAccessibleHypertextSupport();
    }
  }

  /**
   * This is the accessible text that is returned by
   * {@link AccessibleJEditorPaneHTML#getAccessibleText()}.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  protected class JEditorPaneAccessibleHypertextSupport
    extends AccessibleJEditorPane implements AccessibleHypertext
  {

    /**
     * Creates a new JEditorPaneAccessibleHypertextSupport object.
     */
    public JEditorPaneAccessibleHypertextSupport()
    {
      super();
    }

    /**
     * The accessible representation of a HTML link.
     *
     * @author Roman Kennke (kennke@aicas.com)
     */
    public class HTMLLink extends AccessibleHyperlink
    {

      /**
       * The element in the document that represents the link.
       */
      Element element;

      /**
       * Creates a new HTMLLink.
       *
       * @param el the link element
       */
      public HTMLLink(Element el)
      {
        this.element = el;
      }

      /**
       * Returns true if this HTMLLink is still
       * valid. A HTMLLink can become invalid when the document
       * changes.
       *
       * @return true if this HTMLLink is still
       *         valid
       */
      public boolean isValid()
      {
        // I test here if the element at our element's start offset is the
        // same as the element in the document at this offset. If this is true,
        // I consider the link valid, if not, then this link no longer
        // represented by this HTMLLink and therefor invalid.
        HTMLDocument doc = (HTMLDocument) getDocument();
        return doc.getCharacterElement(element.getStartOffset()) == element;
      }

      /**
       * Returns the number of AccessibleActions in this link object. In
       * general, link have 1 AccessibleAction associated with them. There are
       * special cases where links can have multiple actions associated, like
       * in image maps.
       *
       * @return the number of AccessibleActions in this link object
       */
      public int getAccessibleActionCount()
      {
        // TODO: Implement the special cases.
        return 1;
      }

      /**
       * Performs the specified action on the link object. This ususally means
       * activating the link.
       *
       * @return true if the action has been performed
       *         successfully, false otherwise
       */
      public boolean doAccessibleAction(int i)
      {
        String href = (String) element.getAttributes().getAttribute("href");
        HTMLDocument doc = (HTMLDocument) getDocument();
        try
          {
            URL url = new URL(doc.getBase(), href);
            setPage(url);
            String desc = doc.getText(element.getStartOffset(),
                            element.getEndOffset() - element.getStartOffset());
            HyperlinkEvent ev =
              new HyperlinkEvent(JEditorPane.this,
                                 HyperlinkEvent.EventType.ACTIVATED, url, desc,
                                 element);
            fireHyperlinkUpdate(ev);
            return true;
          }
        catch (Exception ex)
          {
            return false;
          }
      }

      /**
       * Returns the description of the action at action index i.
       * This method returns the text within the element associated with this
       * link.
       *
       * @param i the action index
       *
       * @return the description of the action at action index i
       */
      public String getAccessibleActionDescription(int i)
      {
        HTMLDocument doc = (HTMLDocument) getDocument();
        try
          {
            return doc.getText(element.getStartOffset(),
                            element.getEndOffset() - element.getStartOffset());
          }
        catch (BadLocationException ex)
          {
            throw (AssertionError)
            new AssertionError("BadLocationException must not be thrown "
                               + "here.")
              .initCause(ex);
          }
      }

      /**
       * Returns an {@link URL} object, that represents the action at action
       * index i.
       *
       * @param i the action index
       *
       * @return an {@link URL} object, that represents the action at action
       *         index i
       */
      public Object getAccessibleActionObject(int i)
      {
        String href = (String) element.getAttributes().getAttribute("href");
        HTMLDocument doc = (HTMLDocument) getDocument();
        try
          {
            URL url = new URL(doc.getBase(), href);
            return url;
          }
        catch (MalformedURLException ex)
          {
            return null;
          }
      }

      /**
       * Returns an object that represents the link anchor. For examples, if
       * the link encloses a string, then a String object is
       * returned, if the link encloses an <img> tag, then an
       * ImageIcon object is returned.
       *
       * @return an object that represents the link anchor
       */
      public Object getAccessibleActionAnchor(int i)
      {
        // TODO: This is only the String case. Implement all cases.
        return getAccessibleActionDescription(i);
      }

      /**
       * Returns the start index of the hyperlink element.
       *
       * @return the start index of the hyperlink element
       */
      public int getStartIndex()
      {
        return element.getStartOffset();
      }

      /**
       * Returns the end index of the hyperlink element.
       *
       * @return the end index of the hyperlink element
       */
      public int getEndIndex()
      {
        return element.getEndOffset();
      }

    }

    /**
     * Returns the number of hyperlinks in the document.
     *
     * @return the number of hyperlinks in the document
     */
    public int getLinkCount()
    {
      HTMLDocument doc = (HTMLDocument) getDocument();
      HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A);
      int count = 0;
      while (linkIter.isValid())
        {
          count++;
          linkIter.next();
        }
      return count;
    }

    /**
     * Returns the i-th hyperlink in the document or
     * null if there is no hyperlink with the specified index.
     *
     * @param i the index of the hyperlink to return
     *
     * @return the i-th hyperlink in the document or
     *         null if there is no hyperlink with the specified
     *         index
     */
    public AccessibleHyperlink getLink(int i)
    {
      HTMLDocument doc = (HTMLDocument) getDocument();
      HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A);
      int count = 0;
      while (linkIter.isValid())
        {
          count++;
          if (count == i)
            break;
          linkIter.next();
        }
      if (linkIter.isValid())
        {
          int offset = linkIter.getStartOffset();
          // TODO: I fetch the element for the link via getCharacterElement().
          // I am not sure that this is correct, maybe we must use
          // getParagraphElement()?
          Element el = doc.getCharacterElement(offset);
          HTMLLink link = new HTMLLink(el);
          return link;
        }
      else
        return null;
    }

    /**
     * Returns the index of the link element at the character position
     * c within the document, or -1 if there is no
     * link at the specified position.
     *
     * @param c the character index from which to fetch the link index
     *
     * @return the index of the link element at the character position
     *         c within the document, or -1 if there
     *         is no link at the specified position
     */
    public int getLinkIndex(int c)
    {
      HTMLDocument doc = (HTMLDocument) getDocument();
      HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A);
      int count = 0;
      while (linkIter.isValid())
        {
          if (linkIter.getStartOffset() <= c && linkIter.getEndOffset() > c)
            break;
          count++;
          linkIter.next();
        }
      if (linkIter.isValid())
        return count;
      else
        return -1;
    }

    /**
     * Returns the link text of the link at index i, or
     * null, if there is no link at the specified position.
     *
     * @param i the index of the link
     *
     * @return  the link text of the link at index i, or
     *          null, if there is no link at the specified
     *          position
     */
    public String getLinkText(int i)
    {
      HTMLDocument doc = (HTMLDocument) getDocument();
      HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A);
      int count = 0;
      while (linkIter.isValid())
        {
          count++;
          if (count == i)
            break;
          linkIter.next();
        }
      if (linkIter.isValid())
        {
          int offset = linkIter.getStartOffset();
          // TODO: I fetch the element for the link via getCharacterElement().
          // I am not sure that this is correct, maybe we must use
          // getParagraphElement()?
          Element el = doc.getCharacterElement(offset);
          try
            {
              String text = doc.getText(el.getStartOffset(),
                                      el.getEndOffset() - el.getStartOffset());
              return text;
            }
          catch (BadLocationException ex)
            {
              throw (AssertionError)
                new AssertionError("BadLocationException must not be thrown "
                                   + "here.")
                  .initCause(ex);
            }
        }
      else
        return null;
    }
  }

  /**
   * Used to store a mapping for content-type to editor kit class.
   */
  private static class EditorKitMapping
  {
    /**
     * The classname of the editor kit.
     */
    String className;

    /**
     * The classloader with which the kit is to be loaded.
     */
    ClassLoader classLoader;

    /**
     * Creates a new EditorKitMapping object.
     *
     * @param cn the classname
     * @param cl the classloader
     */
    EditorKitMapping(String cn, ClassLoader cl)
    {
      className = cn;
      classLoader = cl;
    }
  }

  /**
   * An EditorKit used for plain text. This is the default editor kit for
   * JEditorPanes.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  private static class PlainEditorKit extends DefaultEditorKit
  {

    /**
     * Returns a ViewFactory that supplies WrappedPlainViews.
     */
    public ViewFactory getViewFactory()
    {
      return new ViewFactory()
      {
        public View create(Element el)
        {
          return new WrappedPlainView(el);
        }
      };
    }
  }

  /**
   * A special stream that can be cancelled.
   */
  private class PageStream
    extends FilterInputStream
  {
    /**
     * True when the stream has been cancelled, false otherwise.
     */
    private boolean cancelled;

    protected PageStream(InputStream in)
    {
      super(in);
      cancelled = false;
    }

    private void checkCancelled()
      throws IOException
    {
      if (cancelled)
        throw new IOException("Stream has been cancelled");
    }

    void cancel()
    {
      cancelled = true;
    }

    public int read()
      throws IOException
    {
      checkCancelled();
      return super.read();
    }

    public int read(byte[] b, int off, int len)
      throws IOException
    {
      checkCancelled();
      return super.read(b, off, len);
    }

    public long skip(long n)
      throws IOException
    {
      checkCancelled();
      return super.skip(n);
    }

    public int available()
      throws IOException
    {
      checkCancelled();
      return super.available();
    }

    public void reset()
      throws IOException
    {
      checkCancelled();
      super.reset();
    }
  }

  /**
   * The thread that loads documents asynchronously.
   */
  private class PageLoader
    implements Runnable
  {
    private Document doc;
    private PageStream in;
    private URL old;
    URL page;
    PageLoader(Document doc, InputStream in, URL old, URL page)
    {
      this.doc = doc;
      this.in = new PageStream(in);
      this.old = old;
      this.page = page;
    }

    public void run()
    {
      try
        {
          read(in, doc);
        }
      catch (IOException ex)
        {
          UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
        }
      finally
        {
          if (SwingUtilities.isEventDispatchThread())
            firePropertyChange("page", old, page);
          else
            {
              SwingUtilities.invokeLater(new Runnable()
              {
                public void run()
                {
                  firePropertyChange("page", old, page);
                }
              });
            }
         }
     }

     void cancel()
     {
       in.cancel();
     }
  }

  private static final long serialVersionUID = 3140472492599046285L;

  private EditorKit editorKit;

  boolean focus_root;

  /**
   * Maps content-types to editor kit instances.
   */
  static HashMap editorKits;

  // A mapping between content types and registered EditorKit types
  static HashMap registerMap;

  static
  {
    registerMap = new HashMap();
    editorKits = new HashMap();
    registerEditorKitForContentType("application/rtf",
                                    "javax.swing.text.rtf.RTFEditorKit");
    registerEditorKitForContentType("text/plain",
                                    "javax.swing.JEditorPane$PlainEditorKit");
    registerEditorKitForContentType("text/html",
                                    "javax.swing.text.html.HTMLEditorKit");
    registerEditorKitForContentType("text/rtf",
                                    "javax.swing.text.rtf.RTFEditorKit");

  }

  // A mapping between content types and used EditorKits
  HashMap editorMap;

  /**
   * The currently loading stream, if any.
   */
  private PageLoader loader;

  public JEditorPane()
  {
    init();
    setEditorKit(createDefaultEditorKit());
  }

  public JEditorPane(String url) throws IOException
  {
    this(new URL(url));
  }

  public JEditorPane(String type, String text)
  {
    init();
    setEditorKit(createEditorKitForContentType(type));
    setText(text);
  }

  public JEditorPane(URL url) throws IOException
  {
    init();
    setEditorKit(createEditorKitForContentType("text/html"));
    setPage(url);
  }

  /**
   * Called by the constructors to set up the default bindings for content
   * types and EditorKits.
   */
  void init()
  {
    editorMap = new HashMap();
  }

  protected EditorKit createDefaultEditorKit()
  {
    return new PlainEditorKit();
  }

  /**
   * Creates and returns an EditorKit that is appropriate for the given
   * content type.  This is created using the default recognized types
   * plus any EditorKit types that have been registered.
   *
   * @see #registerEditorKitForContentType(String, String)
   * @see #registerEditorKitForContentType(String, String, ClassLoader)
   * @param type the content type
   * @return an EditorKit for use with the given content type
   */
  public static EditorKit createEditorKitForContentType(String type)
  {
    // Try cached instance.
    EditorKit e = (EditorKit) editorKits.get(type);
    if (e == null)
      {
        EditorKitMapping m = (EditorKitMapping) registerMap.get(type);
        if (m != null)
          {
            String className = m.className;
            ClassLoader loader = m.classLoader;
            try
              {
                e = (EditorKit) loader.loadClass(className).newInstance();
              }
            catch (Exception e2)
              {
                // The reference implementation returns null when class is not
                // loadable or instantiatable.
              }
          }
        // Cache this for later retrieval.
        if (e != null)
          editorKits.put(type, e);
      }
    return e;
  }

  /**
   * Sends a given HyperlinkEvent to all registered listeners.
   *
   * @param event the event to send
   */
  public void fireHyperlinkUpdate(HyperlinkEvent event)
  {
    HyperlinkListener[] listeners = getHyperlinkListeners();

    for (int index = 0; index < listeners.length; ++index)
       listeners[index].hyperlinkUpdate(event);
  }

  /**
   * Returns the accessible context associated with this editor pane.
   *
   * @return the accessible context associated with this editor pane
   */
  public AccessibleContext getAccessibleContext()
  {
    if (accessibleContext == null)
      {
        if (getEditorKit() instanceof HTMLEditorKit)
          accessibleContext = new AccessibleJEditorPaneHTML();
        else
          accessibleContext = new AccessibleJEditorPane();
      }
    return accessibleContext;
  }

  public final String getContentType()
  {
    return getEditorKit().getContentType();
  }

  /**
   * Returns the EditorKit. If there is no EditorKit set this method
   * calls createDefaultEditorKit() and setEditorKit() first.
   */
  public EditorKit getEditorKit()
  {
    if (editorKit == null)
      setEditorKit(createDefaultEditorKit());
    return editorKit;
  }

  /**
   * Returns the class name of the EditorKit associated with the given
   * content type.
   *
   * @since 1.3
   * @param type the content type
   * @return the class name of the EditorKit associated with this content type
   */
  public static String getEditorKitClassNameForContentType(String type)
  {
    EditorKitMapping m = (EditorKitMapping) registerMap.get(type);
    String kitName = m != null ? m.className : null;
    return kitName;
  }

  /**
   * Returns the EditorKit to use for the given content type.  If an
   * EditorKit has been explicitly set via
   * setEditorKitForContentType
   * then it will be returned.  Otherwise an attempt will be made to create
   * an EditorKit from the default recognzied content types or any
   * EditorKits that have been registered.  If none can be created, a
   * PlainEditorKit is created.
   *
   * @see #registerEditorKitForContentType(String, String)
   * @see #registerEditorKitForContentType(String, String, ClassLoader)
   * @param type the content type
   * @return an appropriate EditorKit for the given content type
   */
  public EditorKit getEditorKitForContentType(String type)
  {
    // First check if an EditorKit has been explicitly set.
    EditorKit e = (EditorKit) editorMap.get(type);
    // Then check to see if we can create one.
    if (e == null)
      {
        e = createEditorKitForContentType(type);
        if (e != null)
          setEditorKitForContentType(type, e);
      }
    // Otherwise default to PlainEditorKit.
    if (e == null)
      e = createDefaultEditorKit();
    return e;
  }

  /**
   * Returns the preferred size for the JEditorPane. This is implemented to
   * return the super's preferred size, unless one of
   * {@link #getScrollableTracksViewportHeight()} or
   * {@link #getScrollableTracksViewportWidth()} returns true,
   * in which case the preferred width and/or height is replaced by the UI's
   * minimum size.
   *
   * @return the preferred size for the JEditorPane
   */
  public Dimension getPreferredSize()
  {
    Dimension pref = super.getPreferredSize();
    Container parent = getParent();
    if (parent instanceof JViewport)
      {
        JViewport vp = (JViewport) getParent();
        TextUI ui = getUI();
        Dimension min = null;
        if (! getScrollableTracksViewportWidth())
          {
            min = ui.getMinimumSize(this);
            int vpWidth = vp.getWidth();
            if (vpWidth != 0 && vpWidth < min.width)
              pref.width = min.width;
          }
        if (! getScrollableTracksViewportHeight())
          {
            if (min == null)
              min = ui.getMinimumSize(this);
            int vpHeight = vp.getHeight();
            if (vpHeight != 0 && vpHeight < min.height)
              pref.height = min.height;
          }
      }
    return pref;
  }

  /**
   * Returns true when a Viewport should force the height of
   * this component to match the viewport height. This is implemented to return
   * true when  the parent is an instance of JViewport and
   * the viewport height > the UI's minimum height.
   *
   * @return true when a Viewport should force the height of
   *         this component to match the viewport height
   */
  public boolean getScrollableTracksViewportHeight()
  {
    // Tests show that this returns true when the parent is a JViewport
    // and has a height > minimum UI height.
    Container parent = getParent();
    int height = parent.getHeight();
    TextUI ui = getUI();
    return parent instanceof JViewport
           && height >= ui.getMinimumSize(this).height
           && height <= ui.getMaximumSize(this).height;
  }

  /**
   * Returns true when a Viewport should force the width of
   * this component to match the viewport width. This is implemented to return
   * true when  the parent is an instance of JViewport and
   * the viewport width > the UI's minimum width.
   *
   * @return true when a Viewport should force the width of
   *         this component to match the viewport width
   */
  public boolean getScrollableTracksViewportWidth()
  {
    // Tests show that this returns true when the parent is a JViewport
    // and has a width > minimum UI width.
    Container parent = getParent();
    return parent != null && parent instanceof JViewport
           && parent.getWidth() > getUI().getMinimumSize(this).width;
  }

  public URL getPage()
  {
    return loader != null ? loader.page : null;
  }

  protected InputStream getStream(URL page)
    throws IOException
  {
    URLConnection conn = page.openConnection();
    // Try to detect the content type of the stream data.
    String type = conn.getContentType();
    if (type != null)
      setContentType(type);
    InputStream stream = conn.getInputStream();
    return new BufferedInputStream(stream);
  }

  public String getText()
  {
    return super.getText();
  }

  public String getUIClassID()
  {
    return "EditorPaneUI";
  }

  public boolean isFocusCycleRoot()
  {
    return focus_root;
  }

  protected String paramString()
  {
    return "JEditorPane";
  }

  /**
   * This method initializes from a stream.
   */
  public void read(InputStream in, Object desc) throws IOException
  {
    EditorKit kit = getEditorKit();
    if (kit instanceof HTMLEditorKit && desc instanceof HTMLDocument)
      {
        HTMLDocument doc = (HTMLDocument) desc;
        setDocument(doc);
        try
          {
            InputStreamReader reader = new InputStreamReader(in);
            kit.read(reader, doc, 0);
          }
        catch (BadLocationException ex)
          {
            assert false : "BadLocationException must not be thrown here.";
          }
      }
    else
      {
        Reader inRead = new InputStreamReader(in);
        super.read(inRead, desc);
      }
  }

  /**
   * Establishes a binding between type and classname.  This enables
   * us to create an EditorKit later for the given content type.
   *
   * @param type the content type
   * @param classname the name of the class that is associated with this
   * content type
   */
  public static void registerEditorKitForContentType(String type,
                                                     String classname)
  {
    registerEditorKitForContentType(type, classname,
                               Thread.currentThread().getContextClassLoader());
  }

  /**
   * Establishes the default bindings of type to classname.
   */
  public static void registerEditorKitForContentType(String type,
                                                     String classname,
                                                     ClassLoader loader)
  {
    registerMap.put(type, new EditorKitMapping(classname, loader));
  }

  /**
   * Replaces the currently selected content with new content represented
   * by the given string.
   */
  public void replaceSelection(String content)
  {
    // TODO: Implement this properly.
    super.replaceSelection(content);
  }

  /**
   * Scrolls the view to the given reference location (that is, the value
   * returned by the UL.getRef method for the URL being displayed).
   */
  public void scrollToReference(String reference)
  {
    // TODO: Implement this properly.
  }

  public final void setContentType(String type)
  {
    // Strip off content type parameters.
    int paramIndex = type.indexOf(';');
    if (paramIndex > -1)
      {
        // TODO: Handle character encoding.
        type = type.substring(0, paramIndex).trim();
      }
    if (editorKit != null
        && editorKit.getContentType().equals(type))
      return;

    EditorKit kit = getEditorKitForContentType(type);

    if (kit != null)
      setEditorKit(kit);
  }

  public void setEditorKit(EditorKit newValue)
  {
    if (editorKit == newValue)
      return;

    if (editorKit != null)
      editorKit.deinstall(this);

    EditorKit oldValue = editorKit;
    editorKit = newValue;

    if (editorKit != null)
      {
        editorKit.install(this);
        setDocument(editorKit.createDefaultDocument());
      }

    firePropertyChange("editorKit", oldValue, newValue);
    invalidate();
    repaint();
    // Reset the accessibleContext since this depends on the editorKit.
    accessibleContext = null;
  }

  /**
   * Explicitly sets an EditorKit to be used for the given content type.
   * @param type the content type
   * @param k the EditorKit to use for the given content type
   */
  public void setEditorKitForContentType(String type, EditorKit k)
  {
    editorMap.put(type, k);
  }

  /**
   * Sets the current URL being displayed.
   */
  public void setPage(String url) throws IOException
  {
    setPage(new URL(url));
  }

  /**
   * Sets the current URL being displayed.
   */
  public void setPage(URL page) throws IOException
  {
    if (page == null)
      throw new IOException("invalid url");

    URL old = getPage();
    // Only reload if the URL doesn't point to the same file.
    // This is not the same as equals because there might be different
    // URLs on the same file with different anchors.
    if (old == null || ! old.sameFile(page))
      {
        InputStream in = getStream(page);
        if (editorKit != null)
          {
            Document doc = editorKit.createDefaultDocument();
            doc.putProperty(Document.StreamDescriptionProperty, page);

            if (loader != null)
              loader.cancel();
            loader = new PageLoader(doc, in, old, page);

            int prio = -1;
            if (doc instanceof AbstractDocument)
              {
                AbstractDocument aDoc = (AbstractDocument) doc;
                prio = aDoc.getAsynchronousLoadPriority();
              }
            if (prio >= 0)
              {
                // Load asynchronously.
                setDocument(doc);
                Thread loadThread = new Thread(loader,
                                               "JEditorPane.PageLoader");
                loadThread.setDaemon(true);
                loadThread.setPriority(prio);
                loadThread.start();
              }
            else
              {
                // Load synchronously.
                loader.run();
                setDocument(doc);
              }
          }
      }
  }

  /**
   * Sets the text of the JEditorPane.  The argument t
   * is expected to be in the format of the current EditorKit.  This removes
   * the content of the current document and uses the EditorKit to read in the
   * new text.  This allows the EditorKit to handle the String rather than just
   * inserting in plain text.
   *
   * @param t the text to display in this JEditorPane
   */
  public void setText(String t)
  {
    try
    {
      // Remove the current content.
      Document doc = getDocument();
      doc.remove(0, doc.getLength());
      if (t == null || t.equals(""))
        return;

      // Let the EditorKit read the text into the Document.
      getEditorKit().read(new StringReader(t), doc, 0);
    }
    catch (BadLocationException ble)
    {
      // TODO: Don't know what to do here.
    }
    catch (IOException ioe)
    {
      // TODO: Don't know what to do here.
    }
  }

  /**
   * Add a HyperlinkListener object to this editor pane.
   *
   * @param listener the listener to add
   */
  public void addHyperlinkListener(HyperlinkListener listener)
  {
    listenerList.add(HyperlinkListener.class, listener);
  }

  /**
   * Removes a HyperlinkListener object to this editor pane.
   *
   * @param listener the listener to remove
   */
  public void removeHyperlinkListener(HyperlinkListener listener)
  {
    listenerList.remove(HyperlinkListener.class, listener);
  }

  /**
   * Returns all added HyperlinkListener objects.
   *
   * @return array of listeners
   *
   * @since 1.4
   */
  public HyperlinkListener[] getHyperlinkListeners()
  {
    return (HyperlinkListener[]) getListeners(HyperlinkListener.class);
  }
}


text:
<?php

namespace LRezek\Arachnid\Tests\Entity;
use LRezek\Arachnid\Annotation as OGM;

/**
 * @OGM\Node
 */
class UserAnnotationlessProperty
{
    /**
     * @OGM\Auto
     */
    protected $id;

    /**
     * @OGM\Property
     * @OGM\Index
     */
    protected $firstName;

    protected $prop1;
}


text:
ccflags-$(CONFIG_USB_DEBUG) := -DDEBUG

usbcore-y := usb.o hub.o hcd.o urb.o message.o driver.o
usbcore-y += config.o file.o buffer.o sysfs.o endpoint.o
usbcore-y += devio.o notify.o generic.o quirks.o devices.o
usbcore-y += port.o

usbcore-$(CONFIG_PCI)		+= hcd-pci.o
usbcore-$(CONFIG_ACPI)		+= usb-acpi.o

obj-$(CONFIG_USB)		+= usbcore.o


text:
module DbAgile
  module IO
    module YAML
      extend IO::TypeSafe

      #
      # Outputs some data as a YAML string
      #
      # @return [...] the buffer itself
      #
      def to_yaml(data, columns = nil, buffer = "", options = {})
        require 'yaml'
        ::YAML::dump(to_typesafe_relation(options[:type_system], data), buffer)
        buffer
      end
      module_function :to_yaml

      #
      # Loads some data from a yaml input. If a block is given, yields it with
      # each tuple in turn and returns nil. Otherwise returns an array of tuples.
      #
      def from_yaml(input, options = {}, &block)
        require 'yaml'
        from_typesafe_xxx(::YAML::load(input), options, &block)
      end
      module_function :from_yaml

    end # module YAML
  end # module IO
end # module DbAgile


text:
/*
 * Utils to obtain cookies, get them, and erase them. Used in utils.js when adding clickevent to the profile button.
 * Author: hearnshawj
 */

/**
 * @param {type} cookieName
 * @returns {unresolved}
 **/
let getCookie = cookieName => {
    let updatedCookieName = cookieName + "=",
        cookie = document.cookie.split(';'); // Obtain the cookie
    for (var i = 0; i < cookie.length; i++) {
        let co = cookie[i];
        while (co.charAt(0) == ' ') co = co.substring(1, co.length);
        if (co.indexOf(updatedCookieName) == 0) return co.substring(updatedCookieName.length, co.length);
    }
    return null; // If there's no cookie, then the length is 0 so return null.
}

let eraseCookie = cookieName =>  document.cookie = cookieName + '=; Max-Age=-99999999;'; // Func to remove cookie


text:
package org.encog.ml.svm;

/**
 * The type of SVM kernel in use.
 */
public enum KernelType {
	/**
	 * Linear kernel.
	 */
	Linear,

	/**
	 * Poly kernel.
	 */
	Poly,

	/**
	 * Radial basis function kernel.
	 */
	RadialBasisFunction,

	/**
	 * Sigmoid kernel.
	 */
	Sigmoid,

	/**
	 * Precomputed kernel.
	 */
	Precomputed
}


text:
Adding screenshots
==================

You can copy and paste images directly in Kanboard to save time.
These images are uploaded as attachments to the task.

This is especially useful for taking screenshots to describe an issue by example.

You can add screenshots directly from the board by clicking on the dropdown menu or in the task view page.

![Dropdown screenshot menu](http://kanboard.net/screenshots/documentation/dropdown-screenshot.png)

To add a new image, take your screenshot and paste with CTRL+V or Command+V:

![Screenshot page](http://kanboard.net/screenshots/documentation/task-screenshot.png)

On Mac OS X, you can use those shortcuts to take screenshots:

- Command-Control-Shift-3: Take a screenshot of the screen, and save it to the clipboard
- Command-Control-Shift-4, then select an area: Take a screenshot of an area and save it to the clipboard
- Command-Control-Shift-4, then space, then click a window: Take a screenshot of a window and save it to the clipboard

There are also several third-party applications that can be used to take screenshots with annotations and shapes.

**Note: This feature doesn't works with all browsers.** It doesn't work with Safari due to this bug: https://bugs.webkit.org/show_bug.cgi?id=49141


text: MathJax.Localization.addTranslation("ce","FontWarnings",{version:"2.7.5",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/ce/FontWarnings.js");


text:
require "rails_helper"

describe SectionForm do
  let(:collection) { double(Collection, id: 1) }
  let(:showcase) { double(Showcase, id: 1, collection: collection, sections: sections) }
  let(:section) { double(Section, id: 1, order: 1, item_id: 1, showcase: showcase, "order=" => true, name: "the section") }
  let(:sections) { double(build: true) }

  subject { described_class.new(section) }

  describe "validation" do
    it "raises an error if order is blank" do
      allow(section).to receive(:order).and_return(nil)
      expect { subject }.to raise_error
    end
  end

  describe "#form_url" do
    it "returns an array with the new path" do
      allow(section).to receive(:new_record?).and_return(true)
      expect(subject.form_url).to eq([showcase, section])
    end

    it "returns an array with the edit path" do
      allow(section).to receive(:new_record?).and_return(false)
      expect(subject.form_url).to eq([section])
    end
  end

  describe "#form_partial" do
    it "uses the section type class to determine type" do
      expect_any_instance_of(SectionType).to receive(:type).and_return("image")
      subject.form_partial
    end

    it "returns a the corect form for image sections" do
      allow(subject).to receive(:section_type).and_return("image")
      expect(subject.form_partial).to eq("image_form")
    end

    it "returns a the corect form for text sections" do
      allow(subject).to receive(:section_type).and_return("text")
      expect(subject.form_partial).to eq("text_form")
    end

    it "raises an error for an incorrect section" do
      allow(subject).to receive(:section_type).and_return("dsfasfasfasafafds")
      expect { subject.form_partial }.to raise_error
    end
  end

  describe "#name" do
    it "calls the section name service" do
      expect(SectionName).to receive(:call).with(section)
      subject.name
    end
  end

  describe "#collection" do
    it "returns the section collection" do
      expect(subject.collection).to eq(collection)
    end
  end

  describe "#showcase" do
    it "returns the section showcase" do
      expect(subject.showcase).to eq(showcase)
    end
  end

  describe "build_from_params" do
    let(:controller) { double(ApplicationController, params: {}) }
    let(:new_params) { { collection_id: "10", showcase_id: "20", section: { order: "1" } } }
    let(:edit_params) { { collection_id: "10", showcase_id: "20", id: "30" } }
    subject { described_class.build_from_params(controller) }

    context "new_params" do
      before(:each) do
        allow_any_instance_of(ShowcaseQuery).to receive(:public_find).with("20").and_return(showcase)
        allow_any_instance_of(SectionQuery).to receive(:build).and_return(section)

        allow(controller).to receive(:params).and_return(new_params)
      end

      it "finds the object from showcase" do
        expect_any_instance_of(ShowcaseQuery).to receive(:public_find).with("20").and_return(showcase)
        subject
      end

      it "builds the section from showcase" do
        expect_any_instance_of(SectionQuery).to receive(:build).and_return(section)
        subject
      end

      it "sets the order" do
        expect(section).to receive(:order=)
        subject
      end

      it "returns a new instance of SectionForm" do
        expect(subject).to be_a(SectionForm)
      end
    end

    context "edit_params" do
      before(:each) do
        allow_any_instance_of(SectionQuery).to receive(:find).with("30").and_return(section)

        allow(controller).to receive(:params).and_return(edit_params)
      end

      it "finds the obect form the section" do
        expect_any_instance_of(SectionQuery).to receive(:find).with("30").and_return(section)
        subject
      end

      it "returns a new instance of SectionForm" do
        expect(subject).to be_a(SectionForm)
      end
    end
  end
end


text:
<?php

namespace Sylius\Component\Promotion\Model;

/**
 * Promotion rule model.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class Rule implements RuleInterface
{
    /**
     * Id
     *
     * @var integer
     */
    protected $id;

    /**
     * Type
     *
     * @var string
     */
    protected $type;

    /**
     * Configuration
     *
     * @var array
     */
    protected $configuration;

    /**
     * Associated promotion
     *
     * @var PromotionInterface
     */
    protected $promotion;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->configuration = array();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * {@inheritdoc}
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfiguration()
    {
        return $this->configuration;
    }

    /**
     * {@inheritdoc}
     */
    public function setConfiguration(array $configuration)
    {
        $this->configuration = $configuration;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getPromotion()
    {
        return $this->promotion;
    }

    /**
     * {@inheritdoc}
     */
    public function setPromotion(PromotionInterface $promotion = null)
    {
        $this->promotion = $promotion;

        return $this;
    }
}


text:
package com.github.ruananswer.statistics;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Arrays;

/**
 * Created by ruan on 16-4-22.
 */
public class QuickMedianTest {
    @Test
    public void simpleArray() {
        double[] testArray = {
                2, 1, 6, 5, 4, 3
        };
        testCorrectness(testArray);
    }

    @Test
    public void bigArray() {
        double[] testArray = new double[1000];
        for (int i = 0; i < testArray.length; i++) {
            testArray[i] = Math.random();
        }
        testCorrectness(testArray);
    }

    private void testCorrectness(double[] arr) {
        QuickMedians stat = new QuickMedians(arr);

        Arrays.sort(arr);
        double median = 0;
        if (arr.length % 2 == 0)
            median = (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2.0;
        else
            median = arr[arr.length / 2];
        Assert.assertEquals(stat.getMedian(), median, 0.001);
    }
}


text:
from decimal import Decimal, InvalidOperation
from math import sin, cos, atan2, radians, sqrt, degrees

from django.core.exceptions import ValidationError
from django.db import models
from django import forms
from django.forms.utils import flatatt
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

MAP_WIDGET = r'''

'''

class GeoLocation(object):
    """ A location represented by a latitude and longitude pair. """

    @classmethod
    def from_string(cls, string):
        if string is None:
            return GeoLocation(None, None)
        ll = string.split(',')
        if len(ll) != 2:
            raise ValidationError(
                        _('Location must be a latitude/longitude pair.')
                  )
        try:
            latitude = Decimal(ll[0].strip())
            longitude = Decimal(ll[1].strip())
            return GeoLocation(latitude, longitude)
        except InvalidOperation:
            raise ValidationError(_('Could not convert entries to decimal.'))

    def __init__(self, lat, long):
        self.latitude = lat
        self.longitude = long

    def __unicode__(self):
        if self:
            return ', '.join([str(self.latitude), str(self.longitude)])
        else:
            return ''

    def __sub__(self, loc2):
        """ Returns a 2-tuple of distance in miles and initial bearing in
        degrees.
        """
        R = 3958.8
        dlat = radians(loc2.latitude-self.latitude)
        lat1 = radians(self.latitude)
        lat2 = radians(loc2.latitude)
        dlon = radians(loc2.longitude-self.longitude)
        a = sin(dlat/2)**2+cos(lat1)*cos(lat2)*sin(dlon/2)**2
        c = 2*atan2(sqrt(a), sqrt(1-a))
        d = R*c
        bearing = atan2(sin(dlon)*cos(lat2),
                        cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(dlon))
        return d, (degrees(bearing)+360) % 360

    def __len__(self):
        if self.latitude is None or self.longitude is None:
            return 0
        else:
            return 1

class MapWidget(forms.TextInput):
    class Media:
        js = (('https://maps.googleapis.com/maps/api/'
               'js?key=AIzaSyBcW7EQwfPZa3poz2Hr3MPllP4vjpilcLc'),)

    def render(self, name, value, attrs=None):
        if isinstance(value, GeoLocation):
            loc = value
        else:
            try:
                loc = GeoLocation.from_string(value)
            except ValidationError:
                value = None
                loc = GeoLocation(None, None)
        latitude = loc.latitude or 42.260
        longitude = loc.longitude or -83.7483
        input_html = super(MapWidget, self).render(name, value, attrs)
        widg = MAP_WIDGET % {
            'lat': latitude,
            'lng': longitude,
            'name': name,
            'is_existing': 'true' if (loc.latitude is not None) else 'false',
            'z': 10 if loc.latitude is None else 18,
        }
        return mark_safe(input_html + '\n' + unicode(self.media) + widg)

class LocationFormField(forms.CharField):
    widget = MapWidget

    def clean(self, value):
        v = super(LocationFormField, self).clean(value)
        if v is None:
            return v
        ll = value.split(',')
        if len(ll) != 2:
            raise ValidationError(
                        _('Location must be a latitude/longitude pair.')
            )
        try:
            latitude = Decimal(ll[0].strip())
            longitude = Decimal(ll[1].strip())
        except InvalidOperation:
            raise ValidationError(_('Could not convert entries to decimal.'))
        if latitude > 90 or latitude < -90:
            raise ValidationError(_('Latitude must be in [-90,90]'))
        if longitude > 180 or longitude < -180:
            raise ValidationError(_('Longitude must be in [-180,180]'))
        return v

class LocationField(models.CharField):
    """ A Location (latitude and longitude)."""

    description = _('A comma-separated pair of decimal values representing'
                    'latitude and longitude')

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 22
        super(LocationField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(LocationField, self).deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

    def from_db_value(self, value, expression, connection, context):
        return self.to_python(value)

    def to_python(self, value):
        if isinstance(value, GeoLocation):
            return value

        if value is None or value == '':
            return GeoLocation(None, None)
        # The string case
        ll = value.split(',')
        if len(ll) != 2:
            raise ValidationError(
                    "Invalid input for GeoLocation instance %s" % unicode(ll)
            )
        latitude = Decimal(ll[0].strip())
        longitude = Decimal(ll[1].strip())
        return GeoLocation(latitude, longitude)

    def get_prep_value(self, value):
        return unicode(value)

    def formfield(self, **kwargs):
        defaults = {'form_class': LocationFormField}
        defaults.update(kwargs)
        return super(LocationField, self).formfield(**defaults)


text:
from django.shortcuts import render, redirect
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.clickjacking import xframe_options_exempt
from .decorators import cors_allow_credentials
from rocketchat_auth import helpers

def home(request):
    return render(request, 'home.html')

def redirect_rocketchat(request):
    return redirect(settings.ROCKETCHAT_URL)

@cors_allow_credentials()
@xframe_options_exempt
def api(request):
    """
    Implements API for Rocket.Chat IFrame authentication
    """
    if not request.user.is_authenticated():
        return HttpResponse(status=401)

    fullname = ' '.join([request.user.first_name, request.user.last_name])\
                  .strip()

    token = helpers.create_user(
         request.user.email, fullname, request.user.username)

    return JsonResponse({
        'token': token
    })