text:
/* global app:true */

(function() {
	'use strict';

	app = app || {};

	/*app.Router = Backbone.Router.extend({
		initialize: function(opts) {
			this.main = opts.main;
			this.navView = new app.NavView();
		},
		routes: {
			'': 'index',
			'user/:id': 'showUser'
		},
		index: function() {
			this.main.html(this.navView.render().el);
		},
		showUser: function() {
			var self = this,
				user,
				experiments;

			id = parseInt(id, 10);
			function render() {
				var userView = new userView({
					model: user.toJSON(),
					collection: expermients
				});
				self.main.html(self.navView.render().el);
				self.main.append(userView.render().el);
			}

			if(id === USER.id) {
				user = new UserModel(USER);
				experimients = this.userExperiments;
				render();
			} else {
				user = new UserModel({id: id});
				experimients = new Experiments({url: "/contactos/exps"});
				user.fetch().then(function() {
					experimients.fetch().then(render);
				});
			}
		}
	});

	app.ExperimentView = Backbone.View.extend({
		tagName: "ul",
		template: _.template($("#tmpl-experimentView").html()),
		render: function() {
			this.collection.forEach(this.addExperiment, this);
			return this;
		},
		addExperiment: function(experiment) {
			this.$el.append(this.template(experiment.toJSON()));
		}
	})

	app.NavView = Backbone.View.extend({
		template: _.template($("#tmpl-navView").html()),
		render: function() {
			this.el.innerHTML = this.template(USER);
			return this;
		}
	});

	app.UserModel = Backbone.Model.extend({
		url: function() {
			return "/contactos/exps"		//return '/user-' + this.get('id') + '.json';
		}
	})

	$(document).ready(function() {
		app.router = new app.Router({
			main: $("#main")
		});
		Backbone.history.start();	//{ pushState: true });
	});*/

}());


text:
/**
 * Contains classes related to the Connected Components algorithm.
 */
package org.gradoop.flink.algorithms.gelly.connectedcomponents;

redpajama_set_name: RedPajamaGithub


text:
TESTS = test/*.js
REPORTER = spec
#REPORTER = dot

check: test

test:
	@NODE_ENV=test ./node_modules/.bin/mocha \
		--reporter $(REPORTER) \
		--timeout 300 \
		--require should \
		--growl \
		$(TESTS)

#browserify:
#	browserify src/index.js > build/container.js

#uglify: browserify
#	uglifyjs build/container.js > build/container.min.js

#build: uglify

install:
	npm install

.PHONY: test


text:
![image](screenshot.png)
#TITLE
##DESCRIPTION
##AUTHOR
Hello my name is [ebird-design](https://github.com/ebird-design) and I'd like ti say...
##LICENSE


text:
<?php

namespace Sebpro\ArtisanExt\Commands;

use Illuminate\Console\Command;
use Sebpro\ArtisanExt\ArtisanExt;

class ExtPermCheck extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'app:permcheck';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check the permissions on the storage and bootstrap/cache directories.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $permissions_array = ArtisanExt::checkPermissions();
        $count = 0;

        foreach ($permissions_array as $item => $value) {
            if ($value[key($value)] == true) {
                $count++;
                $this->info('The '.key($value).' directory is writable.');
            } else {
                $this->error('The '.key($value).' directory is not writable.');
            }
        }

        if ($count == count($permissions_array)) {
            return $this->info('All permissions are set correctly.');
        }

        return $this->error('Some of your permissions are not set correctly.
                             Check the laravel documentation for the correct '.
                            'permissions.');
    }
}


text:
// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __MEMMANLIST_H
#define __MEMMANLIST_H

#include "memmanager.hh"

#include <utility>
#include <cassert>

namespace mozart {

inline
MemoryManager& virtualMMToActualMM(MemoryManager& mm) {
  return mm;
}

////////////////////
// MemManagedList //
////////////////////

template <class T, class MM = MemoryManager&>
class MemManagedList {
private:
  struct ListNode {
    ListNode* next;
    T item;
  };
public:
  struct iterator {
    iterator(ListNode* node) : node(node) {}

    bool operator==(const iterator& other) {
      return node == other.node;
    }

    bool operator!=(const iterator& other) {
      return node != other.node;
    }

    iterator operator++() {
      node = node->next;
      return *this;
    }

    iterator operator++(int) {
      iterator result = *this;
      node = node->next;
      return result;
    }

    iterator operator+(size_t count) {
      iterator result = *this;
      while (count != 0) {
        ++result;
        --count;
      }
      return result;
    }

    T& operator*() {
      return node->item;
    }

    T* operator->() {
      return &node->item;
    }
  private:
    friend class MemManagedList<T, MM>;

    ListNode* node;
  };

  struct removable_iterator {
    removable_iterator(ListNode* node, ListNode* prev) :
      node(node), prev(prev) {}

    bool operator==(const removable_iterator& other) {
      return node == other.node;
    }

    bool operator!=(const removable_iterator& other) {
      return node != other.node;
    }

    removable_iterator operator++() {
      prev = node;
      node = node->next;
      return *this;
    }

    removable_iterator operator++(int) {
      removable_iterator result = *this;
      prev = node;
      node = node->next;
      return result;
    }

    T& operator*() {
      return node->item;
    }

    T* operator->() {
      return &node->item;
    }
  private:
    friend class MemManagedList<T, MM>;

    ListNode* node;
    ListNode* prev;
  };
public:
  MemManagedList() : first(nullptr), last(nullptr) {}

  bool empty() {
    return first == nullptr;
  }

  void push_back(MM mm, const T& item) {
    if (last == nullptr) {
      first = last = newNode(mm, nullptr, item);
    } else {
      last->next = newNode(mm, nullptr, item);
      last = last->next;
    }
  }

  template <class... Args>
  void push_back_new(MM mm, Args&&... args) {
    if (last == nullptr) {
      first = last = newNode_new(mm, nullptr, std::forward<Args>(args)...);
    } else {
      last->next = newNode_new(mm, nullptr, std::forward<Args>(args)...);
      last = last->next;
    }
  }

  void push_front(MM mm, const T& item) {
    if (last == nullptr) {
      first = last = newNode(mm, nullptr, item);
    } else {
      first = newNode(mm, first, item);
    }
  }

  template <class... Args>
  void push_front_new(MM mm, Args&&... args) {
    if (last == nullptr) {
      first = last = newNode_new(mm, nullptr, std::forward<Args>(args)...);
    } else {
      first = newNode_new(mm, first, std::forward<Args>(args)...);
    }
  }

  T pop_front(MM mm) {
    assert(!empty());
    ListNode* node = first;
    T result = node->item;
    first = node->next;
    if (first == nullptr)
      last = nullptr;
    freeNode(mm, node);
    return result;
  }

  T& front() {
    assert(!empty());
    return first->item;
  }

  T& back() {
    assert(!empty());
    return last->item;
  }

  void remove_front(MM mm) {
    assert(!empty());
    ListNode* node = first;
    first = node->next;
    if (first == nullptr)
      last = nullptr;
    freeNode(mm, node);
  }

  void clear(MM mm) {
    ListNode* node = first;

    while (node != nullptr) {
      ListNode* next = node->next;
      freeNode(mm, node);
      node = next;
    }

    first = last = nullptr;
  }

  removable_iterator remove(MM mm, removable_iterator iterator) {
    ListNode* node = iterator.node;
    internalRemove(iterator);
    freeNode(mm, node);
    return iterator;
  }

  void remove(MM mm, removable_iterator first, removable_iterator last) {
    while (first != last)
      first = remove(mm, first);
  }

  void remove_after(MM mm, iterator iter) {
    remove(removable_iterator(iter.node->next, iter.node));
  }

  void remove_after(MM mm, iterator first, iterator last) {
    remove(mm, removable_iterator(first.node->next, first.node),
           removable_iterator(last.node, nullptr /* unused */));
  }

  void splice(MM mm, MemManagedList<T, MM>& source) {
    if (last == nullptr)
      first = source.first;
    else
      last->next = source.first;

    last = source.last;
    source.first = source.last = nullptr;
  }

  void splice(MM mm, MemManagedList<T, MM>& source,
              removable_iterator& srcIterator) {
    ListNode* node = srcIterator.node;
    source.internalRemove(srcIterator);

    node->next = nullptr;

    if (last == nullptr) {
      first = last = node;
    } else {
      last->next = node;
      last = node;
    }
  }

  void insert_before(MM mm, removable_iterator& iterator, const T& item) {
    ListNode* node = newNode(mm, iterator.node, item);
    internalInsert_before(node, iterator);
  }

  template <class... Args>
  void insert_before_new(MM mm, removable_iterator& iterator, Args&&... args) {
    ListNode* node = newNode_new(mm, iterator.node,
                                 std::forward<Args>(args)...);
    internalInsert_before(node, iterator);
  }

  iterator begin() {
    return iterator(first);
  }

  iterator end() {
    return iterator(nullptr);
  }

  removable_iterator removable_begin() {
    return removable_iterator(first, nullptr);
  }

  removable_iterator removable_end() {
    return removable_iterator(nullptr, last);
  }

  /** Size of the list. O(n) operation. */
  size_t size() {
    size_t result = 0;
    for (auto iter = begin(); iter != end(); ++iter)
      result++;
    return result;
  }
private:
  void internalRemove(removable_iterator& iterator) {
    ListNode* node = iterator.node;
    ListNode* prev = iterator.prev;

    iterator.node = node->next;

    if (node == last)
      last = prev;

    if (prev == nullptr)
      first = node->next;
    else
      prev->next = node->next;
  }

  void internalInsert_before(ListNode* node, removable_iterator& iterator) {
    if (iterator.prev == nullptr)
      first = node;
    else
      iterator.prev->next = node;

    if (iterator.node == nullptr)
      last = node;

    iterator.prev = node;
  }
private:
  ListNode* newNode(MM mm, ListNode* next, const T& item) {
    ListNode* node = mallocNode(mm);
    node->next = next;
    node->item = item;
    return node;
  }

  template <class... Args>
  ListNode* newNode_new(MM mm, ListNode* next, Args&&... args) {
    ListNode* node = mallocNode(mm);
    node->next = next;
    new (&node->item) T(std::forward<Args>(args)...);
    return node;
  }

  ListNode* mallocNode(MM mm) {
    return static_cast<ListNode*>(
      virtualMMToActualMM(mm).malloc(sizeof(ListNode)));
  }

  void freeNode(MM mm, ListNode* node) {
    virtualMMToActualMM(mm).free(
      static_cast<void*>(node), sizeof(ListNode));
  }

  ListNode* first;
  ListNode* last;
};

}

#endif // __MEMMANLIST_H


text:
<?php

namespace Jordo\ProjectBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Jordo\ProjectBundle\Entity\Project
 *
 * @ORM\Table(name="project_project")
 * @ORM\Entity
 */
