text:
package com.khmelenko.lab.varis.adapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.khmelenko.lab.varis.R;
import com.khmelenko.lab.varis.storage.SearchHistoryProvider;

/**
 * Adapter for search results
 *
 * @author Dmytro Khmelenko (d.khmelenko@gmail.com)
 */
public class SearchResultsAdapter extends CursorAdapter {

    public SearchResultsAdapter(Context context, Cursor cursor) {
        super(context, cursor, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView text = (TextView) view.findViewById(R.id.item_search_result_text);
        int columnIndex = cursor.getColumnIndex(SearchHistoryProvider.HEADER_COLUMN);
        String textValue = cursor.getString(columnIndex);
        text.setText(textValue);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return inflater.inflate(R.layout.item_search_result, parent, false);
    }
}


text:
# Containers
##  Breif history and overview

Web applications with Node.js

Telerik Software Academy

    http://academy.telerik.com

# Table of Contents

- Breif history
  - How IT developed over the years
- The Docker Project
  - The what and why of Docker
- Docker in action
  - The how of Docker
- Docker in-depth

# Breif history
## How IT developed over the years

# Physical machines

- Each application runs on a seperate `physical machine`, which causes problems:
  - Procurement time
  - Power solutions
  - Cooling solutions
  - Administration
  - Low utilization

# Virtual machines
- Each application runs on a seperate `virtual machine`, on top of a `physical` one:
  - This solves `some` of the problems stated above, but causes:
    - Licensing hell
    - Higher administration costs
       - Each **physical** machine has to be updated
       - Each **virtual** machine has to be updated
    - System resource overhead

# Containers
- Each application runs in a seperate `container`, on top of a `physical machine` (or virtual):
   - This solves `most` of the problems, but it's **not** a perfect solution
   - They allow to ship applications, regardless of host's bins and libs
   - They are **fast and lightweight**
   - They can **scale** very easily
   - They provide **availability**

# Containers

# The Docker Project
## The what and why of Docker

# What is Docker?

Wikipedia defines **Docker** as:

 ```
 An open-source project that automates the deployment of
 software applications inside containers by providing an
 additional layer of abstraction and automation of
 OS-level virtualization on Linux.
 ```

- **Docker** is a tool that allows developers to easily deploy their applications in a sandbox (called containers) to run on the host operating system.

# What is Docker?

- **The key benefit** of Docker is that it allows users to package an application with all of its dependencies into a **standardized unit** for software development.
- **Unlike virtual machines**, containers do not have the high overhead and hence enable more efficient usage of the underlying system and resources.

# Basic Terminology

- **Images** - The blueprints of our application which form the basis of containers.
    - Similar to `virtual machine` templates
    - Similar to `OOP classes` (kind of)
    - Similar to `3D Blueprint`
- **Containers** - Created from Docker images and run the actual application.
    - Similar to `virtual machine` instances
    - Similar to `OOP objects`
    - Similar to `3D printed object`

# Basic Terminology

- **Docker Daemon** - The background service running on the host that manages building, running and distributing Docker containers
    - The daemon is the process that runs in the operating system to which clients talk to
- **Docker Client** - The command line tool that allows the user to interact with the daemon
    - More generally, there can be other forms of clients too, such as Kitematic

# Basic Terminology
- **Docker Hub** - A registry of Docker images:
    - Something like GitHub, but for Docker images.
    - You can think of the registry as a directory of `most` publicly available Docker images.
    - If required, one can host their own Docker registries and can use them for pulling images.
    - You have one `free private repository` when you register, right off the bat.

# Under the hood

- Each container reuses the underlying OS's kernel and a part of the underlying bins and libraries
- Each container has:
  - It's own filesystem root (/)
  - It's own PID 0
  - It's own network

# Running it on Windows
- Requirements
    - At least `Windows Server 2016` Standard or
    - At least `Windows 10` (Pro or Ultimate) Anniversary Update (Version 10.0.14396)
    - CPU Virtualization support
        - Enable **Virtualization** in `BIOS` settings
        - Enable **Hyper-V** in `Windows Features` settings
- Installation
    - Download Docker for Windows (**not Docker Toolbox!**)

# Other platforms
- Mac
    - Hardware from at least **after 2010**
    - Software at least **10.10.3v**
    - CPU Virtualization support
      - Uses `DataKit`
- Linux
    - Most distributions (Debian, Ubuntu, CentOS, etc.)
        - sudo wget -qO- https://get.docker.com/ | sh
    - Have a weird/rare distro?
        - DuckDuckGo it...

# Docker in action
## The how of Docker

# Example
- Let's download run a very simple image:
    - **docker login**
        - `Log in` into **Docker Hub**
    - **docker pull** hello-world (optional step)
        - `Downloads` the image ``hello-world``
    - **docker run** hello-world
        - `Creates` a container out of it
        - `Runs` it without any additional settings
            - It will output some hello-world text
            - Then it will die `(PID 0 closes)`

# Docker Commands
- Main commands example:
    - **docker build** -t angular .
    - **docker run** -d -p 3001:3001 --name client angular
    - **docker ps** -a
    - **docker start** client
    - **docker stop** client
    - **docker rm** client
    - **docker rmi** angular
- The only command you need to remember:
    - **docker --help**

# Docker In-Depth
## Well.. not really.. it just sounds cool

# Questions?

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_QT_PEERTABLEMODEL_H
#define BITCOIN_QT_PEERTABLEMODEL_H

#include "main.h"
#include "net.h"

#include <QAbstractTableModel>
#include <QStringList>

class ClientModel;
class PeerTablePriv;

QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE

struct CNodeCombinedStats {
    CNodeStats nodeStats;
    CNodeStateStats nodeStateStats;
    bool fNodeStateStatsAvailable;
};

class NodeLessThan
{
public:
    NodeLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {}
    bool operator()(const CNodeCombinedStats& left, const CNodeCombinedStats& right) const;

private:
    int column;
    Qt::SortOrder order;
};

/**
   Qt model providing information about connected peers, similar to the
   "getpeerinfo" RPC call. Used by the rpc console UI.
 */
class PeerTableModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    explicit PeerTableModel(ClientModel* parent = 0);
    const CNodeCombinedStats* getNodeStats(int idx);
    int getRowByNodeId(NodeId nodeid);
    void startAutoRefresh();
    void stopAutoRefresh();

    enum ColumnIndex {
        Address = 0,
        Subversion = 1,
        Ping = 2
    };

    /** @name Methods overridden from QAbstractTableModel
        @{*/
    int rowCount(const QModelIndex& parent) const;
    int columnCount(const QModelIndex& parent) const;
    QVariant data(const QModelIndex& index, int role) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;
    QModelIndex index(int row, int column, const QModelIndex& parent) const;
    Qt::ItemFlags flags(const QModelIndex& index) const;
    void sort(int column, Qt::SortOrder order);
    /*@}*/

public Q_SLOTS:
    void refresh();

private:
    ClientModel* clientModel;
    QStringList columns;
    PeerTablePriv* priv;
    QTimer* timer;
};

#endif // BITCOIN_QT_PEERTABLEMODEL_H


text:
package edu.university.roombooking.domain;

import static javax.persistence.FetchType.LAZY;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Cacheable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

@Entity
@Table(name="db_status")
@Cacheable(false)
public class DbStatus implements Serializable {

	private static final long serialVersionUID = 1L;

	@EmbeddedId
	private DbStatusPK id;

	@OneToMany(mappedBy="dbStatus", fetch = LAZY)
	@OrderBy
	private List<Reservation> reservations;

	public DbStatus(){
	}

	public DbStatusPK getId() {
		return id;
	}

	public void setId(DbStatusPK id) {
		this.id = id;
	}

	public List<Reservation> getReservations() {
		return reservations;
	}

	public void setReservations(List<Reservation> reservations) {
		this.reservations = reservations;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result
				+ ((reservations == null) ? 0 : reservations.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof DbStatus))
			return false;
		DbStatus other = (DbStatus) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (reservations == null) {
			if (other.reservations != null)
				return false;
		} else if (!reservations.equals(other.reservations))
			return false;
		return true;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">

<!-- Based on solutions offered at
    1. https://blog.travis-ci.com/2017-03-30-deploy-maven-travis-ci-packagecloud/
    2. https://xebia.com/blog/unpacking-the-possibilities-of-github-packages/
-->

    <activeProfiles>
    <activeProfile>github</activeProfile>
    </activeProfiles>

    <profiles>
    <profile>
        <id>github</id>
        <repositories>
            <repository>
            <id>github</id>
            <name>GitHub spideruci Apache Maven Packages</name>
            <url>https://maven.pkg.github.com/spideruci/projects4testing</url>
            </repository>
        </repositories>
    </profile>
    </profiles>

  <servers>
    <server>
        <id>github</id>
        <username>vijay.0288@gmail.com</username>
        <password>${env.GH_TOKEN}</password>
      </server>
  </servers>
</settings>


text:
package ch02.car;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

/**
   A car shape that can be positioned anywhere on the screen.
*/
public class Car
{
   private int xLeft;
   private int yTop;

   /**
      Constructs a car with a given top left corner.
      @param x the x coordinate of the top left corner
      @param y the y coordinate of the top left corner
   */
   public Car(int x, int y)
   {
      xLeft = x;
      yTop = y;
   }

   /**
      Draws the car.
      @param g2 the graphics context
   */
   public void draw(Graphics2D g2)
   {
      Rectangle body
            = new Rectangle(xLeft, yTop + 10, 60, 10);
      Ellipse2D.Double frontTire
            = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10);
      Ellipse2D.Double rearTire
            = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10);

      // The bottom of the front windshield
      Point2D.Double r1
            = new Point2D.Double(xLeft + 10, yTop + 10);
      // The front of the roof
      Point2D.Double r2
            = new Point2D.Double(xLeft + 20, yTop);
      // The rear of the roof
      Point2D.Double r3
            = new Point2D.Double(xLeft + 40, yTop);
      // The bottom of the rear windshield
      Point2D.Double r4
            = new Point2D.Double(xLeft + 50, yTop + 10);

      Line2D.Double frontWindshield
            = new Line2D.Double(r1, r2);
      Line2D.Double roofTop
            = new Line2D.Double(r2, r3);
      Line2D.Double rearWindshield
            = new Line2D.Double(r3, r4);

      g2.draw(body);
      g2.draw(frontTire);
      g2.draw(rearTire);
      g2.draw(frontWindshield);
      g2.draw(roofTop);
      g2.draw(rearWindshield);
   }
}


text:
<project name="jar">

    <macrodef name="app-jar">
        <attribute name="toJarFile" default="${dist.jar}"/>
        <attribute name="preverifyDir" default="${preverify.dir}"/>
        <attribute name="resourcesDir" default="${resources.dir}"/>
        <attribute name="manifestfile" default="${manifest.file}"/>

        <sequential>
            <echo>[${project.title}-Jar] @{preverifyDir}, @{resourcesDir} -> @{toJarFile}</echo>

            <jar
                destfile="@{toJarFile}"
                manifest="@{manifestfile}">

                <fileset dir="@{preverifyDir}" >
                    <exclude name="**/*.java"/>
                </fileset>
                <fileset dir="@{resourcesDir}" excludes="CVS/** .svn" />

            </jar>
        </sequential>
    </macrodef>

</project>


text:
#include <string.h>
#include <stdio.h>
#include <cstring>
#define BUFSIZE 5

void tester (const char *__str) {
	char *test = new char[BUFSIZE];
	test[strlen(__str)]='a';
	delete(test);
}

int main(int argc, const char *argv[])
{
	if (argc > 1){
		const char *userstr=argv[1];
		tester(userstr);
	}
//	fprintf(stderr, "in the end of program\n");
	return 0;
}


text:
angular.module(PKG.name+'.feature.templates', [
  PKG.name+'.commons',

  PKG.name+'.feature.crud'

]);


text:
package com.hunorkovacs.phy;

import java.util.Vector;

/**
* A uniform force field with constant magnitude and direction.
*

* Its base structure is the same as the PointlikeBody.
* In addition it possesses a force vector g.
* Can move and be acted on by another force if its mass is declared to a nonzero value.
* Its method, calcuating the acting forces, had to be modified to function correctly.
*

* @see PointlikeBody
*/
public class GravityField extends PointlikeBody
{
    /**
     * The g property of the force field. Its magnitude is measured in N*kg.
     */
    private com.hunorkovacs.phy.Dimension g;

    /**
     * Perfect definition of the object, assigning mass, position, velocity, g, model and name.
     *

     * It gets the main attributes, and also an instance of the PHYModel class.
     * Very important to use this constructor and to specify the phymodel object.
     * Otherwise the body will have no connection to other objects, declared
     * to live inside a different system.
     * @param m mass to be assigned
     * @param p position to be assigned
     * @param v speed to be assigned
     * @param g g constant of the force field to be assigned
     * @param phymodel the model object which holds all the other bodies
     * @param name name to be assigned
     */
    GravityField(double m, com.hunorkovacs.phy.Dimension p, com.hunorkovacs.phy.Dimension v, com.hunorkovacs.phy.Dimension g, PHYModel phymodel, String name)
    {
        super(m,p,v,phymodel,name);
        this.g = g;
    }

    /**
     * Returns the g property of the object.
     * @return the vector holding x and y components of the force measured in N*kg.
     */
    public com.hunorkovacs.phy.Dimension getG()
    {
        return g;
    }

    /**
     * Sets the g property of the object.
     * @param g the vector holding x and y components of the force measured in N*kg.
     */
    public void setG(com.hunorkovacs.phy.Dimension g)
    {
        this.g = g;
    }

    /**
     * Returns the applied force to a body with mass m.
     *

     * proceeds by the formula F = m*g
     * @param m the mass of the body to act on
     * @return the force vector applied on the given body by this field
     */
    public com.hunorkovacs.phy.Dimension act(double m)
    {
        return new com.hunorkovacs.phy.Dimension(g.getX()*m, g.getY()*m);
    }

    /**
     * The modified version of the calulcateActingForces() from the PointlikeBody class for spaces.
     *

     * I had to override this function because of the way the PointlikeBody caluclates forces.
     * It involves checking forces that apply to this actual object. In case of a force,
     * we should not consider the actual one as an acting force during the calculation.
     * Otherwise each force would make itself accelerate.
     */
    protected com.hunorkovacs.phy.Dimension calculateActingForces()
    {
        int i,j;
        boolean identicalSets;
        Vector bodyinris = new Vector();
        Vector bodyinforce = new Vector();
        com.hunorkovacs.phy.Dimension F = new com.hunorkovacs.phy.Dimension();

        for (i=0; i<phymodel.getnRIS(); i++) if (isInsideRIS(p, phymodel.getRISAt(i))) bodyinris.add(phymodel.getRISAt(i));
outer:  for (i=0; i<phymodel.getnGF(); i++){
            GravityField gf = phymodel.getGFAt(i);
            identicalSets = true;
            for (j=0; j<phymodel.getnRIS(); j++){
                RectangularIsolatorSpace ris = phymodel.getRISAt(j);
                if ((isInsideRIS(gf.getPosition(), ris))^(isInsideRIS(p, ris))){
                    identicalSets = false;
                    continue outer;
                }
            }
            if ((identicalSets)&&(!gf.equals(this))) bodyinforce.add(gf);
        }
        for (i=0; i<bodyinforce.size(); i++) F.setXY(F.getX()+((GravityField)bodyinforce.get(i)).act(m).getX(), F.getY()+((GravityField)bodyinforce.get(i)).act(m).getY());
        return F;
    }
}


text:
package com.kzmen.sczxjf.view.wheelview.listener;

import android.view.View;

/**
 * Created by KyuYi on 2017/3/2.
 * E-Mail:kyu_yi@sina.com
 * 功能:
 */

public interface CustomListener {
    void customLayout(View v);
}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/code_cache/simple_lru_cache.h"

#include <limits>

#include "base/feature_list.h"
#include "base/numerics/clamped_math.h"
#include "content/public/common/content_features.h"
#include "net/base/url_util.h"

namespace content {

using GetResult = SimpleLruCache::GetResult;

GetResult::GetResult(base::Time response_time, mojo_base::BigBuffer data)
    : response_time(response_time), data(std::move(data)) {}
GetResult::~GetResult() = default;

GetResult::GetResult(GetResult&&) = default;
GetResult& GetResult::operator=(GetResult&&) = default;

SimpleLruCache::Value::Value(Age age, base::Time response_time, uint32_t size)
    : age(age), response_time(response_time), size(size) {
  DCHECK(!base::FeatureList::IsEnabled(features::kInMemoryCodeCache));
}

SimpleLruCache::Value::Value(Age age,
                             base::Time response_time,
                             uint32_t size,
                             base::span<const uint8_t> data)
    : age(age),
      response_time(response_time),
      size(size),
      data(data.begin(), data.end()) {
  DCHECK(base::FeatureList::IsEnabled(features::kInMemoryCodeCache));
}

SimpleLruCache::Value::~Value() = default;

SimpleLruCache::Value::Value(Value&&) = default;
SimpleLruCache::Value& SimpleLruCache::Value::operator=(Value&&) = default;

SimpleLruCache::SimpleLruCache(uint64_t capacity) : capacity_(capacity) {}
SimpleLruCache::~SimpleLruCache() = default;

absl::optional<GetResult> SimpleLruCache::Get(const std::string& key) {
  base::Time response_time;
  mojo_base::BigBuffer data;
  if (!GetInternal(key, &response_time, &data)) {
    return absl::nullopt;
  }
  return absl::make_optional<GetResult>(response_time, std::move(data));
}

bool SimpleLruCache::Has(const std::string& key) {
  return GetInternal(key, /*response_time=*/nullptr, /*data=*/nullptr);
}

void SimpleLruCache::Put(const std::string& key,
                         base::Time response_time,
                         base::span<const uint8_t> payload) {
  Delete(key);

  const uint64_t size = base::ClampedNumeric<uint64_t>(key.size()) +
                        payload.size() + kEmptyEntrySize;

  if (size > capacity_) {
    // Ignore a too big entry.
    return;
  }

  const Age age = GetNextAge();
  if (base::FeatureList::IsEnabled(features::kInMemoryCodeCache)) {
    entries_.emplace(key, Value(age, response_time, size, payload));
  } else {
    entries_.emplace(key, Value(age, response_time, size));
  }
  access_list_.emplace(age, std::move(key));
  size_ += size;
  Evict();
}

void SimpleLruCache::Delete(const std::string& key) {
  const auto it = entries_.find(key);
  if (it == entries_.end()) {
    return;
  }

  DCHECK_GE(size_, it->second.size);
  size_ -= it->second.size;
  access_list_.erase(it->second.age);
  entries_.erase(it);
}

uint64_t SimpleLruCache::GetSize() const {
  return size_;
}

void SimpleLruCache::Clear() {
  entries_.clear();
  access_list_.clear();
  size_ = 0;
}

bool SimpleLruCache::GetInternal(const std::string& key,
                                 base::Time* response_time,
                                 mojo_base::BigBuffer* data) {
  const auto it = entries_.find(key);
  if (it == entries_.end()) {
    return false;
  }
  const Age age = GetNextAge();
  access_list_.erase(it->second.age);
  it->second.age = age;
  access_list_.emplace(age, it->first);

  if (response_time) {
    *response_time = it->second.response_time;
  }
  if (data && base::FeatureList::IsEnabled(features::kInMemoryCodeCache)) {
    *data = mojo_base::BigBuffer(it->second.data);
  }
  return true;
}

void SimpleLruCache::Evict() {
  while (capacity_ < size_) {
    auto it = access_list_.begin();
    DCHECK(it != access_list_.end());
    DCHECK(entries_.find(it->second) != entries_.end());

    Delete(it->second);
  }
}

}  // namespace content


text:
module PoodrRspec
  class RoadBike < Bicycle
    attr_reader :tape_color

    def post_initialize(args)
      @tape_color = args[:tape_color]
    end

    def local_spares
      { tape_color: tape_color }
    end

    def default_tire_size
      '23'
    end
  end
end


text:
from .collections import Collection
from .documents import Document
from .compat import py3k

__all__ = [
        'Document',
        'Collection'
        ]

if py3k:
    from .compat import normalize_string_type
    import json

    # This handles a bug of the json.loads method in python 3.2, see:
    # http://bugs.python.org/issue10976 for more information. Should be fixed
    # in python3
    json.loads = normalize_string_type(json.loads)


text:
import Observable from "./observable";
import { symbol } from "./symbol";
import Event, { isError, hasValue } from "./event";

class ESObservable<V> {
  observable: Observable<V>
  constructor(observable: Observable<V>) {
    this.observable = observable;
  }
  subscribe(observerOrOnNext: any, onError: any, onComplete: any) {
    const observer = typeof observerOrOnNext === 'function'
        ? { next: observerOrOnNext, error: onError, complete: onComplete }
        : observerOrOnNext
    const subscription = {
      closed: false,
      unsubscribe: function() {
        subscription.closed = true;
        cancel();
      }
    };

    const cancel = this.observable.subscribe(function(event: Event<V>) {
      if (hasValue(event) && observer.next) {
        observer.next(event.value);
      } else if (isError(event)) {
        if (observer.error) observer.error(event.error);
        subscription.unsubscribe();
      } else if (event.isEnd) {
        subscription.closed = true;
        if (observer.complete) observer.complete();
      }
    });
    return subscription;
  }
}