class Project
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    protected $title;

    /**
     * @var string $description
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    protected $description;

    /**
     * @var string $contexte
     *
     * @ORM\Column(name="contexte", type="text", nullable=true)
     */
    protected $contexte;

    /**
     * @var string $demande
     *
     * @ORM\Column(name="demande", type="text", nullable=true)
     */
    protected $demande;

    /**
     * @var float $budget
     *
     * @ORM\Column(name="budget", type="float", nullable=true)
     */
    protected $budget;

    /**
     * @var string $state
     *
     * @ORM\Column(name="state", type="string", length=30, nullable=true)
     */
    protected $state;

    /**
     * @ORM\OneToMany(targetEntity="\Jordo\ProjectBundle\Entity\State", mappedBy="project")
     * @ORM\OrderBY({"dateCreated"="DESC"})
     */
    protected $states;

    /**
     * @var datetime $dateStart
     *
     * @ORM\Column(name="date_start", type="datetime", nullable=true)
     */
    protected $dateStart;

    /**
     * @var datetime $dateCreated
     *
     * @ORM\Column(name="date_created", type="datetime", nullable=true)
     */
    protected $dateCreated;

    /**
     * @var $gantt
     *
     * @ORM\ManyToOne(targetEntity="\Jordo\GanttBundle\Entity\Gantt", inversedBy="project")
     */
    protected $gantt;

    /**
     * @var $team
     *
     * @ORM\OneToMany(targetEntity="\Jordo\ProjectBundle\Entity\Team", mappedBy="project")
     */
    protected $team;

    /**
     * @var $contact
     *
     * @ORM\ManyToOne(targetEntity="\Jordo\ContactBundle\Entity\Contact", inversedBy="project")
     */
    protected $contact;

    /**
     * @var $documents
     *
     * @ORM\OneToMany(targetEntity="\Jordo\ProjectBundle\Entity\Document", mappedBy="project")
     */
    protected $documents;

    public function __construct()
    {
        $this -> dateCreated = $this -> dateCreated ?: new \DateTime();
    }

    public function __toString()
    {
        return (string) sprintf('%03d %s', $this->id, $this->title);
    }

    public function getProgression()
    {
        return count($this->getDocuments());
    }

    public function getJeh()
    {
        $jeh = 0;
        foreach( $this->team as $team )
            $jeh += $team->getJEH();
        return $jeh;
    }

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

    /**
     * Set title
     *
     * @param string $title
     * @return Project
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set budget
     *
     * @param float $budget
     * @return Project
     */
    public function setBudget($budget)
    {
        $this->budget = $budget;

        return $this;
    }

    /**
     * Get budget
     *
     * @return float
     */
    public function getBudget()
    {
        return $this->budget;
    }

    /**
     * Set state
     *
     * @param integer $state
     * @return Project
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return integer
     */
    public function getState()
    {
        foreach( $this->states as $state )
            return $state;
    }

    /**
     * Set dateStart
     *
     * @param \DateTime $dateStart
     * @return Project
     */
    public function setDateStart($dateStart)
    {
        $this->dateStart = $dateStart;

        return $this;
    }

    /**
     * Get dateStart
     *
     * @return \DateTime
     */
    public function getDateStart()
    {
        return $this->dateStart;
    }

    /**
     * Set dateCreated
     *
     * @param \DateTime $dateCreated
     * @return Project
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;

        return $this;
    }

    /**
     * Get dateCreated
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * Add team
     *
     * @param Jordo\ProjectBundle\Entity\Team $team
     * @return Project
     */
    public function addTeam(\Jordo\ProjectBundle\Entity\Team $team)
    {
        $this->team[] = $team;

        return $this;
    }

    /**
     * Remove team
     *
     * @param Jordo\ProjectBundle\Entity\Team $team
     */
    public function removeTeam(\Jordo\ProjectBundle\Entity\Team $team)
    {
        $this->team->removeElement($team);
    }

    /**
     * Get team
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getTeam()
    {
        return $this->team;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Project
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set contact
     *
     * @param Jordo\ContactBundle\Entity\Contact $contact
     * @return Project
     */
    public function setContact(\Jordo\ContactBundle\Entity\Contact $contact = null)
    {
        $this->contact = $contact;

        return $this;
    }

    /**
     * Get contact
     *
     * @return Jordo\ContactBundle\Entity\Contact
     */
    public function getContact()
    {
        return $this->contact;
    }

    /**
     * Add documents
     *
     * @param Jordo\ProjectBundle\Entity\Document $documents
     * @return Project
     */
    public function addDocument(\Jordo\ProjectBundle\Entity\Document $documents)
    {
        $this->documents[] = $documents;

        return $this;
    }

    /**
     * Remove documents
     *
     * @param Jordo\ProjectBundle\Entity\Document $documents
     */
    public function removeDocument(\Jordo\ProjectBundle\Entity\Document $documents)
    {
        $this->documents->removeElement($documents);
    }

    /**
     * Get documents
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getDocuments()
    {
        return $this->documents;
    }

    /**
     * Set gantt
     *
     * @param Jordo\GanttBundle\Entity\Gantt $gantt
     * @return Project
     */
    public function setGantt(\Jordo\GanttBundle\Entity\Gantt $gantt = null)
    {
        $this->gantt = $gantt;

        return $this;
    }

    /**
     * Get gantt
     *
     * @return Jordo\GanttBundle\Entity\Gantt
     */
    public function getGantt()
    {
        return $this->gantt;
    }

    /**
     * Set contexte
     *
     * @param string $contexte
     * @return Project
     */
    public function setContexte($contexte)
    {
        $this->contexte = $contexte;

        return $this;
    }

    /**
     * Get contexte
     *
     * @return string
     */
    public function getContexte()
    {
        return $this->contexte;
    }

    /**
     * Set demande
     *
     * @param string $demande
     * @return Project
     */
    public function setDemande($demande)
    {
        $this->demande = $demande;

        return $this;
    }

    /**
     * Get demande
     *
     * @return string
     */
    public function getDemande()
    {
        return $this->demande;
    }

    /**
     * Add states
     *
     * @param Jordo\ProjectBundle\Entity\State $states
     * @return Project
     */
    public function addState(\Jordo\ProjectBundle\Entity\State $states)
    {
        $this->states[] = $states;

        return $this;
    }

    /**
     * Remove states
     *
     * @param Jordo\ProjectBundle\Entity\State $states
     */
    public function removeState(\Jordo\ProjectBundle\Entity\State $states)
    {
        $this->states->removeElement($states);
    }

    /**
     * Get states
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getStates()
    {
        return $this->states;
    }
}


text:
angular
  .module('<%= applicationSlug %>')
  .controller('HomeController', HomeController)

function HomeController () {
  this.viewName = 'Home'
}


text:
from a301utils.a301_readfile import download
from a301lib.cloudsat import get_geo
import glob
import os
from pathlib import Path
import sys
import json
import numpy as np
import h5py
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

rad_file='MYD021KM.A2006303.2220.006.2012078143305.h5'
geom_file='MYD03.A2006303.2220.006.2012078135515.h5'
lidar_file='2006303212128_02702_CS_2B-GEOPROF-LIDAR_GRANULE_P2_R04_E02.h5'
download(rad_file)
download(geom_file)
download(lidar_file)

# ### 1. Read in the groundtrack data

# In[2]:

lats,lons,date_times,prof_times,dem_elevation=get_geo(lidar_file)

# ### 2. use the modis corner lats and lons to clip the cloudsat lats and lons to the same region

# In[3]:

from a301utils.modismeta_read import parseMeta
metadict=parseMeta(rad_file)
corner_keys = ['min_lon','max_lon','min_lat','max_lat']
min_lon,max_lon,min_lat,max_lat=[metadict[key] for key in corner_keys]

# Find all the cloudsat points that are between the min/max by construting a logical
# True/False vector.  As with matlab, this vector can be used as an index to pick
# out those points at the indices where it evaluates to True.  Also as in matlab
# if a logical vector is passed to a numpy function like sum, the True values are
# cast to 1 and the false values are cast to 0, so summing a logical vector tells
# you the number of true values.

# In[4]:

lon_hit=np.logical_and(lons>min_lon,lons<max_lon)
lat_hit = np.logical_and(lats>min_lat,lats< max_lat)
in_box=np.logical_and(lon_hit,lat_hit)
print("ground track has {} points, we've selected {}".format(len(lon_hit),np.sum(in_box)) )
box_lons,box_lats=lons[in_box],lats[in_box]

# ### 3. Reproject MYD021KM channel 1 to a lambert azimuthal projection
#
# If we are on OSX we can run the a301utils.modis_to_h5 script to turn
# the h5 level 1b files into a pyresample projected file for channel 1
# by running python using the os.system command
#
# If we are on windows, a201utils.modis_to_h5 needs to be run in
# the pyre environment in a separate shell

# In[9]:

from a301lib.modis_reproject import make_projectname
reproject_name=make_projectname(rad_file)
reproject_path = Path(reproject_name)

if reproject_path.exists():
        print('using reprojected h5 file {}'.format(reproject_name))
else: #need to create reproject.h5 for channel 1
    channels='-c 1 4 3 31'
    template='python -m a301utils.modis_to_h5 {} {} {}'
    command=template.format(rad_file,geom_file,channels)
    if 'win' in sys.platform[:3]:
       print('platform is {}, need to run modis_to_h5.py in new environment'
          .format(sys.platform))
       print('open an msys terminal and run \n{}\n'.format(command))
    else: #osx, so presample is available
        print('running \n{}\n'.format(command))
        out=os.system(command)
        the_size=reproject_path.stat().st_size
        print('generated reproject file for 4 channels, size is {} bytes'.format(the_size))

# ###  read in the chan1 read in the basemap argument string and turn it  into a dictionary of basemap arguments using json.loads

# In[6]:

with h5py.File(reproject_name,'r') as h5_file:
    basemap_args=json.loads(h5_file.attrs['basemap_args'])
    chan1=h5_file['channels']['1'][...]
    geo_string = h5_file.attrs['geotiff_args']
    geotiff_args = json.loads(geo_string)

print('basemap_args: \n{}\n'.format(basemap_args))
print('geotiff_args: \n{}\n'.format(geotiff_args))

# In[7]:

get_ipython().magic('matplotlib inline')
from matplotlib import cm
from matplotlib.colors import Normalize

cmap=cm.autumn  #see http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
cmap.set_over('w')
cmap.set_under('b',alpha=0.2)
cmap.set_bad('0.75') #75% grey

plt.close('all')
fig,ax = plt.subplots(1,1,figsize=(14,14))
#
# set up the Basemap object
#
basemap_args['ax']=ax
basemap_args['resolution']='c'
bmap = Basemap(**basemap_args)
#
# transform the ground track lons/lats to x/y
#
cloudsatx,cloudsaty=bmap(box_lons,box_lats)
#
# plot as blue circles
#
bmap.plot(cloudsatx,cloudsaty,'bo')
#
# now plot channel 1
#
num_meridians=180
num_parallels = 90
col = bmap.imshow(chan1, origin='upper',cmap=cmap, vmin=0, vmax=0.4)

lon_sep, lat_sep = 5,5
parallels = np.arange(-90, 90, lat_sep)
meridians = np.arange(0, 360, lon_sep)
bmap.drawparallels(parallels, labels=[1, 0, 0, 0],
                       fontsize=10, latmax=90)
bmap.drawmeridians(meridians, labels=[0, 0, 0, 1],
                       fontsize=10, latmax=90)
bmap.drawcoastlines()
colorbar=fig.colorbar(col, shrink=0.5, pad=0.05,extend='both')
colorbar.set_label('channel1 reflectivity',rotation=-90,verticalalignment='bottom')
_=ax.set(title='vancouver')

# ### write the groundtrack out for future use

# In[8]:

groundtrack_name = reproject_name.replace('reproject','groundtrack')
print('writing groundtrack to {}'.format(groundtrack_name))
box_times=date_times[in_box]
#
# h5 files can't store dates, but they can store floating point
# seconds since 1970, which is called POSIX timestamp
#
timestamps = [item.timestamp() for item in box_times]
timestamps= np.array(timestamps)
with h5py.File(groundtrack_name,'w') as groundfile:
    groundfile.attrs['cloudsat_filename']=lidar_file
    groundfile.attrs['modis_filename']=rad_file
    groundfile.attrs['reproject_filename']=reproject_name
    dset=groundfile.create_dataset('cloudsat_lons',box_lons.shape,box_lons.dtype)
    dset[...] = box_lons[...]
    dset.attrs['long_name']='cloudsat longitude'
    dset.attrs['units']='degrees East'
    dset=groundfile.create_dataset('cloudsat_lats',box_lats.shape,box_lats.dtype)
    dset[...] = box_lats[...]
    dset.attrs['long_name']='cloudsat latitude'
    dset.attrs['units']='degrees North'
    dset= groundfile.create_dataset('cloudsat_times',timestamps.shape,timestamps.dtype)
    dset[...] = timestamps[...]
    dset.attrs['long_name']='cloudsat UTC datetime timestamp'
    dset.attrs['units']='seconds since Jan. 1, 1970'

# If I do
#
# python -m a301utils.h5dump MYD021KM.A2006303.2220.006.groundtrack.h5
#
# I get (where dtype=f4 means 4 byte (32 bit) float and dtype=f8 means 8 byte (32 bit) float):
#
#     ++++++++++++++++++++
#     found the following top-level items:
#     cloudsat_lats: <HDF5 dataset "cloudsat_lats": shape (2305,), type "<f4">
#     cloudsat_lons: <HDF5 dataset "cloudsat_lons": shape (2305,), type "<f4">
#     cloudsat_times: <HDF5 dataset "cloudsat_times": shape (2305,), type "<f8">
#     ++++++++++++++++++++
#     _______________
#     root group object <HDF5 dataset "cloudsat_lats": shape (2305,), type "<f4">
#     _______________
#         long_name: cloudsat latitude
#         units: degrees North
#     _______________
#     root group object <HDF5 dataset "cloudsat_lons": shape (2305,), type "<f4">
#     _______________
#         long_name: cloudsat longitude
#         units: degrees East
#     _______________
#     root group object <HDF5 dataset "cloudsat_times": shape (2305,), type "<f8">
#     _______________
#         long_name: cloudsat UTC datetime timestamp
#         units: seconds since Jan. 1, 1970
#     -------------------
#     attributes for the root file
#     -------------------
#     attribute name:  cloudsat_filename --- value:  2006303212128_02702_CS_2B-GEOPROF-LIDAR_GRANULE_P2_R04_E02.h5
#     attribute name:  modis_filename --- value:  MYD021KM.A2006303.2220.006.2012078143305.h5
#     attribute name:  reproject_filename --- value:  MYD021KM.A2006303.2220.006.reproject.h5
#
#

# In[ ]:


text:
var CACHE_MAX_SIZE = 5000;

var ORDER_STATUS = {
  SENT: "SENT", // not used in MT4 or backtest mode
  PENDING: "PENDING",
  OPENED: "OPENED",
  CLOSE_SENT: "CLOSE_SENT", // not used in MT4 or backtest mode
  CLOSING: "CLOSING", // not used in MT4 mode
  CLOSED: "CLOSED",
  CANCEL_SENT: "CANCEL_SENT", // not used in MT4 or backtest mode
  CANCELLED: "CANCELLED",
  UNKNOWN: "UNKNOWN"
};

var ORDER_EVENT = {
  SENT: "SENT",
  RECEIVED: "RECEIVED",
  OPENED: "OPENED",
  CLOSE_SENT: "CLOSE_SENT",
  CLOSE_RECEIVED: "CLOSE_RECEIVED",
  PARTIALLY_CLOSED: "PARTIALLY_CLOSED",
  CLOSED: "CLOSED",
  CANCEL_SENT: "CANCEL_SENT",
  CANCELLED: "CANCELLED"
};

var ORDER_SIDE = {
  BUY: 'buy',
  SELL: 'sell'
};

// moving average method
var MOVING_AVERAGE_METHOD = {
  SMA: 0,
  EMA: 1,
  SMMA: 2,
  LWMA: 3
};

var getPriceFromHistoData = function (histoData, appliedPrice) {
  return histoData.map(APPLIED_PRICE[appliedPrice]);
};

// Applied price
var APPLIED_PRICE = {
  PRICE_CLOSE: 0,
  PRICE_OPEN: 1,
  PRICE_HIGH: 2,
  PRICE_LOW: 3,
  PRICE_MEDIAN: 4,
  PRICE_TYPICAL: 5,
  PRICE_WEIGHTED: 6
};

APPLIED_PRICE[APPLIED_PRICE.PRICE_CLOSE] = function (data) {
  return data.close
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_OPEN] = function (data) {
  return data.open
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_HIGH] = function (data) {
  return data.high
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_LOW] = function (data) {
  return data.low
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_MEDIAN] = function (data) {
  return (data.high + data.low) / 2
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_TYPICAL] = function (data) {
  return (data.high + data.low + data.close) / 3
};
APPLIED_PRICE[APPLIED_PRICE.PRICE_WEIGHTED] = function (data) {
  return (data.high + data.low + 2 * data.close) / 4
};

var getInterval = function (intervalName) {
  return {
    periodicity: parseInt(intervalName.substring(1)),
    periodicityUnit: {S: 1000, M: 60000, H: 3600000, D: 86400000}[intervalName.charAt(0)],
    inMillis: function () {
      return this.periodicity * this.periodicityUnit
    }
  };
};

var random = function (seed, iteration) {
  var x = Math.sin(seed * iteration) * 10000;
  return x - Math.floor(x);
};


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('grapher_admin', '0029_auto_20180201_0923'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='chart',
            unique_together=set([]),
        ),
        migrations.RemoveField(
            model_name='chart',
            name='name',
        ),
        migrations.RemoveField(
            model_name='chart',
            name='notes',
        ),
        migrations.RemoveField(
            model_name='chart',
            name='origin_url',
        ),
        migrations.RemoveField(
            model_name='chart',
            name='published',
        ),
        migrations.RemoveField(
            model_name='chart',
            name='slug',
        ),
        migrations.RemoveField(
            model_name='chart',
            name='type',
        ),
    ]


text:
package Paws::SSM::ListInventoryEntriesResult;
  use Moose;
  has CaptureTime => (is => 'ro', isa => 'Str');
  has Entries => (is => 'ro', isa => 'ArrayRef[Paws::SSM::InventoryItemEntry]');
  has InstanceId => (is => 'ro', isa => 'Str');
  has NextToken => (is => 'ro', isa => 'Str');
  has SchemaVersion => (is => 'ro', isa => 'Str');
  has TypeName => (is => 'ro', isa => 'Str');

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::SSM::ListInventoryEntriesResult

=head1 ATTRIBUTES

=head2 CaptureTime => Str

The time that inventory information was collected for the instance(s).

=head2 Entries => ArrayRef[L<Paws::SSM::InventoryItemEntry>]

A list of inventory items on the instance(s).

=head2 InstanceId => Str

The instance ID targeted by the request to query inventory information.

=head2 NextToken => Str

The token to use when requesting the next set of items. If there are no
additional items to return, the string is empty.

=head2 SchemaVersion => Str

The inventory schema version used by the instance(s).

=head2 TypeName => Str

The type of inventory item returned by the request.

=head2 _request_id => Str

=cut

1;


text:
<?xml version="1.0" encoding="utf-8"?>
<!--191 Student Loan Pre-Claims and Claims-->
<TransactionSpecification TransactionSetIdentifierCode="191" xmlns="http://tempuri.org/X12ParserSpecification.xsd">
  <Segment SegmentId="BGN" />
  <Loop LoopId="ENT">
    <Name>Entity</Name>
    <StartingSegment SegmentId="ENT" />
    <Segment SegmentId="IN2" />
    <Segment SegmentId="N3" />
    <Segment SegmentId="N4" />
    <Segment SegmentId="PER" />
    <Segment SegmentId="DMG" />
    <Segment SegmentId="DMA" />
    <Segment SegmentId="DTP" />
    <Segment SegmentId="YNQ" />
    <Segment SegmentId="ENR" />
    <Loop LoopId="IN1">
      <Name>Individual Identification</Name>
      <StartingSegment SegmentId="IN1" />
      <Segment SegmentId="IN2" />
      <Segment SegmentId="N3" />
      <Segment SegmentId="N4" />
      <Segment SegmentId="PER" />
      <Segment SegmentId="DTP" />
      <Segment SegmentId="YNQ" />
    </Loop>
    <Loop LoopId="REF">
      <Name>Reference Identification</Name>
      <StartingSegment SegmentId="REF" />
      <Segment SegmentId="SLI" />
      <Segment SegmentId="GR" />
      <Segment SegmentId="DEF" />
      <Segment SegmentId="YNQ" />
      <Segment SegmentId="DB" />
      <Segment SegmentId="DTP" />
      <Segment SegmentId="AMT" />
      <Loop LoopId="IN1">
        <Name>Individual Identification</Name>
        <StartingSegment SegmentId="IN1" />
        <Segment SegmentId="IN2" />
        <Segment SegmentId="N3" />
        <Segment SegmentId="N4" />
        <Segment SegmentId="PER" />
        <Segment SegmentId="YNQ" />
      </Loop>
    </Loop>
  </Loop>
</TransactionSpecification>


text:
module Megam
    class BalancesCollection
        include Enumerable

        attr_reader :iterator
        def initialize
            @balance = Array.new
            @balance_by_name = Hash.new
            @insert_after_idx = nil
        end

        def all_balance
            @balance
        end

        def [](index)
            @balance[index]
        end

        def []=(index, arg)
            is_megam_balance(arg)
            @balance[index] = arg
            @balance_by_name[arg.id] = index
        end

        def <<(*args)
            args.flatten.each do |a|
                is_megam_balance(a)
                @balance << a
                @balance_by_name[a.id] =@balance.length - 1
            end
            self
        end

        # 'push' is an alias method to <<
        alias_method :push, :<<

        def insert(balance)
            is_megam_balance(balance)
            if @insert_after_idx
                # in the middle of executing a run, so any predefs inserted now should
                # be placed after the most recent addition done by the currently executing
                # balance
                @balance.insert(@insert_after_idx + 1, balance)
                # update id -> location mappings and register new balance
                @balance_by_name.each_key do |key|
                    @balance_by_name[key] += 1 if@balance_by_name[key] > @insert_after_idx
                end
                @balance_by_name[balance.id] = @insert_after_idx + 1
                @insert_after_idx += 1
            else
                @balance << balance
                @balance_by_name[balance.id] =@balance.length - 1
            end
        end

        def each
            @balance.each do |balance|
                yield balance
            end
        end

        def each_index
            @balance.each_index do |i|
                yield i
            end
        end

        def empty?
            @balance.empty?
        end

        def lookup(balance)
            lookup_by = nil
            if balance.kind_of?(Megam::Balances)
                lookup_by = balance.id
            elsif balance.kind_of?(String)
                lookup_by = balance
            else
                raise ArgumentError, "Must pass a Megam::Balance or String to lookup"
            end
            res =@balance_by_name[lookup_by]
            unless res
                raise ArgumentError, "Cannot find a balance matching #{lookup_by} (did you define it first?)"
            end
            @balance[res]
        end

        def to_s
            @balance.join(", ")
        end

        def for_json
            to_a.map { |item| item.to_s }
        end

        def to_json(*a)
            Megam::JSONCompat.to_json(for_json, *a)
        end

        def self.json_create(o)
            collection = self.new()
            o["results"].each do |balance_list|
                balance_array = balance_list.kind_of?(Array) ? balance_list : [ balance_list ]
                balance_array.each do |balance|
                    collection.insert(balance)
                end
            end
            collection
        end

        private

        def is_megam_balance(arg)
            unless arg.kind_of?(Megam::Balances)
                raise ArgumentError, "Members must be Megam::balance's"
            end
            true
        end
    end
end


text:
<?php

class Ai1wm_Not_Readable_Exception extends Exception {

}


text:
(function() {
  var Processor, makeQuadVBO, root,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  makeQuadVBO = function(texture) {
    var vbo;
    if (texture == null) {
      texture = null;
    }
    vbo = new cofgl.VertexBufferObject('TRIANGLES', 6);
    vbo.addBuffer('aVertexPosition', 3, [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]);
    if (texture != null) {
      vbo.addBuffer('aTextureCoord', 2, texture.scaleCoords([1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]));
    } else {
      vbo.addBuffer('aTextureCoord', 2, [1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]);
    }
    vbo.upload();
    return vbo;
  };

  Processor = (function(_super) {
    __extends(Processor, _super);

    Processor.withStack('processor');

    function Processor(shader, fbo) {
      if (fbo == null) {
        fbo = null;
      }
      this.shader = shader;
      if (fbo) {
        this.fbo = fbo;
        this.fboManaged = false;
      } else {
        this.fbo = new cofgl.FrameBufferObject;
        this.fboManaged = true;
      }
      this.vbo = makeQuadVBO(this.fbo.texture);
    }

    Processor.prototype.destroy = function() {
      if (this.fboManaged) {
        this.fbo.destroy();
      }
      return this.vbo.destroy();
    };

    Processor.prototype.bind = function() {
      return this.fbo.push();
    };

    Processor.prototype.unbind = function() {
      this.fbo.pop();
      return this.draw();
    };

    Processor.prototype.draw = function() {
      var gl;
      gl = cofgl.engine.gl;
      this.shader.push();
      gl.clearColor(1.0, 1.0, 1.0, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      this.fbo.texture.push();
      this.vbo.draw();
      this.fbo.texture.pop();
      return this.shader.pop();
    };

    return Processor;

  })(cofgl.ContextObject);

  root = self.cofgl != null ? self.cofgl : self.cofgl = {};

  root.makeQuadVBO = makeQuadVBO;

  root.Processor = Processor;

}).call(this);


text:
namespace Browsio.Domain
{
    using Incoding.CQRS;

    public class ConfirUserCommand : CommandBase
    {
        public string UserId { get; set; }

        public override void Execute()
        {
            User user = this.Repository.GetById<User>(this.UserId);
            user.Activated = true;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.fop.pdf (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.fop.pdf

Interfaces

PDFColorSpace

PDFEncryption

PDFImage

PDFWritable

RefPDFFont

StreamCache

StructureType

Classes

AbstractPDFFontStream

AbstractPDFStream

AlphaRasterImage

ASCII85Filter

ASCIIHexFilter

BitmapImage

CCFFilter

CMapBuilder

DCTFilter

DestinationComparator

FlateFilter

InMemoryStreamCache

NullFilter

ObjectStream

PDFAction

PDFAnnotList

PDFArray

PDFCFFStream

PDFCFFStreamType0C

PDFCharProcs

PDFCIDFont

PDFCIDFontDescriptor

PDFCIDSystemInfo

PDFCIELabColorSpace

PDFCMap

PDFColor

PDFColorHandler

PDFDestination

PDFDests

PDFDeviceColorSpace

PDFDictionary

PDFDocument

PDFDPart

PDFDPartRoot

PDFEmbeddedFile

PDFEmbeddedFiles

PDFEncoding

PDFEncryptionJCE

PDFEncryptionManager

PDFEncryptionParams

PDFFactory

PDFFileSpec

PDFFilter

PDFFilterList

PDFFont

PDFFontDescriptor

PDFFontNonBase14

PDFFontTrueType

PDFFontType0

PDFFontType1

PDFFontType3

PDFFormXObject

PDFFunction

PDFGoTo

PDFGoToRemote

PDFGState

PDFICCBasedColorSpace

PDFICCStream

PDFIdentifiedDictionary

PDFImageXObject

PDFInfo

PDFInternalLink

PDFJavaScriptLaunchAction

PDFLaunch

PDFLayer

PDFLayer.Resolver

PDFLinearization

PDFLink

PDFMetadata

PDFName

PDFNames

PDFNameTreeNode

PDFNavigator

PDFNavigator.Resolver

PDFNavigatorAction

PDFNull

PDFNumber

PDFNumberTreeNode

PDFNumsArray

PDFObject

PDFObjectNumber

PDFOutline

PDFOutputIntent

PDFPage

PDFPageLabels

PDFPages

PDFPaintingState

PDFParentTree

PDFPathPaint

PDFPattern

PDFProfile

PDFRectangle

PDFReference

PDFResourceContext

PDFResources

PDFRoot

PDFSeparationColorSpace

PDFSetOCGStateAction

PDFSetOCGStateAction.Resolver

PDFShading

PDFStream

PDFStructElem

PDFStructElem.Placeholder

PDFStructTreeRoot

PDFT1Stream

PDFText

PDFTextUtil

PDFToUnicodeCMap

PDFTransitionAction

PDFTransitionAction.Resolver

PDFTTFStream

PDFUri

PDFWArray

PDFXObject

StandardStructureAttributes

StandardStructureAttributes.Table

StandardStructureTypes

StandardStructureTypes.Grouping

StandardStructureTypes.Illustration

StandardStructureTypes.InlineLevelStructure

StandardStructureTypes.List

StandardStructureTypes.Paragraphlike

StandardStructureTypes.RubyOrWarichu

StandardStructureTypes.Table

StreamCacheFactory

StructureHierarchyMember

TempFileStreamCache

TransitionDictionary

VersionController

Enums

PDFAMode

PDFInfo.StandardKey

PDFUAMode

PDFVTMode

PDFXMode

StandardStructureAttributes.Table.Scope

Version

Exceptions

PDFConformanceException

PDFFilterException

TransparencyDisallowedException


text:
ACCOUNT=$USER@google.com
PROJECT=70795436982
BUCKET=gce-scripts
gcloud config set account $ACCOUNT
gcloud config set project $PROJECT
gsutil cp gee.sh gs://$BUCKET/gee.sh
# TODO(sub) auto-generate sample log and provide a flag to do skip it
gsutil cp gee_sample_log.txt gs://$BUCKET/gee_sample_log.txt
gsutil setmeta  -h "Cache-Control:public, max-age=0, no-transform" gs://$BUCKET/gee.sh gs://$BUCKET/gee_sample_log.txt
gsutil acl set public-read gs://$BUCKET/gee.sh gs://$BUCKET/gee_sample_log.txt


text:
package org.hisp.dhis.common;

import java.util.Date;
import java.util.Set;

import org.hisp.dhis.analytics.AggregationType;
import org.hisp.dhis.analytics.SortOrder;
import org.hisp.dhis.analytics.UserOrgUnitType;

public class DataQueryRequest
{
    protected Set<String> dimension;

    protected Set<String> filter;

    protected AggregationType aggregationType;

    protected String measureCriteria;

    protected String preAggregationMeasureCriteria;

    protected Date startDate;

    protected Date endDate;

    protected SortOrder order;

    protected String timeField;

    protected String orgUnitField;

    protected boolean skipMeta;

    protected boolean skipData;

    protected boolean skipRounding;

    protected boolean completedOnly;

    protected boolean hierarchyMeta;

    protected boolean ignoreLimit;

    protected boolean hideEmptyRows;

    protected boolean hideEmptyColumns;

    protected boolean showHierarchy;

    protected boolean includeNumDen;

    protected boolean includeMetadataDetails;

    protected boolean duplicatesOnly;

    protected DisplayProperty displayProperty;

    protected IdScheme outputIdScheme;

    protected IdScheme outputDataElementIdScheme;

    protected IdScheme outputOrgUnitIdScheme;

    protected IdScheme inputIdScheme;

    protected String approvalLevel;

    protected Date relativePeriodDate;

    protected String userOrgUnit;

    protected UserOrgUnitType userOrgUnitType;

    protected DhisApiVersion apiVersion;

    public Set<String> getDimension()
    {
        return dimension;
    }

    public Set<String> getFilter()
    {
        return filter;
    }

    public AggregationType getAggregationType()
    {
        return aggregationType;
    }

    public String getMeasureCriteria()
    {
        return measureCriteria;
    }

    public String getPreAggregationMeasureCriteria()
    {
        return preAggregationMeasureCriteria;
    }

    public Date getStartDate()
    {
        return startDate;
    }

    public Date getEndDate()
    {
        return endDate;
    }

    public SortOrder getOrder()
    {
        return order;
    }

    public String getTimeField()
    {
        return timeField;
    }

    public String getOrgUnitField()
    {
        return orgUnitField;
    }

    public boolean isSkipMeta()
    {
        return skipMeta;
    }

    public boolean isSkipData()
    {
        return skipData;
    }

    public boolean isSkipRounding()
    {
        return skipRounding;
    }

    public boolean isCompletedOnly()
    {
        return completedOnly;
    }

    public boolean isHierarchyMeta()
    {
        return hierarchyMeta;
    }

    public boolean isIgnoreLimit()
    {
        return ignoreLimit;
    }

    public boolean isHideEmptyRows()
    {
        return hideEmptyRows;
    }

    public boolean isHideEmptyColumns()
    {
        return hideEmptyColumns;
    }

    public boolean isShowHierarchy()
    {
        return showHierarchy;
    }

    public boolean isIncludeNumDen()
    {
        return includeNumDen;
    }

    public boolean isIncludeMetadataDetails()
    {
        return includeMetadataDetails;
    }

    public DisplayProperty getDisplayProperty()
    {
        return displayProperty;
    }

    public IdScheme getOutputIdScheme()
    {
        return outputIdScheme;
    }

    public IdScheme getOutputDataElementIdScheme()
    {
        return outputDataElementIdScheme;
    }

    public IdScheme getOutputOrgUnitIdScheme()
    {
        return outputOrgUnitIdScheme;
    }

    public IdScheme getInputIdScheme()
    {
        return inputIdScheme;
    }

    public String getApprovalLevel()
    {
        return approvalLevel;
    }

    public Date getRelativePeriodDate()
    {
        return relativePeriodDate;
    }

    public String getUserOrgUnit()
    {
        return userOrgUnit;
    }

    public UserOrgUnitType getUserOrgUnitType()
    {
        return userOrgUnitType;
    }

    public DhisApiVersion getApiVersion()
    {
        return apiVersion;
    }

    public boolean isDuplicatesOnly()
    {
        return duplicatesOnly;
    }

    public static DataQueryRequestBuilder newBuilder()
    {
        return new DataQueryRequest.DataQueryRequestBuilder();
    }

    protected DataQueryRequest()
    {
    }

    public static class DataQueryRequestBuilder
    {
        private DataQueryRequest request;

        protected DataQueryRequestBuilder()
        {
            this.request = new DataQueryRequest();
        }

        public DataQueryRequestBuilder dimension( Set<String> dimension )
        {
            this.request.dimension = dimension;
            return this;
        }

        public DataQueryRequestBuilder filter( Set<String> filter )
        {
            this.request.filter = filter;
            return this;
        }

        public DataQueryRequestBuilder aggregationType( AggregationType aggregationType )
        {
            this.request.aggregationType = aggregationType;
            return this;
        }

        public DataQueryRequestBuilder measureCriteria( String measureCriteria )
        {
            this.request.measureCriteria = measureCriteria;
            return this;
        }

        public DataQueryRequestBuilder preAggregationMeasureCriteria( String preAggregationMeasureCriteria )
        {
            this.request.preAggregationMeasureCriteria = preAggregationMeasureCriteria;
            return this;
        }

        public DataQueryRequestBuilder startDate( Date startDate )
        {
            this.request.startDate = startDate;
            return this;
        }

        public DataQueryRequestBuilder endDate( Date endDate )
        {
            this.request.endDate = endDate;
            return this;
        }

        public DataQueryRequestBuilder order( SortOrder order )
        {
            this.request.order = order;
            return this;
        }

        public DataQueryRequestBuilder timeField( String timeField )
        {
            this.request.timeField = timeField;
            return this;
        }

        public DataQueryRequestBuilder orgUnitField( String orgUnitField )
        {
            this.request.orgUnitField = orgUnitField;
            return this;
        }

        public DataQueryRequestBuilder skipMeta( boolean skipMeta )
        {
            this.request.skipMeta = skipMeta;
            return this;
        }

        public DataQueryRequestBuilder skipData( boolean skipData )
        {
            this.request.skipData = skipData;
            return this;
        }

        public DataQueryRequestBuilder skipRounding( boolean skipRounding )
        {
            this.request.skipRounding = skipRounding;
            return this;
        }

        public DataQueryRequestBuilder completedOnly( boolean completedOnly )
        {
            this.request.completedOnly = completedOnly;
            return this;
        }

        public DataQueryRequestBuilder hierarchyMeta( boolean hierarchyMeta )
        {
            this.request.hierarchyMeta = hierarchyMeta;
            return this;
        }

        public DataQueryRequestBuilder ignoreLimit( boolean ignoreLimit )
        {
            this.request.ignoreLimit = ignoreLimit;
            return this;
        }

        public DataQueryRequestBuilder hideEmptyRows( boolean hideEmptyRows )
        {
            this.request.hideEmptyRows = hideEmptyRows;
            return this;
        }

        public DataQueryRequestBuilder hideEmptyColumns( boolean hideEmptyColumns )
        {
            this.request.hideEmptyColumns = hideEmptyColumns;
            return this;
        }

        public DataQueryRequestBuilder showHierarchy( boolean showHierarchy )
        {
            this.request.showHierarchy = showHierarchy;
            return this;
        }

        public DataQueryRequestBuilder includeNumDen( boolean includeNumDen )
        {
            this.request.includeNumDen = includeNumDen;
            return this;
        }

        public DataQueryRequestBuilder includeMetadataDetails( boolean includeMetadataDetails )
        {
            this.request.includeMetadataDetails = includeMetadataDetails;
            return this;
        }

        public DataQueryRequestBuilder displayProperty( DisplayProperty displayProperty )
        {
            this.request.displayProperty = displayProperty;
            return this;
        }

        public DataQueryRequestBuilder outputIdScheme( IdScheme outputIdScheme )
        {
            this.request.outputIdScheme = outputIdScheme;
            return this;
        }

        public DataQueryRequestBuilder outputDataElementIdScheme( IdScheme outputDataElementIdScheme )
        {
            this.request.outputDataElementIdScheme = outputDataElementIdScheme;
            return this;
        }

        public DataQueryRequestBuilder outputOrgUnitIdScheme( IdScheme outputOrgUnitIdScheme )
        {
            this.request.outputOrgUnitIdScheme = outputOrgUnitIdScheme;
            return this;
        }

        public DataQueryRequestBuilder inputIdScheme( IdScheme inputIdScheme )
        {
            this.request.inputIdScheme = inputIdScheme;
            return this;
        }

        public DataQueryRequestBuilder approvalLevel( String approvalLevel )
        {
            this.request.approvalLevel = approvalLevel;
            return this;
        }

        public DataQueryRequestBuilder relativePeriodDate( Date relativePeriodDate )
        {
            this.request.relativePeriodDate = relativePeriodDate;
            return this;
        }

        public DataQueryRequestBuilder userOrgUnit( String userOrgUnit )
        {
            this.request.userOrgUnit = userOrgUnit;
            return this;
        }

        public DataQueryRequestBuilder userOrgUnitType( UserOrgUnitType userOrgUnitType )
        {
            this.request.userOrgUnitType = userOrgUnitType;
            return this;
        }

        public DataQueryRequestBuilder apiVersion( DhisApiVersion apiVersion )
        {
            this.request.apiVersion = apiVersion;
            return this;
        }

        public DataQueryRequestBuilder duplicatesOnly( boolean duplicatesOnly )
        {
            this.request.duplicatesOnly = duplicatesOnly;
            return this;
        }

        public DataQueryRequest build()
        {
            return request;
        }

        public DataQueryRequestBuilder fromCriteria( AggregateAnalyticsQueryCriteria criteria )
        {
            this.request.aggregationType = criteria.getAggregationType();
            this.request.approvalLevel = criteria.getApprovalLevel();
            this.request.completedOnly = criteria.isCompletedOnly();
            this.request.dimension = criteria.getDimension();
            this.request.displayProperty = criteria.getDisplayProperty();
            this.request.endDate = criteria.getEndDate();
            this.request.filter = criteria.getFilter();
            this.request.hideEmptyColumns = criteria.isHideEmptyColumns();
            this.request.hideEmptyRows = criteria.isHideEmptyRows();
            this.request.hierarchyMeta = criteria.isHierarchyMeta();
            this.request.ignoreLimit = criteria.isIgnoreLimit();
            this.request.includeMetadataDetails = criteria.isIncludeMetadataDetails();
            this.request.includeNumDen = criteria.isIncludeNumDen();
            this.request.inputIdScheme = criteria.getInputIdScheme();
            this.request.measureCriteria = criteria.getMeasureCriteria();
            this.request.order = criteria.getOrder();
            this.request.orgUnitField = criteria.getOrgUnitField();
            this.request.outputIdScheme = criteria.getOutputIdScheme();
            this.request.outputOrgUnitIdScheme = criteria.getOutputOrgUnitIdScheme();
            this.request.outputDataElementIdScheme = criteria.getOutputDataElementIdScheme();
            this.request.preAggregationMeasureCriteria = criteria.getPreAggregationMeasureCriteria();
            this.request.relativePeriodDate = criteria.getRelativePeriodDate();
            this.request.showHierarchy = criteria.isShowHierarchy();
            this.request.skipData = criteria.isSkipData();
            this.request.skipMeta = criteria.isSkipMeta();
            this.request.skipRounding = criteria.isSkipRounding();
            this.request.startDate = criteria.getStartDate();
            this.request.timeField = criteria.getTimeField();
            this.request.userOrgUnit = criteria.getUserOrgUnit();
            this.request.userOrgUnitType = criteria.getUserOrgUnitType();
            return this;
        }
    }

}


text:
#ifndef __ENV
#define __ENV

#include <x86.h>
#include <util.h>
#include <trap.h>

// An environment ID 'envid_t' has three parts:
//
// +1+---------------21-----------------+--------10--------+
// |0|          Uniqueifier             |   Environment    |
// | |                                  |      Index       |
// +------------------------------------+------------------+
//                                       \--- ENVX(eid) --/
//
// The environment index ENVX(eid) equals the environment's offset in the
// 'envs[]' array.  The uniqueifier distinguishes environments that were
// created at different times, but share the same environment index.
//
// All real environments are greater than 0 (so the sign bit is zero).
// envid_ts less than 0 signify errors.  The envid_t == 0 is special, and
// stands for the current environment.

#define LOG2NENV		10
//	max simultaneously active envs
#define NENV			(1 << LOG2NENV)
#define ENVX(envid)		((envid) & (NENV - 1))

// Values of env_status in struct Env
enum {
	ENV_FREE = 0,		// inactive, on nev_free_list
	ENV_DYING,			// zombie
	ENV_RUNNABLE,
	ENV_RUNNING,
	ENV_NOT_RUNNABLE
};

// Special environment types
enum EnvType {
	ENV_TYPE_USER = 0,
	ENV_TYPE_FS,		// File system server
};

struct Env {
	struct Trapframe env_tf;	// Saved registers
	struct Env *env_link;		// Next free Env
	envid_t env_id;			// Unique environment identifier
	envid_t env_parent_id;		// env_id of this env's parent
	enum EnvType env_type;		// Indicates special system environments
	unsigned env_status;		// Status of the environment
	uint32_t env_runs;		// Number of times environment has run
	int env_cpunum;			// The CPU that the env is running on

	// Address space
	pde_t *env_pgdir;		// Kernel virtual address of page dir

	// Exception handling
	void *env_pgfault_upcall;	// Page fault upcall entry point

	bool env_ipc_recving;		// Env is blocked receiving
	void *env_ipc_dstva;		// VA at which to map received page
	uint32_t env_ipc_value;		// Data value sent to us
	envid_t env_ipc_from;		// envid of the sender
	int env_ipc_perm;		// Perm of page mapping received
};

#ifndef	__FOR_USER__

extern struct Env *envs;		// All environments
extern struct Env *curenv;		// Current environment
extern struct Segdesc gdt[];

void	env_init(void);
void	env_init_percpu(void);
int		env_alloc(struct Env **e, envid_t parent_id);
void	env_free(struct Env *e);
void	env_create(uint8_t *binary, enum EnvType type);
void	env_destroy(struct Env *e);	// Does not return if e == curenv

int		envid2env(envid_t envid, struct Env **env_store, bool checkperm);

// The following two functions do not return
void	env_run(struct Env *e) __attribute__((noreturn));
void	env_pop_tf(struct Trapframe *tf) __attribute__((noreturn));

// For test prupose
int 	env_shit_create(uintptr_t entry);

// Without this extra macro, we couldn't pass macros like TEST to
// ENV_CREATE because of the C pre-processor's argument prescan rule.
#define ENV_PASTE3(x, y, z) x ## y ## z

#define ENV_CREATE(x, type)						\
	do {								\
		extern uint8_t ENV_PASTE3(_binary_, x, _start)[];	\
		env_create(ENV_PASTE3(_binary_, x, _start),		\
			   type);					\
	} while (0)

#endif /* __FOR_USER__ */