(<any>ESObservable.prototype)[symbol('observable')] = function() {
  return this;
};

(<any>Observable.prototype).toESObservable = function() {
  return new ESObservable(this);
};

(<any>Observable.prototype)[symbol('observable')] = (<any>Observable.prototype).toESObservable;


text:
export interface ICalculationsService {

}


text:
namespace IECorePython
{
void bindImath();
}

#endif // IECOREPYTHON_IMATHBINDING_H


text:
/*	$NetBSD: cd9660.h,v 1.17 2011/06/23 02:35:56 enami Exp $	*/

/*
 * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
 * Perez-Rathke and Ram Vedam.  All rights reserved.
 *
 * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
 * Alan Perez-Rathke and Ram Vedam.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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 DANIEL WATT, WALTER DEIGNAN, RYAN
 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``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 DANIEL WATT, WALTER DEIGNAN, RYAN
 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM 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.
 *
 * $FreeBSD$
 */

#ifndef _MAKEFS_CD9660_H
#define _MAKEFS_CD9660_H

#include <inttypes.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <limits.h>
#include <sys/queue.h>
#include <sys/param.h>
#include <sys/endian.h>

#include "makefs.h"
#include "iso.h"
#include "iso_rrip.h"
#include "cd9660/cd9660_eltorito.h"

#ifdef DEBUG
#define	INODE_WARNX(__x)	warnx __x
#else /* DEBUG */
#define	INODE_WARNX(__x)
#endif /* DEBUG */

#define CD9660MAXPATH 4096

#define ISO_STRING_FILTER_NONE = 0x00
#define ISO_STRING_FILTER_DCHARS = 0x01
#define ISO_STRING_FILTER_ACHARS = 0x02

/*
Extended preferences type, in the spirit of what makefs gives us (only ints)
*/
typedef struct {
	const char  *shortName;		/* Short option */
	const char	*name;		/* option name */
	char		*value;		/* where to stuff the value */
	int		minLength;	/* minimum for value */
	int		maxLength;	/* maximum for value */
	const char	*desc;		/* option description */
	int		filterFlags;
} string_option_t;

/******** STRUCTURES **********/

/*Defaults*/
#define ISO_DEFAULT_VOLUMEID "MAKEFS_CD9660_IMAGE"
#define ISO_DEFAULT_APPID "MAKEFS"
#define ISO_DEFAULT_PUBLISHER "MAKEFS"
#define ISO_DEFAULT_PREPARER "MAKEFS"

#define ISO_VOLUME_DESCRIPTOR_STANDARD_ID "CD001"
#define ISO_VOLUME_DESCRIPTOR_BOOT 0
#define ISO_VOLUME_DESCRIPTOR_PVD 1
#define ISO_VOLUME_DESCRIPTOR_TERMINATOR 255

/*30 for name and extension, as well as version number and padding bit*/
#define ISO_FILENAME_MAXLENGTH_BEFORE_VERSION 30
#define ISO_FILENAME_MAXLENGTH	36
#define ISO_FILENAME_MAXLENGTH_WITH_PADDING 37

#define ISO_FLAG_CLEAR 0x00
#define ISO_FLAG_HIDDEN 0x01
#define ISO_FLAG_DIRECTORY 0x02
#define ISO_FLAG_ASSOCIATED 0x04
#define ISO_FLAG_PERMISSIONS 0x08
#define ISO_FLAG_RESERVED5 0x10
#define ISO_FLAG_RESERVED6 0x20
#define ISO_FLAG_FINAL_RECORD 0x40

#define ISO_PATHTABLE_ENTRY_BASESIZE 8

#define ISO_RRIP_DEFAULT_MOVE_DIR_NAME "RR_MOVED"
#define RRIP_DEFAULT_MOVE_DIR_NAME ".rr_moved"

#define	CD9660_BLOCKS(__sector_size, __bytes)	\
	howmany((__bytes), (__sector_size))

#define CD9660_MEM_ALLOC_ERROR(_F)	\
    err(EXIT_FAILURE, "%s, %s l. %d", _F, __FILE__, __LINE__)

#define CD9660_IS_COMMAND_ARG_DUAL(var,short,long)\
		(strcmp((var),(short)) == 0) || (strcmp((var),(long))==0)

#define CD9660_IS_COMMAND_ARG(var,arg)\
		(strcmp((var),(arg)) == 0)

#define CD9660_TYPE_FILE	0x01
#define CD9660_TYPE_DIR		0x02
#define CD9660_TYPE_DOT		0x04
#define CD9660_TYPE_DOTDOT	0x08
#define CD9660_TYPE_VIRTUAL	0x80

#define CD9660_INODE_HASH_SIZE	1024
#define CD9660_SECTOR_SIZE	2048

#define CD9660_END_PADDING	150

/* Slight modification of the ISO structure in iso.h */
typedef struct _iso_directory_record_cd9660 {
	u_char length			[ISODCL (1, 1)];	/* 711 */
	u_char ext_attr_length		[ISODCL (2, 2)];	/* 711 */
	u_char extent			[ISODCL (3, 10)];	/* 733 */
	u_char size			[ISODCL (11, 18)];	/* 733 */
	u_char date			[ISODCL (19, 25)];	/* 7 by 711 */
	u_char flags			[ISODCL (26, 26)];
	u_char file_unit_size		[ISODCL (27, 27)];	/* 711 */
	u_char interleave		[ISODCL (28, 28)];	/* 711 */
	u_char volume_sequence_number	[ISODCL (29, 32)];	/* 723 */
	u_char name_len			[ISODCL (33, 33)];	/* 711 */
	char name			[ISO_FILENAME_MAXLENGTH_WITH_PADDING];
} iso_directory_record_cd9660;

/* TODO: Lots of optimization of this structure */
typedef struct _cd9660node {
	u_char	type;/* Used internally */
	/* Tree structure */
	struct _cd9660node	*parent;	/* parent (NULL if root) */
	TAILQ_HEAD(cd9660_children_head, _cd9660node)	cn_children;
	TAILQ_ENTRY(_cd9660node)		cn_next_child;

	struct _cd9660node *dot_record; /* For directories, used mainly in RRIP */
	struct _cd9660node *dot_dot_record;

	fsnode		*node;		/* pointer to fsnode */
	struct _iso_directory_record_cd9660	*isoDirRecord;
	struct iso_extended_attributes	*isoExtAttributes;

	/***** SIZE CALCULATION *****/
	/*already stored in isoDirRecord, but this is an int version, and will be
		copied to isoDirRecord on writing*/
	uint32_t fileDataSector;

	/*
	 * same thing, though some notes:
	 * If a file, this is the file size
	 * If a directory, this is the size of all its children's
	 *	directory records
	 * plus necessary padding
	 */
	int64_t fileDataLength;

	int64_t fileSectorsUsed;
	int fileRecordSize;/*copy of a variable, int for quicker calculations*/

	/* Old name, used for renaming - needs to be optimized but low priority */
	char o_name [ISO_FILENAME_MAXLENGTH_WITH_PADDING];

	/***** SPACE RESERVED FOR EXTENSIONS *****/
	/* For memory efficiency's sake - we should move this to a separate struct
		and point to null if not needed */
	/* For Rock Ridge */
	struct _cd9660node *rr_real_parent, *rr_relocated;

	int64_t susp_entry_size;
	int64_t susp_dot_entry_size;
	int64_t susp_dot_dot_entry_size;

	/* Continuation area stuff */
	int64_t susp_entry_ce_start;
	int64_t susp_dot_ce_start;
	int64_t susp_dot_dot_ce_start;

	int64_t susp_entry_ce_length;
	int64_t susp_dot_ce_length;
	int64_t susp_dot_dot_ce_length;

	/* Data to put at the end of the System Use field */
	int64_t su_tail_size;
	char *su_tail_data;

	/*** PATH TABLE STUFF ***/
	int level;			/*depth*/
	int ptnumber;
	struct _cd9660node *ptnext, *ptprev, *ptlast;

	/* SUSP entries */
	TAILQ_HEAD(susp_linked_list, ISO_SUSP_ATTRIBUTES) head;
} cd9660node;

typedef struct _path_table_entry
{
	u_char length[ISODCL (1, 1)];
	u_char extended_attribute_length[ISODCL (2, 2)];
	u_char first_sector[ISODCL (3, 6)];
	u_char parent_number[ISODCL (7, 8)];
	u_char name[ISO_FILENAME_MAXLENGTH_WITH_PADDING];
} path_table_entry;

typedef struct _volume_descriptor
{
	u_char *volumeDescriptorData; /*ALWAYS 2048 bytes long*/
	int64_t sector;
	struct _volume_descriptor *next;
} volume_descriptor;

typedef struct _iso9660_disk {
	int sectorSize;
	struct iso_primary_descriptor		primaryDescriptor;
	struct iso_supplementary_descriptor	supplementaryDescriptor;

	volume_descriptor *firstVolumeDescriptor;

	cd9660node *rootNode;

	/* Important sector numbers here */
	/* primaryDescriptor.type_l_path_table*/
	int64_t primaryBigEndianTableSector;

	/* primaryDescriptor.type_m_path_table*/
	int64_t primaryLittleEndianTableSector;

	/* primaryDescriptor.opt_type_l_path_table*/
	int64_t secondaryBigEndianTableSector;

	/* primaryDescriptor.opt_type_m_path_table*/
	int64_t secondaryLittleEndianTableSector;

	/* primaryDescriptor.path_table_size*/
	int pathTableLength;
	int64_t dataFirstSector;

	int64_t totalSectors;
	/* OPTIONS GO HERE */
	int	isoLevel;

	int include_padding_areas;

	int follow_sym_links;
	int verbose_level;
	int displayHelp;
	int keep_bad_images;

	/* SUSP options and variables */
	int64_t susp_continuation_area_start_sector;
	int64_t susp_continuation_area_size;
	int64_t susp_continuation_area_current_free;

	int rock_ridge_enabled;
	/* Other Rock Ridge Variables */
	char *rock_ridge_renamed_dir_name;
	int rock_ridge_move_count;
	cd9660node *rr_moved_dir;

	int archimedes_enabled;
	int chrp_boot;

	/* Spec breaking options */
	u_char allow_deep_trees;
	u_char allow_start_dot;
	u_char allow_max_name; /* Allow 37 char filenames*/
	u_char allow_illegal_chars; /* ~, !, # */
	u_char allow_lowercase;
	u_char allow_multidot;
	u_char omit_trailing_period;

	/* BOOT INFORMATION HERE */
	int has_generic_bootimage; /* Default to 0 */
	char *generic_bootimage;

	int is_bootable;/* Default to 0 */
	int64_t boot_catalog_sector;
	boot_volume_descriptor *boot_descriptor;
	char * boot_image_directory;

	TAILQ_HEAD(boot_image_list,cd9660_boot_image) boot_images;
	int image_serialno;
	LIST_HEAD(boot_catalog_entries,boot_catalog_entry) boot_entries;

} iso9660_disk;

/******** GLOBAL VARIABLES ***********/
extern iso9660_disk diskStructure;

/************ FUNCTIONS **************/
int			cd9660_valid_a_chars(const char *);
int			cd9660_valid_d_chars(const char *);
void			cd9660_uppercase_characters(char *, int);

/* ISO Data Types */
void			cd9660_721(uint16_t, unsigned char *);
void			cd9660_731(uint32_t, unsigned char *);
void			cd9660_722(uint16_t, unsigned char *);
void			cd9660_732(uint32_t, unsigned char *);
void 			cd9660_bothendian_dword(uint32_t dw, unsigned char *);
void 			cd9660_bothendian_word(uint16_t dw, unsigned char *);
void			cd9660_set_date(char *, time_t);
void			cd9660_time_8426(unsigned char *, time_t);
void			cd9660_time_915(unsigned char *, time_t);

/*** Boot Functions ***/
int	cd9660_write_generic_bootimage(FILE *);
int	cd9660_add_generic_bootimage(const char *);
int	cd9660_write_boot(FILE *);
int	cd9660_add_boot_disk(const char *);
int	cd9660_eltorito_add_boot_option(const char *, const char *);
int	cd9660_setup_boot(int);
int	cd9660_setup_boot_volume_descriptor(volume_descriptor *);

/*** Write Functions ***/
int	cd9660_write_image(const char *image);
int	cd9660_copy_file(FILE *, off_t, const char *);

void	cd9660_compute_full_filename(cd9660node *, char *);
int	cd9660_compute_record_size(cd9660node *);

/* Debugging functions */
void	debug_print_tree(cd9660node *,int);
void	debug_print_path_tree(cd9660node *);
void	debug_print_volume_descriptor_information(void);
void	debug_dump_to_xml_ptentry(path_table_entry *,int, int);
void	debug_dump_to_xml_path_table(FILE *, off_t, int, int);
void	debug_dump_to_xml(FILE *);
int	debug_get_encoded_number(unsigned char *, int);
void	debug_dump_integer(const char *, char *,int);
void	debug_dump_string(const char *,unsigned char *,int);
void	debug_dump_directory_record_9_1(unsigned char *);
void	debug_dump_to_xml_volume_descriptor(unsigned char *,int);

void	cd9660_pad_string_spaces(char *, int);

#endif


text: ©<?=date('Y')?> IT-JIEP. All Rights Reserved


text:
module Snoopy
  class Client
    attr_accessor :savon

    def initialize(attrs)
      @savon = Savon.client(attrs)
    end

    def call service, args={}
      Timeout::timeout(Snoopy.open_timeout) do
        savon.call(service, args).body
      end
    rescue Timeout::Error
      raise Snoopy::Exception::ServerTimeout.new
    rescue => e
      raise Snoopy::Exception::ClientError.new(e.message)
    end

  end
end


text:
package java.io;

import java.util.ArrayList;

import com.google.gwt.storage.client.Storage;

/** LocalStorage based File implementation for GWT. Should probably have used Harmony as a starting point instead of writing this
 * from scratch.
 *
 * @author Stefan Haustein */
public class File {

	public static final File ROOT = new File("");

	public static final char separatorChar = '/';

	public static final String separator = "" + separatorChar;

	public static final char pathSeparatorChar = ':';

	public static final String pathSeparator = "" + pathSeparatorChar;

	public static final Storage LocalStorage = Storage.getLocalStorageIfSupported();

	File parent;
	String name;
	boolean absolute;

	public File (String pathname) {
		while (pathname.endsWith(separator) && pathname.length() > 0) {
			pathname = pathname.substring(0, pathname.length() - 1);
		}

		int cut = pathname.lastIndexOf(separatorChar);
		if (cut == -1) {
			name = pathname;
		} else if (cut == 0) {
			name = pathname.substring(cut);
			parent = name.equals("") ? null : ROOT;
		} else {
			name = pathname.substring(cut + 1);
			parent = new File(pathname.substring(0, cut));
		}

// Compatibility.println("new File ('"+pathname+ "'); canonical name: '" + getCanonicalPath() + "'");
	}

	public File (String parent, String child) {
		this(new File(parent), child);
	}

	public File (File parent, String child) {
		this.parent = parent;
		this.name = child;
	}

	/*
	 * public File(URI uri) { }
	 */

	public String getName () {
		return name;
	}

	public String getParent () {
		return parent == null ? "" : parent.getPath();
	}

	public File getParentFile () {
		return parent;
	}

	public String getPath () {
		return parent == null ? name : (parent.getPath() + separatorChar + name);
	}

	private boolean isRoot () {
		return name.equals("") && parent == null;
	}

	public boolean isAbsolute () {
		if (isRoot()) {
			return true;
		}
		if (parent == null) {
			return false;
		}
		return parent.isAbsolute();
	}

	public String getAbsolutePath () {
		String path = getAbsoluteFile().getPath();
		return path.length() == 0 ? "/" : path;
	}

	public File getAbsoluteFile () {
		if (isAbsolute()) {
			return this;
		}
		if (parent == null) {
			return new File(ROOT, name);
		}
		return new File(parent.getAbsoluteFile(), name);
	}

	public String getCanonicalPath () {
		return getCanonicalFile().getAbsolutePath();
	}

	public File getCanonicalFile () {
		File cParent = parent == null ? null : parent.getCanonicalFile();
		if (name.equals(".")) {
			return cParent == null ? ROOT : cParent;
		}
		if (cParent != null && cParent.name.equals("")) {
			cParent = null;
		}
		if (name.equals("..")) {
			if (cParent == null) {
				return ROOT;
			}
			if (cParent.parent == null) {
				return ROOT;
			}
			return cParent.parent;
		}
		if (cParent == null && !name.equals("")) {
			return new File(ROOT, name);
		}
		return new File(cParent, name);
	}

	/*
	 * public URL toURL() throws MalformedURLException { }
	 *
	 * public URI toURI() { }
	 */

	public boolean canRead () {
		return true;
	}

	public boolean canWrite () {
		return true;
	}

	public boolean exists () {
		return LocalStorage.getItem(getCanonicalPath()) != null;
	}

	public boolean isDirectory () {
		String s = LocalStorage.getItem(getCanonicalPath());
		return s != null && s.startsWith("{");
	}

	public boolean isFile () {
		String s = LocalStorage.getItem(getCanonicalPath());
		return s != null && !s.startsWith("{");
	}

	public boolean isHidden () {
		return false;
	}

	public long lastModified () {
		return 0;
	}

	public long length () {
		try {
			if (!exists()) {
				return 0;
			}

			RandomAccessFile raf = new RandomAccessFile(this, "r");
			long len = raf.length();
			raf.close();
			return len;
		} catch (IOException e) {
			return 0;
		}
	}

	public boolean createNewFile () throws IOException {
		if (exists()) return false;
		if (!parent.exists()) return false;
		LocalStorage.setItem(getCanonicalPath(), RandomAccessFile.btoa(""));
		return true;
	}

	public boolean delete () {
		if (!exists()) {
			return false;
		}
		LocalStorage.removeItem(getCanonicalPath());
		return true;
	}

	public void deleteOnExit () {
		throw new RuntimeException("NYI: File.deleteOnExit()");
	}

	public String[] list () {
		throw new RuntimeException("NYI: File.list()");
	}

	/*
	 * public String[] list(FilenameFilter filter) { return null; }
	 */

	public File[] listFiles () {
		return listFiles(null);
	}

	public File[] listFiles (FilenameFilter filter) {
		ArrayList<File> files = new ArrayList<File>();
		String prefix = getCanonicalPath();
		if (!prefix.endsWith(separator)) {
			prefix += separatorChar;
		}
		int cut = prefix.length();
		int cnt = LocalStorage.getLength();
		for (int i = 0; i < cnt; i++) {
			String key = LocalStorage.key(i);
			if (key.startsWith(prefix) && key.indexOf(separatorChar, cut) == -1) {
				String name = key.substring(cut);
				if (filter == null || filter.accept(this, name)) {
					files.add(new File(this, name));
				}
			}
		}
		return files.toArray(new File[files.size()]);
	}

	/*
	 * public File[] listFiles(FileFilter filter) { return null; }
	 */

	public boolean mkdir () {
		if (parent != null && !parent.exists()) {
			return false;
		}
		if (exists()) {
			return false;
		}
		// We may want to make this a JS map
		LocalStorage.setItem(getCanonicalPath(), "{}");
		return true;
	}

	public boolean mkdirs () {
		if (parent != null) {
			parent.mkdirs();
		}
		return mkdir();
	}

	public boolean renameTo (File dest) {
		throw new RuntimeException("renameTo()");
	}

	public boolean setLastModified (long time) {
		return false;
	}

	public boolean setReadOnly () {
		return false;
	}

	public static File[] listRoots () {
		return new File[] {ROOT};
	}

	public static File createTempFile (String prefix, String suffix, File directory) throws IOException {
		throw new RuntimeException("NYI: createTempFile");
	}

	public static File createTempFile (String prefix, String suffix) throws IOException {
		throw new RuntimeException("NYI: createTempFile");
	}

	public int compareTo (File pathname) {
		throw new RuntimeException("NYI: File.compareTo()");
	}

	public boolean equals (Object obj) {
		if (!(obj instanceof File)) {
			return false;
		}
		return getPath().equals(((File)obj).getPath());
	}

	public int hashCode () {
		return parent != null ? parent.hashCode() + name.hashCode() : name.hashCode();
	}