#endif


text:
get '/archives' do
    erb :'archive/archive'
end


text:
require 'spec_helper'

feature 'LocationFieldSets' do
  it 'create a new set, edit it, then visit index' do
    visit '/field_sets'
    click_link 'New set for locations'
    expect(page).to have_content 'Name'
    fill_in 'Name', with: 'Suppliers'
    click_button 'Done'
    expect(page).to have_content 'Location field set successfully created'
    click_link 'Suppliers'
    click_link 'Edit set'
    fill_in 'Description', with: 'Electronics'
    click_button 'Done'
    expect(page).to have_content 'Location field set successfully updated'
    expect(page).to have_content 'Electronics'
  end
end


text:
package io.joern.php2cpg.datastructures

import io.joern.php2cpg.astcreation.AstCreator.NameConstants
import io.joern.x2cpg.Ast
import io.joern.x2cpg.datastructures.{Scope => X2CpgScope}
import io.shiftleft.codepropertygraph.generated.nodes.{NewLocal, NewMethod, NewNamespaceBlock, NewNode, NewTypeDecl}
import io.shiftleft.semanticcpg.language.types.structure.NamespaceTraversal
import org.slf4j.LoggerFactory

import scala.collection.mutable

class Scope extends X2CpgScope[String, NewNode, NewNode] {