	public String toString () {
		return name;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements.  See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership.  The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License.  You may obtain a copy of the License at
~
~     http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>atlas-graphdb</artifactId>
        <groupId>org.apache.atlas</groupId>
        <version>0.8-graphdb-SNAPSHOT</version>
    </parent>
    <artifactId>atlas-graphdb-titan0</artifactId>
    <description>Apache Atlas Titan 0.5 Graph DB Impl</description>
    <name>Apache Atlas Titan 0.5 Plugin</name>
    <packaging>jar</packaging>

    <properties>
        <checkstyle.failOnViolation>true</checkstyle.failOnViolation>
        <tinkerpop.version>2.6.0</tinkerpop.version>
        <titan.version>0.5.4</titan.version>
    </properties>

    <dependencies>

        <!-- for graphdb interface definitions -->
        <dependency>
            <groupId>org.apache.atlas</groupId>
            <artifactId>atlas-graphdb-api</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.thinkaurelius.titan</groupId>
            <artifactId>titan-core</artifactId>
	    <version>0.5.4</version>
        </dependency>

        <dependency>
            <groupId>com.tinkerpop.blueprints</groupId>
            <artifactId>blueprints-core</artifactId>
	    <version>2.6.0</version>
        </dependency>

        <dependency>
            <groupId>com.tinkerpop.gremlin</groupId>
            <artifactId>gremlin-java</artifactId>
	    <version>2.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
        </dependency>

        <dependency>
            <groupId>com.thinkaurelius.titan</groupId>
            <artifactId>titan-es</artifactId>
	    <version>0.5.4</version>
        </dependency>

        <dependency>
            <groupId>com.thinkaurelius.titan</groupId>
            <artifactId>titan-berkeleyje</artifactId>
	    <version>0.5.4</version>
        </dependency>

        <dependency>
            <groupId>com.thinkaurelius.titan</groupId>
            <artifactId>titan-lucene</artifactId>
	    <version>0.5.4</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!--
                 Create 'uber' jar that contains all of the dependencies (except those whose scope is provided)
                 Only titan 0 and its dependencies are included.  The other dependencies are bundled in the war file.

                We also relocate the Google guava packages because Titan 0.5.4 and Titan 1 use different (and incompatible)
                versions of Guava.  This decouples the version of Guava used directly by Atlas from the version
                required by graph database implementations.
            -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>false</shadedArtifactAttached>
                            <artifactSet>
                                <excludes>
                                    <!-- these are bundled with Atlas -->
                                    <exclude>org.slf4j:*</exclude>
                                </excludes>
                            </artifactSet>
                            <filters>
                                <filter>
                                    <artifact>com.thinkaurelius.titan:titan-core</artifact>
                                    <!-- force use of our custom LocalLockMediator implementation -->
                                    <excludes>
                                        <exclude>com/thinkaurelius/titan/diskstorage/locking/LocalLockMediator*</exclude>
                                    </excludes>
                                </filter>

                            </filters>
                            <relocations>
                                <relocation>
                                    <pattern>com.google.common</pattern>
                                    <shadedPattern>org.apache.atlas.shaded.com.google.common</shadedPattern>
                                </relocation>
                            </relocations>
                            <createSourcesJar>true</createSourcesJar>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <excludes>
                        <exclude>**/log4j.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <!-- Graph DB -->
            <dependency>
                <groupId>com.tinkerpop.blueprints</groupId>
                <artifactId>blueprints-core</artifactId>
                <version>2.6.0</version>
            </dependency>

            <dependency>
                <groupId>com.thinkaurelius.titan</groupId>
                <artifactId>titan-core</artifactId>
                <version>0.5.4</version>
                <exclusions>
                    <!-- rexster does not work with servlet-api -->
                    <exclusion>
                        <groupId>com.tinkerpop.rexster</groupId>
                        <artifactId>rexster-core</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>com.tinkerpop.rexster</groupId>
                        <artifactId>rexster-server</artifactId>
                    </exclusion>
                    <!-- asm 4.0 does not work with jersey asm 3.1 -->
                    <exclusion>
                        <groupId>com.tinkerpop</groupId>
                        <artifactId>frames</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>com.esotericsoftware.reflectasm</groupId>
                        <artifactId>reflectasm</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.ow2.asm</groupId>
                        <artifactId>asm</artifactId>
                    </exclusion>
                    <exclusion> <!-- GPL license imported from ganglia -->
                        <groupId>org.acplt</groupId>
                        <artifactId>oncrpc</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>com.thinkaurelius.titan</groupId>
                <artifactId>titan-berkeleyje</artifactId>
                <version>0.5.4</version>
            </dependency>

            <dependency>
                <groupId>com.thinkaurelius.titan</groupId>
                <artifactId>titan-hbase</artifactId>
                <version>0.5.4</version>
            </dependency>

        </dependencies>
    </dependencyManagement>
</project>


text:
package org.motechproject.mtraining.service.ut;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.mds.util.InstanceSecurityRestriction;
import org.motechproject.mtraining.repository.PropertiesMapQueryExecution;

import javax.jdo.Query;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

public class PropertiesMapQueryExecutionTest {

    private static final String KEY_1 = "key_1";
    private static final String KEY_2 = "key_2";
    private static final String VALUE_1 = "value_1";

    @Mock
    private Query query;

    @Mock
    private InstanceSecurityRestriction instanceSecurityRestriction;

    @Before
    public void setup() {
        initMocks(this);
    }

    @Test
    public void shouldBuildCorrectFilterWithoutMap() {
        PropertiesMapQueryExecution queryExecution = new PropertiesMapQueryExecution(null);
        queryExecution.execute(query, instanceSecurityRestriction);

        verify(query).setFilter("");
    }

    @Test
    public void shouldBuildCorrectFilter() {
        Map<String, String> properties = new HashMap<>();
        properties.put(KEY_1, VALUE_1);

        PropertiesMapQueryExecution queryExecution = new PropertiesMapQueryExecution(properties);
        queryExecution.execute(query, instanceSecurityRestriction);

        verify(query).setFilter(String.format("(properties.containsKey('key_1') && properties.get('key_1') == 'value_1')"));

        properties.put(KEY_2, "");

        queryExecution = new PropertiesMapQueryExecution(properties);
        queryExecution.execute(query, instanceSecurityRestriction);

        verify(query).setFilter(String.format("(properties.containsKey('key_2') && properties.get('key_2') == '') && (properties.containsKey('key_1') && properties.get('key_1') == 'value_1')"));
    }
}


text:
package org.apache.isis.core.metamodel.adapter.oid;

import java.util.Arrays;
import java.util.List;

import org.apache.isis.core.metamodel.adapter.oid.Oid.State;
import org.apache.isis.core.metamodel.spec.ObjectSpecId;
import org.apache.isis.core.unittestsupport.value.ValueTypeContractTestAbstract;

public class RootOidDefaultTest_valueSemantics_whenTransient extends ValueTypeContractTestAbstract<RootOidDefault> {

    @Override
    protected List<RootOidDefault> getObjectsWithSameValue() {
        return Arrays.asList(
            new RootOidDefault(ObjectSpecId.of("CUS"), "123", State.TRANSIENT),
            new RootOidDefault(ObjectSpecId.of("CUS"), "123", State.TRANSIENT),
            new RootOidDefault(ObjectSpecId.of("CUS"), "123", State.TRANSIENT)
            );
    }

    @Override
    protected List<RootOidDefault> getObjectsWithDifferentValue() {
        return Arrays.asList(
            new RootOidDefault(ObjectSpecId.of("CUS"), "123", State.PERSISTENT),
            new RootOidDefault(ObjectSpecId.of("CUS"), "124", State.TRANSIENT),
            new RootOidDefault(ObjectSpecId.of("CUX"), "123", State.TRANSIENT));
    }

}


text:
namespace StevensDev
{
namespace sgdm
{

template <class T>
class CountingAllocator: public DefaultAllocator<T>
{
  private:
    int d_allocationCount;
    int d_releaseCount;
    static int d_totalAllocationCount;
    static int d_totalReleaseCount;
  public:
    // CONSTRUCTORS
    CountingAllocator();
      // Default constructor
    CountingAllocator( const CountingAllocator<T> &copy );
      // Copy constructor

    // DESTRUCTOR
    ~CountingAllocator();

    // OPERATORS
    CountingAllocator<T>& operator= (const CountingAllocator<T>& other);

    // ACCESSORS
    int const getAllocationCount() const;
      // returns number of allocations that occurred
    int const getReleaseCount() const;
      // returns number of releases that occured
    int const getOutstandingCount() const;
      // returns number of outstanding allocations
    static int getTotalAllocationCount();
      // returns number of allocations that occurred across instances
    static int getTotalReleaseCount();
      // returns number of releases that occurred across instances
    static int getTotalOutstandingCount();
      // returns number of outstanding alloations across instances

    // MUTATORS (?)
    T* get( int count );
      // Allocates enough memory for count number of Ts
    void release( T* pointer, int count);
      // Releases the memory in ptr, which should be size count.
};

// DECLARATIONS OF STATIC VARIABLES
template<class T>
int CountingAllocator<T>::d_totalAllocationCount = 0;
template<class T>
int CountingAllocator<T>::d_totalReleaseCount = 0;

// FREE OPERATORS
template<class T>
inline
std::ostream& operator<<( std::ostream& stream, const CountingAllocator<T>& alloc)
{
    return stream << "{\"allocation count\":\"" << alloc.getAllocationCount() << "\","
                  << "\"release count\":\"" << alloc.getReleaseCount() << "\"}";
}

// OPERATORS
template<class T>
inline
CountingAllocator<T>& CountingAllocator<T>::operator= (const CountingAllocator<T>& other)
{
    if( this != &other )
    {
        CountingAllocator<T> newAlloc ( other );
        return newAlloc;
    }
    else
        return *this;
}

// CONSTRUCTORS
template<class T>
inline
CountingAllocator<T>::CountingAllocator()
{
    d_allocationCount = 0;
    d_releaseCount = 0;
}

template<class T>
inline
CountingAllocator<T>::CountingAllocator( const CountingAllocator<T> &copy )
{
    d_allocationCount = copy.getAllocationCount();
    d_releaseCount = copy.getReleaseCount();
    //std::cout << "copied allocation count: " << copy.getAllocationCount() << "\n";
    //std::cout << "new allocation count: " << d_allocationCount << "\n";
}

// DESTRUCTOR
template<class T>
inline
CountingAllocator<T>::~CountingAllocator()
{
}

// ACCESSORS
template<class T>
inline
int const CountingAllocator<T>::getAllocationCount() const
{
    return d_allocationCount;
}

template<class T>
inline
int const CountingAllocator<T>::getReleaseCount() const
{
    //std::cout << "IN GET RELEASE COUNT: " << d_releaseCount << std::endl;
    return d_releaseCount;
}

template<class T>
inline
int const CountingAllocator<T>::getOutstandingCount() const
{
    return d_allocationCount - d_releaseCount;
}

template<class T>
inline
int CountingAllocator<T>::getTotalAllocationCount()
{
    return d_totalAllocationCount;
}

template<class T>
inline
int CountingAllocator<T>::getTotalReleaseCount()
{
    return d_totalReleaseCount;
}

template<class T>
inline
int CountingAllocator<T>::getTotalOutstandingCount()
{
    return d_totalAllocationCount - d_totalReleaseCount;
}

// MUTATORS
template<class T>
inline
T* CountingAllocator<T>::get( int count )
{
    d_allocationCount += count;
    d_totalAllocationCount += count;
    return DefaultAllocator<T>::get( count );
}

template<class T>
inline
void CountingAllocator<T>::release( T* pointer, int count )
{
    assert( d_allocationCount - d_releaseCount != 0 );
    d_releaseCount += count;
    d_totalReleaseCount += count;
    DefaultAllocator<T>::release( pointer, count );

};

} // End sgdm namespace
} // End StevensDev namespace

#endif


text:
var FS = require('q-io/fs');
var Q = require('q');
var path = require('path');
var cordova_lib = require('../lib/cordova').lib;
var events = cordova_lib.events;

module.exports = help;

function help(opts)
{
	var args = opts || [];
	var command = ((args)[0] || 'general');
	return Q.fcall( () => {
		return FS.read( path.join(__dirname, "..", "help", `${command}.txt`))
		.then(function (helpDoc) {
			events.emit("log", helpDoc);
		});
	})
	.catch((error) => {
		var name = require("../package").name;
		events.emit("error", `'help ${command}' is not a ${name} command. See '${name} help'`);
	});
}


text:
if (typeof Effect == 'undefined')
        throw("tabs.js requires including script.aculo.us' effects.js library!");

var tabset = Class.create();

tabset.prototype = {
  tabs:           [],
  panels:         [],
  showPanel:     null,
  currentPanel:  null,

  initialize: function(container, options) {
    this.options = Object.extend({
      classNames: {
        tab:        'tab',
        panel:      'panel',
        tabActive:  'selected'
      },
      ids: {
        tab:        'tab_',
        panel:      'panel_'
      },
      onEvent:      'click',
      effects:      true
    }, options || {} );

    container = $(container);

    this.tabs = container.select('.'+this.options.classNames.tab);
    this.tabs.each(function(tab) {
      Event.observe(tab, this.options.onEvent, this.activate.bind(this, tab), false);
    }.bind(this));

    this.panels = container.select('.'+this.options.classNames.panel);
    this.panels.invoke('hide');
  },

  activate: function(tab) {
    var tabName = tab.id.replace(this.options.ids.tab,'');
    this.currentPanel = this.options.ids.panel+tabName;
    if (this.showPanel == this.currentPanel) {
      return false;
    }

    if (this.showPanel) {
      if (this.options.effects) {
        new Effect.Fade(this.showPanel, {queue: 'front'});
      } else {
        $(this.showPanel).hide();
      }
    }

    if (this.options.effects) {
      new Effect.Appear(this.currentPanel, {queue: 'end'});
    } else {
      $(this.currentPanel).show();
    }

    this.tabs.invoke('removeClassName', this.options.classNames.tabActive);
    tab.addClassName(this.options.classNames.tabActive);
    this.showPanel = this.currentPanel;
  },

  getHash: function() {
    var hash = window.location.hash;
    return hash.substring(1); // remove #
  },

  autoActivate: function(tab) {
    var canDoAuto = false;
    var hash = this.getHash();
    if (hash) {
      var autoTab = $(this.options.ids.tab+hash);
      if (autoTab) {
        this.activate(autoTab);
        canDoAuto = true;
      }
    }
    if (!canDoAuto && tab) {
      this.activate(tab);
    }
  }
}


text:
#ifndef BERRYDETACHEDWINDOW_H_
#define BERRYDETACHEDWINDOW_H_

#include "berryPartStack.h"
#include "berryWorkbenchPage.h"
#include "berryLayoutPart.h"
#include "berryIDragOverListener.h"
#include "berryIShellListener.h"
#include "guitk/berryGuiTkIControlListener.h"

#include "berryRectangle.h"
#include "berryShell.h"

namespace berry
{

/**
 * TODO: Drag from detached to fast view bar back to detached causes NPE
 *
 * @since 3.1
 */
class DetachedWindow: public IPropertyChangeListener,
    public IDragOverListener
{

public:
  berryObjectMacro(DetachedWindow);

private:
  PartStack::Pointer folder;

  WorkbenchPage* page;

  Rectangle bounds;

  Shell::Pointer windowShell;

  bool hideViewsOnClose;

  struct ShellListener: public IShellListener
  {
    ShellListener(DetachedWindow* wnd);

    void ShellClosed(ShellEvent::Pointer e);

  private:
    DetachedWindow* window;
  };

  IShellListener::Pointer shellListener;

  struct ShellControlListener: public GuiTk::IControlListener
  {

    ShellControlListener(DetachedWindow* wnd);

    Events::Types GetEventTypes() const;

    void ControlResized(GuiTk::ControlEvent::Pointer e);

  private:
    DetachedWindow* window;
  };

  GuiTk::IControlListener::Pointer resizeListener;

  //      Listener activationListener = new Listener() {
  //          public void handleEvent(Event event) {
  //            switch (event.type) {
  //            case SWT.Activate:
  //              page.window.liftRestrictions();
  //              break;
  //            case SWT.Deactivate:
  //              page.window.imposeRestrictions();
  //              break;
  //            }
  //          }
  //      };

  IWorkbenchPartReference::Pointer activePart;

public:

  /**
   * Create a new FloatingWindow.
   */
  DetachedWindow(WorkbenchPage* workbenchPage);

  void PropertyChange(Object::Pointer source, int propId);

  Shell::Pointer GetShell();

  void Create();

  /**
   * Adds a visual part to this window.
   * Supports reparenting.
   */
  void Add(LayoutPart::Pointer part);

  bool BelongsToWorkbenchPage(IWorkbenchPage::Pointer workbenchPage);

  bool Close();

  /*
   * @see org.blueberry.ui.internal.IDragOverListener#Drag(void*, Object::Pointer, const Point&, const Rectangle& )
   */
  IDropTarget::Pointer Drag(void* currentControl,
      Object::Pointer draggedObject, const Point& position,
      const Rectangle& dragRectangle);

  ILayoutContainer::ChildrenType GetChildren() const;

  WorkbenchPage::Pointer GetWorkbenchPage();

  /**
   * @see IPersistablePart
   */
  void RestoreState(IMemento::Pointer memento);

  /**
   * @see IPersistablePart
   */
  void SaveState(IMemento::Pointer memento);

  void* GetControl();

  /**
   * Opens the detached window.
   */
  int Open();

protected:

  void ActivePartChanged(IWorkbenchPartReference::Pointer partReference);

  /**
   * This method will be called to initialize the given Shell's layout
   */
  void ConfigureShell(Shell::Pointer shell);

  /**
   * Override this method to create the widget tree that is used as the window's contents.
   */
  void* CreateContents(void* parent);

private:

  void UpdateTitle();

  /**
   * Ensure that the shell's minimum size is equal to the minimum size
   * of the first part added to the shell.
   */
  void UpdateMinimumSize();

  static IWorkbenchPartReference::Pointer GetPartReference(
      LayoutPart::Pointer pane);

  /**
   * Closes this window and disposes its shell.
   */
  bool HandleClose();

  /**
   * Prompts for and handles the saving of dirty, saveable views
   * @param views The list of ViewPanes
   * @return true unless the user cancels the save(s)
   */
  bool HandleSaves(std::list<PartPane::Pointer> views);

  /**
   * Answer a list of the view panes.
   */
  void CollectViewPanes(std::list<PartPane::Pointer>& result,
      const std::list<LayoutPart::Pointer>& parts);

};

}

#endif /* BERRYDETACHEDWINDOW_H_ */


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest 1.0.x release of this document can be found
[here](http://releases.k8s.io/release-1.0/docs/design/versioning.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Kubernetes API and Release Versioning

Legend:

* **Kube <major>.<minor>.<patch>** refers to the version of Kubernetes that is released. This versions all components: apiserver, kubelet, kubectl, etc.
* **API vX[betaY]** refers to the version of the HTTP API.

## Release Timeline

### Minor version scheme and timeline

* Kube 1.0.0, 1.0.1 -- DONE!
* Kube 1.0.X (X>1): Standard operating procedure. We patch the release-1.0 branch as needed and increment the patch number.
* Kube 1.1.0-alpha.X: Released roughly every two weeks by cutting from HEAD. No cherrypick releases. If there is a critical bugfix, a new release from HEAD can be created ahead of schedule. (This applies to the beta releases as well.)
* Kube 1.1.0-beta.X: When HEAD is feature-complete, we go into code freeze 2 weeks prior to the desired 1.1.0 date and only merge PRs essential to 1.1. Releases continue to be cut from HEAD until we're essentially done.
* Kube 1.1.0: Final release. Should occur between 3 and 4 months after 1.0.

### Major version timeline

There is no mandated timeline for major versions. They only occur when we need to start the clock on deprecating features. A given major version should be the latest major version for at least one year from its original release date.

## Release versions as related to API versions

Here is an example major release cycle:

* **Kube 1.0 should have API v1 without v1beta\* API versions**
 * The last version of Kube before 1.0 (e.g. 0.14 or whatever it is) will have the stable v1 API. This enables you to migrate all your objects off of the beta API versions of the API and allows us to remove those beta API versions in Kube 1.0 with no effect. There will be tooling to help you detect and migrate any v1beta\* data versions or calls to v1 before you do the upgrade.
* **Kube 1.x may have API v2beta***
 * The first incarnation of a new (backwards-incompatible) API in HEAD is v2beta1. By default this will be unregistered in apiserver, so it can change freely. Once it is available by default in apiserver (which may not happen for several minor releases), it cannot change ever again because we serialize objects in versioned form, and we always need to be able to deserialize any objects that are saved in etcd, even between alpha versions. If further changes to v2beta1 need to be made, v2beta2 is created, and so on, in subsequent 1.x versions.
* **Kube 1.y (where y is the last version of the 1.x series) must have final API v2**
 * Before Kube 2.0 is cut, API v2 must be released in 1.x. This enables two things: (1) users can upgrade to API v2 when running Kube 1.x and then switch over to Kube 2.x transparently, and (2) in the Kube 2.0 release itself we can cleanup and remove all API v2beta\* versions because no one should have v2beta\* objects left in their database. As mentioned above, tooling will exist to make sure there are no calls or references to a given API version anywhere inside someone's kube installation before someone upgrades.
 * Kube 2.0 must include the v1 API, but Kube 3.0 must include the v2 API only. It *may* include the v1 API as well if the burden is not high - this will be determined on a per-major-version basis.

## Rationale for API v2 being complete before v2.0's release

It may seem a bit strange to complete the v2 API before v2.0 is released, but *adding* a v2 API is not a breaking change. *Removing* the v2beta\* APIs *is* a breaking change, which is what necessitates the major version bump. There are other ways to do this, but having the major release be the fresh start of that release's API without the baggage of its beta versions seems most intuitive out of the available options.

# Patches

Patch releases are intended for critical bug fixes to the latest minor version, such as addressing security vulnerabilities, fixes to problems affecting a large number of users, severe problems with no workaround, and blockers for products based on Kubernetes.

They should not contain miscellaneous feature additions or improvements, and especially no incompatibilities should be introduced between patch versions of the same minor version (or even major version).

Dependencies, such as Docker or Etcd, should also not be changed unless absolutely necessary, and also just to fix critical bugs (so, at most patch version changes, not new major nor minor versions).

# Upgrades

* Users can upgrade from any Kube 1.x release to any other Kube 1.x release as a rolling upgrade across their cluster. (Rolling upgrade means being able to upgrade the master first, then one node at a time. See #4855 for details.)
* No hard breaking changes over version boundaries.
 * For example, if a user is at Kube 1.x, we may require them to upgrade to Kube 1.x+y before upgrading to Kube 2.x. In others words, an upgrade across major versions (e.g. Kube 1.x to Kube 2.x) should effectively be a no-op and as graceful as an upgrade from Kube 1.x to Kube 1.x+1. But you can require someone to go from 1.x to 1.x+y before they go to 2.x.

There is a separate question of how to track the capabilities of a kubelet to facilitate rolling upgrades. That is not addressed here.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/design/versioning.md?pixel)]()


text:
nas2end!(v::AbstractVector, o::Base.Sort.ForwardOrdering) = nas2right!(v,o)
nas2end!(v::AbstractVector, o::Base.Sort.ReverseOrdering) = nas2left!(v,o)
nas2end!{O<:Base.Order.ForwardOrdering}(v::AbstractVector{Int}, o::Base.Order.Perm{O}) = nas2right!(v,o)
nas2end!{O<:Base.Order.ReverseOrdering}(v::AbstractVector{Int}, o::Base.Order.Perm{O}) = nas2left!(v,o)

myisna(o::Base.Order.Ordering, chunks, i::Int) = Base.unsafe_bitgetindex(chunks, i)

swap(o::Base.Order.DirectOrdering, data, i, j) = setindex!(data, data[i], j)
function swap(o::Base.Order.Perm, data, i, j)
    data[j], data[i] = data[i], data[j]
end

datachunks(o::Base.Order.Perm, v::AbstractVector{Int}) = (v, o.data.na.chunks)
datachunks(o::Base.Order.DirectOrdering, v::DataVector) = (v.data, v.na.chunks)

function nas2left!(v::Union(AbstractVector{Int}, DataVector), o::Base.Order.Ordering, lo::Int=1, hi::Int=length(v))
    data, chunks = datachunks(o, v)

    i = lo
    @inbounds while i <= hi && myisna(o, chunks, i)
        i += 1
    end
    j = i + 1
    @inbounds while j <= hi
        if myisna(o, chunks, j)
            swap(o, data, i, j)
            i += 1
        end
        j += 1
    end
    if isa(o, Base.Order.DirectOrdering)
        v.na[lo:i-1] = true
        v.na[i:hi] = false
    end
    return i, hi
end

function nas2right!(v::Union(AbstractVector{Int}, DataVector), o::Base.Order.Ordering, lo::Int=1, hi::Int=length(v))
    data, chunks = datachunks(o, v)

    i = hi
    @inbounds while lo <= i && myisna(o, chunks, i)
        i -= 1
    end
    j = i - 1
    @inbounds while lo <= j
        if myisna(o, chunks, j)
            swap(o, data, i, j)
            i -= 1
        end
        j -= 1
    end
    if isa(o, Base.Order.DirectOrdering)
        v.na[lo:i] = false
        v.na[i+1:hi] = true
    end
    return lo, i
end

function dasort!(v::DataVector, a::Base.Sort.Algorithm, o::Base.Order.DirectOrdering)
    lo, hi = nas2end!(v, o)
    sort!(v.data, lo, hi, a, o)
    v
end

function dapermsort!{O<:Base.Order.DirectOrdering,T<:DataVector}(v::AbstractVector{Int}, a::Base.Sort.Algorithm, o::Base.Order.Perm{O,T})
    lo, hi = nas2end!(v, o)
    sort!(v, lo, hi, a, Base.Order.Perm(o.order, o.data.data))
end

Base.sort!(v::DataVector, a::Base.Sort.Algorithm, o::Base.Order.DirectOrdering) = dasort!(v,a,o)
Base.sort!{O<:Base.Order.DirectOrdering,T<:DataVector}(v::Vector{Int}, a::Base.Sort.Algorithm, o::Base.Order.Perm{O,T}) = dapermsort!(v,a,o)


text:
layout: default
description: This page will guide you through the process of a manual upgrade of a clustersetup
---
Manually Upgrading a _Cluster_ Deployment
=========================================

This page will guide you through the process of a manual upgrade of a [_cluster_](architecture-deployment-modes-cluster-architecture.html)
setup. The different nodes in a _cluster_ can be upgraded one at a time without
incurring downtime of the _cluster_ and very short downtimes of the single nodes.

The manual upgrade procedure described in this _Section_ can be used to upgrade
to a new hotfix, or to perform an upgrade to a new minor version of ArangoDB.
Please refer to the [Upgrade Paths](upgrading-general-info.html#upgrade-paths) section
for detailed information.

Preparations
------------

The ArangoDB installation packages (e.g. for Debian or Ubuntu) set up a
convenient standalone instance of `arangod`. During installation, this instance's
database will be upgraded (see [`--database.auto-upgrade`](programs-arangod-database.html#auto-upgrade))
and the service will be (re)started.

You have to make sure that your _cluster_ deployment is independent of this
standalone instance. Specifically, make sure that the database directory as
well as the socket used by the standalone instance provided by the package are
separate from the ones in your _cluster_ configuration. Also, that you haven't
modified the init script or systemd unit file for the standalone instance in way
that it would start or stop your _cluster_ instance instead.

You can read about the details on how to deploy your _cluster_ independently of the
standalone instance in the [_cluster_ deployment preliminary](deployment-cluster.html).

In the following, we assume that you don't use the standalone instance from the
package but only a manually started _cluster_ instance, and we will move the
standalone instance out of the way if necessary so you have to make as little
changes as possible to the running _cluster_.

### Install the new ArangoDB version binary

The first step is to install the new ArangoDB package.

**Note:** you do not have to stop the _cluster_ (_arangod_) processes before upgrading it.

For example, if you want to upgrade to `3.7.13` on Debian or Ubuntu, either call

```
$ apt install arangodb=3.7.13
```

(`apt-get` on older versions) if you have added the ArangoDB repository. Or
install a specific package using

```
$ dpkg -i arangodb3-3.7.13-1_amd64.deb
```

after you have downloaded the corresponding file from
[download.arangodb.com](https://download.arangodb.com/){:target="_blank"}.

#### Stop the Standalone Instance

As the package will automatically start the standalone instance, you might want to
stop it now, as otherwise this standalone instance that is started on your machine
can create some confusion later. As you are starting the _cluster_ processes manually
you do not need this standalone instance, and you can hence stop it:

```
$ service arangodb3 stop
```

Also, you might want to remove the standalone instance from the default
_runlevels_ to prevent it to start on the next reboot of your machine. How this
is done depends on your distribution and _init_ system. For example, on older Debian
and Ubuntu systems using a SystemV-compatible _init_, you can use:

```
$ update-rc.d -f arangodb3 remove
```

Set supervision in maintenance mode
-----------------------------------

It is required to disable _cluster_ supervision in order to upgrade your _cluster_. The
following API calls will activate and de-activate the Maintenance mode of the Supervision job:

You might use _curl_ to send the API call.

### Activate Maintenance mode

`curl -u username:password <coordinator>/_admin/cluster/maintenance -XPUT -d'"on"'`

For Example:
```
curl http://localhost:7002/_admin/cluster/maintenance -XPUT -d'"on"'

{"error":false,"warning":"Cluster supervision deactivated.
It will be reactivated automatically in 60 minutes unless this call is repeated until then."}
```
**Note:** In case the manual upgrade takes longer than 60 minutes, the API call has to be resend.

### Deactivate Maintenance mode

The _cluster_ supervision reactivates 60 minutes after disabling it.
It can be manually reactivated by the following API call:

`curl -u username:password <coordinator>/_admin/cluster/maintenance -XPUT -d'"off"'`

For example:
```
curl http://localhost:7002/_admin/cluster/maintenance -XPUT -d'"off"'

{"error":false,"warning":"Cluster supervision reactivated."}
```

Upgrade the _cluster_ processes
-------------------------------

Now all the _cluster_ (_Agents_, _DB-Servers_ and _Coordinators_) processes (_arangod_) have to be
upgraded on each node.

**Note:** The maintenance mode has to be activated.

In order to stop the _arangod_ processes we will need to use a command like `kill -15`:

```
kill -15 <pid-of-arangod-process>
```

The _pid_ associated to your _cluster_ can be checked using a command like _ps_:

```
ps -C arangod -fww
```

The output of the command above does not only show the PID's of all _arangod_
processes but also the used commands, which can be useful for the following
restart of all _arangod_ processes.

The output below is from a test machine where three _Agents_, two _DB-Servers_
and two _Coordinators_ are running locally. In a more production-like scenario,
you will find only one instance of each one running:

```
ps -C arangod -fww
UID        PID  PPID  C STIME TTY          TIME CMD
max      29075  8072  0 13:50 pts/2    00:00:42 arangod --server.endpoint tcp://0.0.0.0:5001 --agency.my-address=tcp://127.0.0.1:5001 --server.authentication false --agency.activate true --agency.size 3 --agency.endpoint tcp://127.0.0.1:5001 --agency.supervision true --log.file a1 --javascript.app-path /tmp --database.directory agent1
max      29208  8072  2 13:51 pts/2    00:02:08 arangod --server.endpoint tcp://0.0.0.0:5002 --agency.my-address=tcp://127.0.0.1:5002 --server.authentication false --agency.activate true --agency.size 3 --agency.endpoint tcp://127.0.0.1:5001 --agency.supervision true --log.file a2 --javascript.app-path /tmp --database.directory agent2
max      29329 16224  0 13:51 pts/3    00:00:42 arangod --server.endpoint tcp://0.0.0.0:5003 --agency.my-address=tcp://127.0.0.1:5003 --server.authentication false --agency.activate true --agency.size 3 --agency.endpoint tcp://127.0.0.1:5001 --agency.supervision true --log.file a3 --javascript.app-path /tmp --database.directory agent3
max      29461 16224  1 13:53 pts/3    00:01:11 arangod --server.authentication=false --server.endpoint tcp://0.0.0.0:6001 --cluster.my-address tcp://127.0.0.1:6001 --cluster.my-role PRIMARY --cluster.agency-endpoint tcp://127.0.0.1:5001 --cluster.agency-endpoint tcp://127.0.0.1:5002 --cluster.agency-endpoint tcp://127.0.0.1:5003 --log.file db1 --javascript.app-path /tmp --database.directory dbserver1
max      29596  8072  0 13:54 pts/2    00:00:56 arangod --server.authentication=false --server.endpoint tcp://0.0.0.0:6002 --cluster.my-address tcp://127.0.0.1:6002 --cluster.my-role PRIMARY --cluster.agency-endpoint tcp://127.0.0.1:5001 --cluster.agency-endpoint tcp://127.0.0.1:5002 --cluster.agency-endpoint tcp://127.0.0.1:5003 --log.file db2 --javascript.app-path /tmp --database.directory dbserver2
max      29824 16224  1 13:55 pts/3    00:01:53 arangod --server.authentication=false --server.endpoint tcp://0.0.0.0:7001 --cluster.my-address tcp://127.0.0.1:7001 --cluster.my-role COORDINATOR --cluster.agency-endpoint tcp://127.0.0.1:5001 --cluster.agency-endpoint tcp://127.0.0.1:5002 --cluster.agency-endpoint tcp://127.0.0.1:5003 --log.file c1 --javascript.app-path /tmp --database.directory coordinator1
max      29938 16224  2 13:56 pts/3    00:02:13 arangod --server.authentication=false --server.endpoint tcp://0.0.0.0:7002 --cluster.my-address tcp://127.0.0.1:7002 --cluster.my-role COORDINATOR --cluster.agency-endpoint tcp://127.0.0.1:5001 --cluster.agency-endpoint tcp://127.0.0.1:5002 --cluster.agency-endpoint tcp://127.0.0.1:5003 --log.file c2 --javascript.app-path /tmp --database.directory coordinator2

```

### Upgrade a _cluster_ node

The following procedure is upgrading _Agent_, _DB-Server_ and _Coordinator_ on one node.

**Note:** The starting commands of _Agent_, _DB-Server_ and _Coordinator_ have to be reused.

#### Stop the _Agent_

```
kill -15 <pid-of-agent>
```

#### Upgrade the _Agent_

The _arangod_ process of the _Agent_ has to be upgraded using the same command that has
been used before with the additional option:

```
--database.auto-upgrade=true
```

The _Agent_ will stop automatically after the upgrade.

#### Restart the _Agent_

The _arangod_ process of the _Agent_ has to be restarted using the same command that has
been used before (without the additional option).

#### Stop the _DB-Server_

```
kill -15 <pid-of-dbserver>
```

#### Upgrade the _DB-Server_

The _arangod_ process of the _DB-Server_ has to be upgraded using the same command that has
been used before with the additional option:

```
--database.auto-upgrade=true
```

The _DB-Server_ will stop automatically after the upgrade.

#### Restart the _DB-Server_

The _arangod_ process of the _DB-Server_ has to be restarted using the same command that has
been used before (without the additional option).

#### Stop the _Coordinator_

```
kill -15 <pid-of-coordinator>
```

#### Upgrade the _Coordinator_

The _arangod_ process of the _Coordinator_ has to be upgraded using the same command that has
been used before with the additional option:

```
--database.auto-upgrade=true
```

The _Coordinator_ will stop automatically after the upgrade.

#### Restart the _Coordinator_

The _arangod_ process of the _Coordinator_ has to be restarted using the same command that has
been used before (without the additional option).

After repeating this process on every node all _Agents_, _DB-Servers_ and _Coordinators_ are upgraded and the manual upgrade
has successfully finished.

The _cluster_ supervision is reactivated by the API call:

`curl -u username:password <coordinator>/_admin/cluster/maintenance -XPUT -d'"off"'`


text:
using NUnit.Framework;
using billc.TreeNodes;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.calitha.goldparser;
using billc.Visitors;

namespace billc.Tests
{
    /// <summary>
    /// These tests are designed to test end to end
    /// They will use the parser, type checker, and interpreter to run full programs
    /// and verify they run correctly.
    /// </summary>
    [TestFixture]
    class IntegrationTests
    {
        InterpreterVisitor iv;
        TestErrorReporter errorReporter;
        TypeValidatorVisitor tvv;
        MyParser parser;
        string outputBuffer;
        string inputBuffer;

        [SetUp]
        public void Setup()
        {
            outputBuffer = "";
            inputBuffer = "";
            iv = new InterpreterVisitor();
            errorReporter = new TestErrorReporter();
            tvv = new TypeValidatorVisitor();
            iv.input = testInput;
            iv.println = testPrinter;
            var assembly = Assembly.GetExecutingAssembly();
            using (var stream = assembly.GetManifestResourceStream("billc.Bill_Grammar_v2.cgt"))
            {
                parser = new MyParser(stream);
            }
            parser.errorReporter = errorReporter;
            tvv.errorReporter = errorReporter;

            SymbolTable.functions.Clear();
            SymbolTable.classes.Clear();
        }

        private void testPrinter(string s)
        {
            outputBuffer += s;
        }

        private string testInput()
        {
            return inputBuffer;
        }

        [Test, Timeout(2000)]
        public void WhileLoopPrinting()
        {
            string src = "void main() { int a = 0; while(a < 5){ println(toStr(a));\n a = a + 1; }}";

            object parseResult = parser.Parse(src);
            Assert.NotNull(parseResult);
            Assert.False(parser.badParse);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.IsInstanceOf<ProgramNode>(parseResult);
            var prgrm = parseResult as ProgramNode;

            prgrm.accept(iv);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.AreEqual("01234", outputBuffer);
        }

        [Test, Timeout(2000)]
        public void ConditionalPrint([Values("true", "false")] string boolean)
        {
            const string falsePrint = "Was False";
            const string truePrint = "Was True";
            string src = "void main() { bool b = " + boolean + "; if (b) { println(\"" + truePrint + "\"); } else { println(\"" + falsePrint + "\"); }}";
            object parseResult = parser.Parse(src);
            Assert.NotNull(parseResult);
            Assert.False(parser.badParse);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.IsInstanceOf<ProgramNode>(parseResult);
            var prgrm = parseResult as ProgramNode;

            prgrm.accept(iv);
            Assert.IsEmpty(errorReporter.buffer);
            if (boolean == "true")
            {
                Assert.AreEqual(truePrint, outputBuffer);
            }
            else
            {
                Assert.AreEqual(falsePrint, outputBuffer);
            }
        }

        [Test, Timeout(2000)]
        public void StringLength([Values("", "hello", "what a long string")] string val)
        {
            string src = "void main() { int a = length(\"" + val + "\"); println(toStr(a)); }";
            object parseResult = parser.Parse(src);
            Assert.NotNull(parseResult);
            Assert.False(parser.badParse);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.IsInstanceOf<ProgramNode>(parseResult);
            var prgrm = parseResult as ProgramNode;

            prgrm.accept(iv);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.AreEqual(val.Length + "", outputBuffer);
        }

        [Test, Timeout(2000)]
        public void FunctionCallWithParams([Values(0, 5)] int val)
        {
            string src = "void main() { println(toStr(addTwo(" + val + "))); }\n int addTwo(int a){ return a + 2; }";
            object parseResult = parser.Parse(src);
            Assert.NotNull(parseResult);
            Assert.False(parser.badParse);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.IsInstanceOf<ProgramNode>(parseResult);
            var prgrm = parseResult as ProgramNode;

            prgrm.accept(tvv);
            prgrm.accept(iv);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.AreEqual((val + 2) + "", outputBuffer);
        }

        [Test]
        public void FunctionCallAsExpression()
        {
            string src = "void main() { addTwo(5); }\n int addTwo(int a){ return a + 2; }";
            object parseResult = parser.Parse(src);
            Assert.NotNull(parseResult);
            Assert.False(parser.badParse);
            Assert.IsEmpty(errorReporter.buffer);
            Assert.IsInstanceOf<ProgramNode>(parseResult);
            var prgrm = parseResult as ProgramNode;

            prgrm.accept(tvv);
            prgrm.accept(iv);
            Assert.IsNotEmpty(errorReporter.buffer);
        }
    }
}


text:
package com.meiste.greg.ptwgame.servlets;

import com.meiste.greg.ptwgame.entities.Player;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RankingServlet extends HttpServlet {

    @Override
    public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
            throws IOException {
        // TODO: Need to also add "submitted questions first" tie breaker
        int rank = 1;
        final List<Player> players = Player.getForRanking();
        for (final Player player : players) {
            final int newRank = rank++;
            if ((player.rank == null) || (newRank != player.rank)) {
                player.rank = newRank;
                Player.put(player, false);
            }
        }
    }
}


text:
package com.manyi.mall.cachebean.user;

public class UpdateAppRequest {
	private String url;
	private String message;
	private int version;
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public int getVersion() {
		return version;
	}
	public void setVersion(int version) {
		this.version = version;
	}

}


text:
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);

include dirname(__FILE__) . "/../../php/checkFileUpload.php";

	$tmp = explode('.', $_FILES['file']['name']);
	$ownerID = $tmp[0];
	$ext = $tmp[1];

	$safe_filename = $ownerID . 'F' . time() . '.' . $ext;

	$dir_base = dirname(__FILE__) . '/../../files/';        // dirname(__FILE__) is the directory containing the script. This way don't need to know root of webspace
	$isFile = is_uploaded_file($_FILES['file']['tmp_name']);
	if ($isFile) {
			$isMove = move_uploaded_file($_FILES['file']['tmp_name'],  $dir_base . $safe_filename);
	}

	// add malware prevention to images, google search

	// return a response

	$response = $safe_filename . '.' . $ext;
	http_response_code(200);					//See https://docs.angularjs.org/api/ng/service/$http#json-vulnerability-protection
	echo ")]}',\n" . json_encode($response);	// )]}', is used to stop JSON attacks, angular strips it off for you.
	return;

?>


text:
<!DOCTYPE html>

  <title>HELLO MESSAGE (2) | Cape.JS Demo</title>
  <link rel="stylesheet" type="text/css"
     href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

HELLO MESSAGE 2 Cape.JS Demo