  private val logger = LoggerFactory.getLogger(this.getClass)

  private var localStack: List[mutable.ArrayBuffer[NewLocal]]     = Nil
  private var constAndStaticInits: List[mutable.ArrayBuffer[Ast]] = Nil
  private var fieldInits: List[mutable.ArrayBuffer[Ast]]          = Nil
  private val anonymousMethods                                    = mutable.ArrayBuffer[Ast]()

  override def pushNewScope(scopeNode: NewNode): Unit = {
    scopeNode match {
      case _: NewMethod =>
        localStack = mutable.ArrayBuffer[NewLocal]() :: localStack
        super.pushNewScope(scopeNode)

      case _: NewTypeDecl =>
        constAndStaticInits = mutable.ArrayBuffer[Ast]() :: constAndStaticInits
        fieldInits = mutable.ArrayBuffer[Ast]() :: fieldInits
        super.pushNewScope(scopeNode)

      case _: NewNamespaceBlock =>
        super.pushNewScope(scopeNode)

      case invalid =>
        logger.warn(s"pushNewScope called with invalid node $invalid. Ignoring!")
    }
  }

  override def popScope(): Option[NewNode] = {
    val poppedScope = super.popScope()

    poppedScope match {
      case Some(_: NewMethod) =>
        // TODO This is unsafe to catch errors for now.
        localStack = localStack.tail

      case Some(_: NewTypeDecl) =>
        // TODO This is unsafe to catch errors for now
        constAndStaticInits = constAndStaticInits.tail
        fieldInits = fieldInits.tail

      case _ => // Nothing to do here
    }

    poppedScope
  }

  override def addToScope(identifier: String, variable: NewNode): NewNode = {
    variable match {
      case local: NewLocal =>
        // TODO This is unsafe to catch errors for now.
        localStack.head.addOne(local)
      case _ => // Nothing to do here
    }
    super.addToScope(identifier, variable)
  }

  def addAnonymousMethod(methodAst: Ast): Unit = anonymousMethods.addOne(methodAst)

  def getAndClearAnonymousMethods: List[Ast] = {
    val methods = anonymousMethods.toList
    anonymousMethods.clear()
    methods
  }

  def getEnclosingNamespaceName: Option[String] =
    stack.map(_.scopeNode).collectFirst { case ns: NewNamespaceBlock => ns }.map(_.name)

  def getEnclosingTypeDeclType: Option[String] =
    stack.map(_.scopeNode).collectFirst { case td: NewTypeDecl => td }.map(_.fullName)

  def getLocalsInScope: List[NewLocal] = localStack.headOption.map(_.toList).toList.flatten

  def addConstOrStaticInitToScope(ast: Ast): Unit = {
    addInitToScope(ast, constAndStaticInits)
  }
  def getConstAndStaticInits: List[Ast] = {
    getInits(constAndStaticInits)
  }

  def addFieldInitToScope(ast: Ast): Unit = {
    addInitToScope(ast, fieldInits)
  }

  def getFieldInits: List[Ast] = {
    getInits(fieldInits)
  }

  private def addInitToScope(ast: Ast, initList: List[mutable.ArrayBuffer[Ast]]): Unit = {
    // TODO This is unsafe to catch errors for now
    initList.head.addOne(ast)
  }

  private def getInits(initList: List[mutable.ArrayBuffer[Ast]]): List[Ast] = {
    // TODO This is unsafe to catch errors for now
    val ret = initList.head.toList
    // These ASTs should only be added once to avoid aliasing issues.
    initList.head.clear()
    ret
  }
}


text:
<?php

App::uses('TwimConnectionTestCase', 'Twim.TestSuite');

/**
 *
 * @property TwimTrend $Trend
 */
class TwimTrendTestCase extends TwimConnectionTestCase {

	public function setUp() {
		parent::setUp();
		$this->Trend = ClassRegistry::init('Twim.TwimTrend');
		$this->Trend->setDataSource($this->mockDatasourceName);
	}

	public function tearDown() {
		unset($this->Trend);
		parent::tearDown();
	}

	// =========================================================================

	public function testPlace() {
		$this->Trend->getDataSource()->expects($this->once())->method('request')->will($this->returnValue(array()));
		$this->Trend->find(TwimTrend::FINDTYPE_PLACE, array('id' => 1));
		$this->assertSame('1.1/trends/place', $this->Trend->request['uri']['path']);
		$this->assertSame(array('id' => 1), $this->Trend->request['uri']['query']);
	}

	// =========================================================================

	public function testAvailable() {
		$this->Trend->getDataSource()->expects($this->once())->method('request')->will($this->returnValue(array()));
		$this->Trend->find(TwimTrend::FINDTYPE_AVAILABLE);
		$this->assertSame('1.1/trends/available', $this->Trend->request['uri']['path']);
		$this->assertSame(array(), $this->Trend->request['uri']['query']);
	}

	// =========================================================================

	public function testClosest() {
		$this->Trend->getDataSource()->expects($this->once())->method('request')->will($this->returnValue(array()));
		$this->Trend->find(TwimTrend::FINDTYPE_CLOSEST);
		$this->assertSame('1.1/trends/closest', $this->Trend->request['uri']['path']);
		$this->assertSame(array(), $this->Trend->request['uri']['query']);
	}

}


text:
html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png"
)]
//!
Amazon EMR is a web service that makes it easier to process large amounts of data efficiently. Amazon EMR uses Hadoop processing combined with several AWS services to do tasks such as web indexing, data mining, log file analysis, machine learning, scientific simulation, and data warehouse management.

//!
//! If you're using the service, you're probably looking for [EmrClient](struct.EmrClient.html) and [Emr](trait.Emr.html).

mod custom;
mod generated;
pub use custom::*;
pub use generated::*;


text:
#!/usr/bin/env node

var config = {};
var debug = {};
/* Config */
/* |- Debug config */
debug.yes = true; // set this true for debug pictures/messages
debug.picture_path = "/home/kelluke/Web/phantom_test"; // I want to see pictures in web
/* |- User credenitals */
config.username = "kelluke";
config.password = "";

/* Imports */
var colors = require("colors"),
    path = require('path'),
    childProcess = require('child_process');

/* Functions */
function launchbrowser(args){
    var childArgs = [
        "--ssl-protocol=any",
        path.join(__dirname, 'browser.js')
    ];
    args.forEach(function(arg, index){
        console.log("DEBUG: " + "Arg: ".cyan + index + ": " + arg);
        childArgs.push(arg);
    });
    childProcess.execFile("/usr/bin/casperjs", childArgs, function(err, stdout, stderr) {
	if(debug.yes){
            console.log("Browser started");
            if(stdout) console.log("DEBUG: " + "CasperJS output: ".cyan + "%s".yellow, stdout);
            if(stderr) console.log("DEBUG: " + "CasperJS stderr: ".cyan + "%s".red, stderr);
            if(err) console.log("DEBUG: " + "exec err: ".cyan + "%s".red, err);
        }
    });
}
/* Main */
launchbrowser(["https://koding.com/Login", debug.yes, debug.picture_path, config.username, config.password]);


text:
**Udacity: CS 253**

---

### HTML: HyperText Markup Language

HTML documents are the heart of the web; they can do a number of things. HTML is made up of:

* Text content that you see
* Markup (what it looks like)
* References to images, videos, and other files
* Links to other HTML pages

You can experiment with HTML by going to [this website](http://jsfiddle.net/WW3bh/)!

**Plain Text**

Plain text in an HTML document is just plain text; there's nothing changed.

You can prove this by creating a new document, called `hello.html`, and filling it in like this:

    Hello, world!

If you were to open that HTML page in your browser, you'll notice that the page looks something like this:

![hello](../img/hello.png)

**Markup & Tags**

Just being able to edit plain text isn't enough though. What if we wanted bold text? That's where something called "markup" comes in. Markup is just a part of HTML that allows us to do things like make text bold, organize elements into groups, and many other things.

The way we write HTML markup is through these things called "tags". Tags look like this:

    <name>content inside tag</name>

The content inside of a tag can also contain other tags, but we won't worry about that for now. The first tag, which looked like `<name>`, is called the *opening tag*, and the second one, which has the slash inside of it, is called the *closing tag*. Here's some examples of tags: (I encourage you to try this out on your own too):

* bold: `<b>bold text</b>`
* italics: `<em>italic text</em>`
* bold and italic text: `<b><em>This text is both bold and italic because I wrapped it in two tags!</em></b>`

You have to be careful to close your tags though! If you forget to close a `<b>` tag, for example, *all* of the text that follows the `<b>` tag will be bold, even if you didn't want it to be. Things can get weird if you don't close a bunch of tags.

**Attributes**

Time to learn about a new concept! Take a look at this:

    <tag>content</tag>

Which just looks like the tags we are used to now. Now I'm going to add something new:

    <tag attribute="value">content</tag>

That thing that got plopped in the middle of the opening tag is called an *attribute*. HTML attributes have two properties:

1. A name: in the above example, I just used "attribute".
2. A value: in the above example, I just used "value".

We're going to demonstrate an example of a tag that uses attributes. These are "anchor" tags:

    Google

If you were to render this HTML in your browser, you'd see the word "Google", which you could click on to go google.com! The tag itself works the same way as before; we're just wrapping content with them. The attribute here is called `href`, and that means "HyperText Reference".

Links aren't the only tags that can have attributes, as we will continue to see:

**Images**

To display images on our web pages, we use an image tag:

There are three things I want to point out regarding image tags:

1. No closing tag: Not all elements in HTML require a closing tag. These are called "void elements", and `<img>` is our first example of one.
2. `src` attribute: This tells us the location of our image.
3. `alt` attribute: The "alternate" text is displayed if the image doesn't load.

**Whitespace**

Try rendering this in your browser:

    This HTML       has lots of
        spaces and newlines     everywhere

It may look funny, but believe it or not, it'll look like this in the browser: **This HTML has lots of spaces and newlines everywhere**

This is because all unnecessary whitespace, whether it be spaces, tabs, or newlines, is trimmed in HTML. We can force our markup to have line breaks though! This is where the `<br>` tag, or "break" tag, comes in:

    First line
Second line

Try it out! `<br>` is the HTML equivalent of `\n` in most programming languages.

**Block vs. Inline elements**

You may have noticed before that tags like `<em>` or `<b>` didn't result in any separation between words. Check it out:

    This text will be on the same line as this text.

However, let's introduce a new tag, called the "paragraph" tag, that exhibits different behavior:

One line

Second line

The `<p>` tag forces separation between text because it is a "block" element. They, by default, will be placed below elements that come before them in your markup because they get their own invisible "box" with a height and width. Essentially, they get their own line. We will talk about the spacing and other things when we get to CSS later on!

Here are a few examples of inline and block elements in HTML:

* Inline
    * `<a>`
    * `<img>`
    * `<br>`
    * `<em>`
* Block
    * `<p>`
    * `<div>`
    * `<table>`

There are two other tags to mention before we move on: `div` and `span`.

The HTML `<div>` and `<span>` tags can be considered more "generic" elements than something like `<p>` or `<b>`. Span is inline, and div is block, but what you need to remember is that they simply wrap their content and can have styles applied to them using CSS. Other elements can as well, but span and div don't do anything by default, which makes them unique.

**HTML Documents**

The last part of HTML we're going to talk about for now involves making a real HTML file! All HTML (assuming we're writing [HTML5](http://en.wikipedia.org/wiki/HTML5)) files start with this line:

    <!doctype html>

This line tells the web broswer what kind of document this is. We then need to fill in the stuff below that, and you'll recognize three new tags being used:

    <!doctype html>

Before we fill in some more stuff on our new page, let's take a step back:

1. The `<html>` tag
    * This tag surrounds the entire document (except for the doctype declaration at the top).
2. The `<head>` tag
    * This part of the document includes some metadata and links to JavaScript and CSS files.
3. The `<body>` tag
    * This is where the content goes! All of the HTML elements we were learning before would go in here.

Let's fill in the document (be sure to look up any tags that don't make sense to you, as I don't feel a need to explain any more):

    <!doctype html>

            <title>My Website</title>
            <meta charset="utf-8">
            <meta name="description" content="This is what my site's description is.">

                    This is a paragraph with some bold text!

Save that file as `index.html` and open it in a web browser: that's your first complete HTML document! There's a lot more to HTML, but this course is about back end, not front end, web development, so we don't need to go too much more in-depth into HTML.

Check out these resources to learn all about HTML5:

* [HTML5Rocks](http://html5rocks.com)
* [HTML-5-Tutorial](http://html-5-tutorial.com)
* [Dive into HTML5](http://diveintohtml5.info)

Time to move on to URLs!


text:
local mostMonthlyReward = 20		-- GC for having the most monthly tops in a month
local monthlyReward = 5				-- GC for having a monthly top
local baseTop1Reward = 5			-- Base top1 reward, multiplied with amount of months on server
local displayTopCount = 8

local times = {}					-- [top] = {forumid=forumid,mapname=mapname, value=value, date=getRealTime().timestamp, formatDate = FormatDate(getRealTime().timestamp), player=player, mta_name=getPlayerName(player), new=true}
local monthtimes = {}
local monthtTopTime = nil
local mapname
local info
local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }

score = {}
score['Destruction derby'] = true
score['Shooter'] = true

addEvent('onMapStarting')
addEventHandler('onMapStarting', root,
	function(mapInfo, mapOptions, gameOptions)
		if mapname then
			updatePosColumn(mapname)
		end
		queryMapTimes(mapInfo)
		checkResources()
	end
)

addEventHandler('onResourceStart', resourceRoot,
	function()
		handlerConnect = dbConnect( 'mysql', 'host=' .. get"*gcshop.host" .. ';dbname=' .. get"*gcshop.dbname", get("*gcshop.user"), get("*gcshop.pass"))
		local raceInfo = getRaceInfo()
		if not handlerConnect then
			outputDebugString('Serial/IP Database error: could not connect to the mysql db')
			return
		elseif raceInfo then
			queryMapTimes(raceInfo.mapInfo, true)
		end
		checkResources()
	end
)

function queryMapTimes (mapInfo, bStart)
	times = {}
	monthtimes = {}
	monthtTopTime = nil
	mapname = mapInfo.resname
	info = mapInfo
	local q = "SELECT forumid, mapname, pos, value, date, g.mta_name FROM toptimes, mrgreen_gc.green_coins g WHERE forumid = g.forum_id and mapname = ? ORDER BY pos"
	dbQuery(maptimes, {mapInfo, bStart}, handlerConnect, q, mapname)
	if not score[exports.race:getRaceMode()] then
		local q = "SELECT forumid, mapname, value, date, month, g.mta_name FROM toptimes_month, mrgreen_gc.green_coins g WHERE forumid = g.forum_id and mapname = ? ORDER BY date DESC"
		dbQuery(monthlytime, {mapInfo, bStart}, handlerConnect, q, mapname, getRealTime().month+1)
	else
		sendMonthTime()	-- send empty month time
	end
end

function maptimes(qh, mapInfo, bStart)
	local result = dbPoll(qh, 0)
	if not result then
		return outputDebugString('toptimes failed ' .. mapname, 2)
	elseif #result > 0 then
		if mapInfo.resname ~= mapname then
			return outputDebugString('toptimes mismatch ' .. mapname .. ' ' .. mapInfo.resname, 2)
		else
			times = result
			-- var_dump("-v", times)
		end
	else
		-- outputDebugString('new map ' .. mapInfo.resname)
	end
	times.resname = mapInfo.resname
	times.mapname = mapInfo.name
	times.modename = mapInfo.modename
	times.kills = score[mapInfo.modename]
	for k, player in ipairs(getElementsByType'player') do
		local forumid = exports.gc:getPlayerForumID(player)
		if forumid then
			for _, t in ipairs(times) do
				if forumid == t.forumid then
					t.player = player
					t.mta_name = getPlayerName(player)
					break
				end
			end
		end
	end
	for _, t in ipairs(times) do
		t.formatDate = FormatDate(t.date)
	end

	if not bStart then
		sendClientTimes()
	else
		setTimer(sendClientTimes, 1000, 1)
	end
end

function monthlytime(qh, mapInfo, bStart)
	local result = dbPoll(qh, 0)
	if not result then
		return outputDebugString('monthlytime failed ' .. mapname, 2)
	elseif #result > 0 then
		if mapInfo.resname ~= mapname then
			return outputDebugString('toptimes mismatch ' .. mapname .. ' ' .. mapInfo.resname, 2)
		else
			monthtimes = result
			if result[1].month == getRealTime().month+1 then
				monthtTopTime = result[1]
				-- var_dump("-v", times)
				monthtTopTime.resname = mapInfo.resname
				monthtTopTime.mapname = mapInfo.name
				monthtTopTime.modename = mapInfo.modename
				monthtTopTime.kills = score[mapInfo.modename]
				monthtTopTime.formatDate = FormatDate(monthtTopTime.date)
				for k, player in ipairs(getElementsByType'player') do
					local forumid = exports.gc:getPlayerForumID(player)
					if forumid and monthtTopTime.forumid == forumid then
						monthtTopTime.player = player
						monthtTopTime.mta_name = getPlayerName(player)
						break
					end
				end
			end
		end
	else
		-- outputDebugString('new map ' .. mapInfo.resname)
	end
	if not bStart then
		sendMonthTime()
	else
		setTimer(sendMonthTime, 1000, 1)
	end
end

function updatePosColumn(name)
	-- update pos column from previous map
	local q = "CALL updateTopPositions(?);"
	if times.kills then
		q = "CALL updateTopPositionsDesc(?);"
	end
	dbExec(handlerConnect, q, mapname)
	-- outputDebugString('updating pos map ' .. mapname)
end

addEventHandler('onResourceStop', resourceRoot, function()
	if mapname then
		updatePosColumn(mapname)
	end
end)

addEvent('clientstarted', true)
addEventHandler('clientstarted', resourceRoot, function()
	sendClientTimes(client)
end)

function getRaceInfo()
	local raceResRoot = getResourceRootElement( getResourceFromName( "race" ) )
	return raceResRoot and getElementData( raceResRoot, "info" )
end

function sendClientTimes(player)
	triggerClientEvent(player or root, 'updateTopTimes', resourceRoot, times)
end

function sendMonthTime(player)
	triggerClientEvent(player or root, 'updateMonthTime', resourceRoot, monthtTopTime)
end

-------------------------
-- Adding new toptimes --
-------------------------

function updatePlayerTop(player, rank, value)
	local forumid = exports.gc:getPlayerForumID(player)
	local toptime = nil
	if isMapTesting() or not forumid then return end
	for i, row in ipairs(times) do
		if forumid == row.forumid then
			row.player = player
			toptime = row
			break
		end
	end

	if not score[exports.race:getRaceMode()] and rank == 1 and not (monthtTopTime and monthtTopTime.month ~= getRealTime().month+1) and (not monthtTopTime or (not times.kills and value < monthtTopTime.value) or (times.kills and value > monthtTopTime.value)) then
		local oldTime = monthtTopTime and monthtTopTime.value or nil

		-- dont reward first monthly top for a map

		local oldRewarded = 1
		if #monthtimes > 1 or (monthtimes[1] and monthtimes[1].month ~= getRealTime().month+1) then
			oldRewarded = 0
		end

		monthtTopTime = {}
		monthtTopTime.forumid = forumid
		monthtTopTime.value = value
		monthtTopTime.date = getRealTime().timestamp
		monthtTopTime.month = getRealTime().month+1

		monthtTopTime.resname = info.resname
		monthtTopTime.mapname = info.name
		monthtTopTime.modename = info.modename
		monthtTopTime.kills = score[info.modename]
		monthtTopTime.formatDate = FormatDate(monthtTopTime.date)
		monthtTopTime.player = player
		monthtTopTime.mta_name = getPlayerName(player)
		monthtTopTime.rewarded = oldRewarded

		if oldTime then
			monthtimes[1] = monthtTopTime
		else
			table.insert(monthtimes, 2, monthtTopTime)
		end

		local q = "INSERT INTO toptimes_month VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE forumid = ?, value = ?, date=?;"
		dbExec(handlerConnect, q, forumid, info.resname, value, getRealTime().timestamp, getRealTime().month+1, oldRewarded, forumid, value, getRealTime().timestamp)
		sendMonthTime()
		monthtimeImprovement(player, value, oldTime, oldRewarded)
	end

	if not toptime or (not times.kills and value < toptime.value) or (times.kills and value > toptime.value) then
		local q
		local newPos, newTime, oldPos, oldTime
		newTime = value
		if not toptime then
			q = "INSERT INTO `toptimes`( `value`,`date`, `forumid`, `mapname`) VALUES (?,?,?,?)"
			table.insert(times, {forumid=forumid,mapname=mapname, value=value, date=getRealTime().timestamp, formatDate = FormatDate(getRealTime().timestamp), player=player, mta_name=getPlayerName(player), new=true})
			-- outputDebugString('new top for ' .. getPlayerName(player))
		elseif (not times.kills and value < toptime.value) or (times.kills and value > toptime.value) then
			oldPos, oldTime = toptime.pos, toptime.value
			q = "UPDATE `toptimes` SET `value`=?, `date`=? WHERE `forumid`=? AND `mapname`=?"
			toptime.value = value
			toptime.date = getRealTime().timestamp
			toptime.formatDate = FormatDate(toptime.date)
			toptime.player = player
			toptime.mta_name=getPlayerName(player)
			toptime.new=true
			-- outputDebugString('updated top for ' .. getPlayerName(player))
		end
		dbExec(handlerConnect, q, value, getRealTime().timestamp, forumid, mapname)
		if not times.kills then
			table.sort(times, function(a,b) return a.value < b.value or (a.value == b.value and a.date < b.date) end)
		else
			table.sort(times, function(a,b) return a.value > b.value or (a.value == b.value and a.date < b.date) end)
		end
		sendClientTimes()
		for pos_, top in ipairs(times) do
			if top.forumid == forumid then
				newPos = pos_
				break
			end
		end
		toptimeImprovement( player, newPos, newTime, oldPos, oldTime, displayTopCount, #times )
	end
end

addEvent('onPlayerToptimeImprovement')
function toptimeImprovement( player, newPos, newTime, oldPos, oldTime, displayTopCount, getValidEntryCount )
	triggerEvent('onPlayerToptimeImprovement', player, newPos, newTime, oldPos, oldTime, displayTopCount, getValidEntryCount)
	if score[exports.race:getRaceMode()] then
		return
    elseif not oldPos then
		outputChatBox ( "A new personal time on this map:" , player, 255, 165, 0, true)
		outputChatBox ( "#" .. newPos .. ' ' .. timeMsToTimeText(newTime) , player, 255, 165, 0, true)
	else
		outputChatBox ( "Improved your personal time on this map:", player, 255, 165, 0, true)
		outputChatBox ( 'From #' .. oldPos .. " " .. timeMsToTimeText(oldTime) .. " to #" .. newPos .. " " .. timeMsToTimeText(newTime) .. " (-" .. timeMsToTimeText(oldTime - newTime) .. ")", player, 255, 165, 0, true)
    end
	if newPos == 1 then
		giveTop1Reward(player)
	end
end

addEvent('onPlayerMonthtimeImprovement')
function monthtimeImprovement( player, newTime, oldTime, rewarded )
	triggerEvent('onPlayerMonthtimeImprovement', player, newTime, oldTime)
	if score[exports.race:getRaceMode()] then
		return
    elseif rewarded == 0 then
		outputChatBox ( "You now have the monthly top on this map, if you hold it you will receive a reward at the end of the month" , player, 255, 165, 0, true)
	end
end

addEvent('onPlayerFinish')
addEventHandler('onPlayerFinish', root,
	function(rank, time)
		updatePlayerTop(source, rank, time)
	end
, true, 'low')

-- [[
addEventHandler('onPlayerFinishDD', root,
	function(rank)
		local kills = tonumber(getElementData(source, 'kills'))
		if kills and kills > 0 then
			updatePlayerTop(source, rank, kills)
		end
	end
, true, 'low')
--]]

addEventHandler('onPlayerWinDD', root,
	function()
		-- timer to wait for clientside confirmation of a kill from the last killed guy
		setTimer(function(source)
			local kills = tonumber(getElementData(source, 'kills'))
			if kills and kills > 0 then
				updatePlayerTop(source, 1, kills)
			end
		end, 500, 1, source)
	end
, true, 'low')

-- [[
addEventHandler('onPlayerFinishShooter', root,
	function(rank)
		local kills = tonumber(getElementData(source, 'kills'))
		if kills and kills > 0 then
			updatePlayerTop(source, rank, kills)
		end
	end
, true, 'low')
--]]

addEventHandler('onPlayerWinShooter', root,
	function()
		-- timer to wait for clientside confirmation of a kill from the last killed guy
		setTimer(function(source)
			local kills = tonumber(getElementData(source, 'kills'))
			if kills and kills > 0 then
				updatePlayerTop(source, 1, kills)
			end
		end, 500, 1, source)
	end
, true, 'low')

----------------
-- GC rewards --
----------------

-- Check for outstanding month rewards
local currentMonth = getRealTime().month+1
local checkedIDs = {}
function gcLogin ( forumid, amount )
	if checkedIDs[forumid] == getRealTime().month+1 then return end
	local player = source
	-- Check if player has unrewarded most monthly tops in the past months
	local q = [[
	SELECT forumid, month, c FROM (
		SELECT * FROM (
			SELECT *, COUNT(*) c FROM (
				SELECT * FROM `toptimes_month` ORDER BY date
			) AS dated WHERE rewarded = 0 GROUP BY forumid, month ORDER BY `month` ASC, `c`  DESC
		) AS counted GROUP BY month
	) AS maxs WHERE forumid = ? AND month != ?
	]]
	setTimer(function()
		if isElement(player) then
		dbQuery( mostMonthTops, {forumid, getPlayerSerial(player), getRealTime().month+1}, handlerConnect, q, forumid, getRealTime().month+1)
		end
	end, 10000, 1 )
end
addEventHandler("onGCLogin" , root, gcLogin )

function mostMonthTops ( qh, forumid, serial, month )
	local result = dbPoll(qh, 0)
	if not result then
		return outputDebugString('mostMonthTops failed ' .. tostring(forumid), 2)
	else
		-- Do query to check for unrewarded monthly tops
		local q = [[
		SELECT forumid, month, COUNT(*) count, GROUP_CONCAT(mapname) mapnames FROM `toptimes_month`
		WHERE forumid = ? AND rewarded = 0 AND month != ?
		GROUP BY forumid, month ORDER BY `toptimes_month`.`month` ASC
		]]
		dbQuery ( monthlyTops, {forumid, serial, getRealTime().month+1, result}, handlerConnect, q, forumid, getRealTime().month+1)
	end
end

function monthlyTops ( qh, forumid, serial, month, mostResult )
	local result = dbPoll(qh, 0)
	local player
	for _,p in ipairs(getElementsByType'player') do
		if getPlayerSerial(p) == serial then
			player = p
			break
		end
	end
	if not player or not isElement(player) or exports.gc:getPlayerForumID ( player ) ~= forumid then return end
	if not result then
		return outputDebugString('mostMonthTops failed ' .. tostring(forumid), 2)
	else
		checkedIDs[forumid] = month
		if #result > 0 then
			for i, r in ipairs(result) do
				outputChatBox("[GC] You had " .. r.count .. " monthly toptime(s) in " .. months[r.month] .. " and got " .. monthlyReward * r.count .. " GC", player, 0, 255, 0)
				exports.gc:addPlayerGreencoins(player, monthlyReward * r.count)
				outputConsole(months[r.month] .. ': ' .. r.mapnames, player)
			end
			dbExec(handlerConnect, 'UPDATE `toptimes_month` SET `rewarded`=1 WHERE `forumid`=? AND `month`!=? AND `rewarded`=0', forumid, month)
			if #mostResult > 0 then
				local s = "[GC] You had the most monthly toptimes in"
				for i, r in ipairs(mostResult) do
					s = s .. ' ' .. months[r.month]
					if i < #mostResult then
						s = s .. (i ~= #mostResult-1 and ',' or ' and')
					end
				end
				outputChatBox(s .. " and received " .. #mostResult * mostMonthlyReward .. " GC", player, 0, 255, 0)
				exports.gc:addPlayerGreencoins(player, #mostResult * mostMonthlyReward)
			end
		end
	end
end

function giveTop1Reward ( player )
	if not (#monthtimes > 1 or (monthtimes[1] and monthtimes[1].month ~= getRealTime().month+1)) then return end
	outputChatBox ( '[GC]'  .. getPlayerName(player) .. "#00FF00 earned " .. #monthtimes*baseTop1Reward .. " Green-Coins for the new top1", root, 0, 255, 0, true)
	exports.gc:addPlayerGreencoins(player, #monthtimes*baseTop1Reward)
end

--------------------
-- Removing times --
--------------------

function deletetop(p, c, pos, ...)
	pos = tonumber(pos)
	local reason = table.concat({...},' ')
	if not (pos and times[pos]) then
		return outputChatBox('Top not found ' .. tostring(pos), p)
	elseif not reason or #reason < 2 then
		return outputChatBox('Syntax: /deletetop <top> <reason>', p)
	end
	local top = table.remove(times, pos)
	dbExec(handlerConnect, 'DELETE FROM toptimes WHERE forumid = ? and mapname = ?', top.forumid, top.mapname)
	sendClientTimes()
	outputChatBox('Top #' .. pos .. ' ' .. timeMsToTimeText(top.value) .. ' ' .. top.mta_name .. ' was deleted by ' .. _getPlayerName(p))
	deletelog(("Top #%d (%s %s) on map \"%s\" was deleted by %s (%s): %s"):format(pos, timeMsToTimeText(top.value), top.mta_name, top.mapname, _getPlayerName(p), getAccountName(getPlayerAccount(p)), reason))
end
addCommandHandler('deletetop', deletetop, true)

function deletealltops(p, c, ...)
	local reason = table.concat({...},' ')
	if not reason or #reason < 2 then
		return outputChatBox('Syntax: /deletealltops <reason>', p)
	end
	local top = table.remove(times, pos)
	if not top then return end
	for i,v in ipairs(times) do
		times[i] = nil
	end
	dbExec(handlerConnect, 'DELETE FROM toptimes WHERE mapname = ?', times.resname)
	sendClientTimes()
	outputChatBox('All tops deleted for ' .. top.mapname .. ' by ' .. _getPlayerName(p))
	deletelog(("All tops on map \"%s\" deleted by %s (%s): %s"):format(top.mapname, _getPlayerName(p), getAccountName(getPlayerAccount(p)), reason))
end
addCommandHandler('deletealltops', deletealltops, true)

function deletemonthtop(p, c)
	if not monthtTopTime then
		return outputChatBox('Month top not found', p)
	end
	dbExec(handlerConnect, 'DELETE FROM toptimes_month WHERE mapname = ? AND month = ?', monthtTopTime.resname, monthtTopTime.month)
	monthtTopTime = nil
	sendMonthTime()
	outputChatBox('Month top deleted', p)
end
addCommandHandler('deletemonthtop', deletemonthtop, true)

function deletelog ( msg)
	local f = fileExists'deleted_tops.log' and fileOpen'deleted_tops.log' or fileCreate'deleted_tops.log'
	fileSetPos( f, fileGetSize( f ) )
	fileWrite(f, FormatDate(nil, true) .. ' ' .. msg .. '\n')
	fileClose(f)
end

local modes={
	race={race=true},
	mix={nts=true,dd=true,rtf=true,sh=true,ctf=true},
}

function checkResources()
	if true then return end	-- Fuck deletes
	local m = modes[get'server']
	local m2 = modes[get'server'=='race' and 'mix' or 'race']
	if not m then
		return outputChatBox("WARNING: SET THE TOPTIMES SERVER TYPE!", root, 255,0,0)
	end
	dbQuery(function(qh)
		local result = dbPoll(qh, 0)
		if not result then
			return outputDebugString('checkResources failed ', 2)
		else
			for _, r in ipairs(result) do
				local name = string.lower(r.mapname)
				if not (getResourceFromName(name) or m2[split(name, '-')[1]]) then
					outputDebugString('Deleting ' .. name .. ' monthly toptimes')
					dbExec(handlerConnect, 'DELETE FROM toptimes_month WHERE mapname=?', name)
				end
			end
		end
	end, handlerConnect, 'SELECT mapname FROM `toptimes_month` GROUP BY mapname' )

end

-------------------
-- Checking tops --
-------------------

addCommandHandler('oldtops',
	function(p, cmd, name, ex)
		local player = string.lower(name or _getPlayerName(p))
		ex= tonumber(ex) or 3
		local count = {}
		if ex < 1 or ex > 10 then ex = 1 end
		for a=1,ex do
			count [a] = 0
		end
		local map_names = {}
		for k, v in ipairs(exports.mapmanager:getMapsCompatibleWithGamemode(getResourceFromName('race'))) do
			map_names['race maptimes Sprint ' .. (getResourceInfo(v, 'name' ) or getResourceName(v))] = v
		end

		local maps_table = executeSQLQuery( "SELECT tbl_name FROM sqlite_master WHERE tbl_name LIKE 'race maptimes Sprint %' " )
		for k, v in ipairs(maps_table) do

			local mapTable = v.tbl_name
			if map_names[mapTable] then
				local mapTimes = executeSQLQuery( "SELECT playerName FROM ? LIMIT ?", mapTable, tostring(ex) )
				for i, t in ipairs ( mapTimes ) do
					if string.lower(t.playerName) == player then
						outputConsole(mapTable)
						count [i] = count[i] + 1
					end
				end
			end

		end

		outputChatBox(player .. ' old toptimes: ' , p)
		local player = name or _getPlayerName(p)
		for a=1,ex do
			outputChatBox('* Top' .. a .. '\'s = ' .. count [a] , p)
		end
	end
)

addCommandHandler('tops',
	function(p, cmd, ex)
		ex= tonumber(ex) or 3
		local forumid = exports.gc:getPlayerForumID(p)
		if not forumid then
			return outputChatBox("You are not logged in to Greencoins!", p)
		end
		dbQuery(function(qh)
			local result = dbPoll(qh, 0)
			if not result then
				return outputDebugString('/tops failed ' .. forumid, 2)
			elseif #result == 0 then
				outputChatBox("You have no tops!", p)
			else
				outputChatBox('Your toptimes: ' , p)
				for pos = 1,ex do
					local r = nil
					for k,row in ipairs(result) do
						if pos == row.pos then
							r = row
							break
						end
					end
					if not r then
						outputChatBox('* Top' .. pos .. '\'s = ' .. 0 , p)
					else
						outputChatBox('* Top' .. pos .. '\'s = ' .. r.count , p)
						outputConsole(r.mapnames)
					end
				end
			end
		end, handlerConnect, "SELECT pos, count(*) count, GROUP_CONCAT(mapname SEPARATOR ', ') mapnames FROM `toptimes` WHERE forumid=? GROUP BY pos ORDER BY pos", forumid)
	end
)

-------------
-- utility --
-------------

function FormatDate(timestamp, full)
	local t =  getRealTime(timestamp)
	if full then
		return string.format("%02d/%02d/'%02d %02d:%02d:%02d", t.monthday, t.month+1, t.year - 100, t.hour, t.minute, t.second)
	end
	return string.format("%02d-%02d", t.monthday, t.month+1)
end

function timeMsToTimeText( timeMs )

	local minutes	= math.floor( timeMs / 60000 )
	timeMs			= timeMs - minutes * 60000;

	local seconds	= math.floor( timeMs / 1000 )
	local ms		= timeMs - seconds * 1000;

	return string.format( '%02d:%02d:%03d', minutes, seconds, ms );
end

function _getPlayerName ( player )
	return removeColorCoding ( getPlayerName ( player ) )
end

function isMapTesting()
	return getResourceInfo(exports.mapmanager:getRunningGamemodeMap(), 'newupload') == "true"
end

-- modifiers: v - verbose (all subtables), n - normal, s - silent (no output), dx - up to depth x, u - unnamed
function var_dump(...)
	-- default options
	local verbose = false
	local firstLevel = true
	local outputDirectly = true
	local noNames = false
	local indentation = "\t\t\t\t\t\t"
	local depth = nil

	local name = nil
	local output = {}
	for k,v in ipairs(arg) do
		-- check for modifiers
		if type(v) == "string" and k < #arg and v:sub(1,1) == "-" then
			local modifiers = v:sub(2)
			if modifiers:find("v") ~= nil then
				verbose = true
			end
			if modifiers:find("s") ~= nil then
				outputDirectly = false
			end
			if modifiers:find("n") ~= nil then
				verbose = false
			end
			if modifiers:find("u") ~= nil then
				noNames = true
			end
			local s,e = modifiers:find("d%d+")
			if s ~= nil then
				depth = tonumber(string.sub(modifiers,s+1,e))
			end
		-- set name if appropriate
		elseif type(v) == "string" and k < #arg and name == nil and not noNames then
			name = v
		else
			if name ~= nil then
				name = ""..name..": "
			else
				name = ""
			end

			local o = ""
			if type(v) == "string" then
				table.insert(output,name..type(v).."("..v:len()..") \""..v.."\"")
			elseif type(v) == "userdata" then
				local elementType = "no valid MTA element"
				if isElement(v) then
					elementType = getElementType(v)
				end
				table.insert(output,name..type(v).."("..elementType..") \""..tostring(v).."\"")
			elseif type(v) == "table" then
				local count = 0
				for key,value in pairs(v) do
					count = count + 1
				end
				table.insert(output,name..type(v).."("..count..") \""..tostring(v).."\"")
				if verbose and count > 0 and (depth == nil or depth > 0) then
					table.insert(output,"\t{")
					for key,value in pairs(v) do
						-- calls itself, so be careful when you change anything
						local newModifiers = "-s"
						if depth == nil then
							newModifiers = "-sv"
						elseif  depth > 1 then
							local newDepth = depth - 1
							newModifiers = "-svd"..newDepth
						end
						local keyString, keyTable = var_dump(newModifiers,key)
						local valueString, valueTable = var_dump(newModifiers,value)

						if #keyTable == 1 and #valueTable == 1 then
							table.insert(output,indentation.."["..keyString.."]\t=>\t"..valueString)
						elseif #keyTable == 1 then
							table.insert(output,indentation.."["..keyString.."]\t=>")
							for k,v in ipairs(valueTable) do
								table.insert(output,indentation..v)
							end
						elseif #valueTable == 1 then
							for k,v in ipairs(keyTable) do
								if k == 1 then
									table.insert(output,indentation.."["..v)
								elseif k == #keyTable then
									table.insert(output,indentation..v.."]")
								else
									table.insert(output,indentation..v)
								end
							end
							table.insert(output,indentation.."\t=>\t"..valueString)
						else
							for k,v in ipairs(keyTable) do
								if k == 1 then
									table.insert(output,indentation.."["..v)
								elseif k == #keyTable then
									table.insert(output,indentation..v.."]")
								else
									table.insert(output,indentation..v)
								end
							end
							for k,v in ipairs(valueTable) do
								if k == 1 then
									table.insert(output,indentation.." => "..v)
								else
									table.insert(output,indentation..v)
								end
							end
						end
					end
					table.insert(output,"\t}")
				end
			else
				table.insert(output,name..type(v).." \""..tostring(v).."\"")
			end
			name = nil
		end
	end
	local string = ""
	for k,v in ipairs(output) do
		if outputDirectly then
			outputConsole(v)
		end
		string = string..v
	end
	return string, output
end