text:
#include "../include/Inertia.h"
#include "../include/nifqhull.h"
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace Niflib;

static Inertia::fnCalcMassPropertiesSphere extCalcMassPropertiesSphereRoutine = NULL;
static Inertia::fnCalcMassPropertiesBox extCalcMassPropertiesBoxRoutine = NULL;
static Inertia::fnCalcMassPropertiesCylinder extCalcMassPropertiesCylinderRoutine = NULL;
static Inertia::fnCalcMassPropertiesCapsule extCalcMassPropertiesCapsuleRoutine = NULL;
static Inertia::fnCalcMassPropertiesPolyhedron extCalcMassPropertiesPolyhedronRoutine = NULL;
static Inertia::fnCombineMassProperties extCombineMassPropertiesRoutine = NULL;

void Inertia::SetCalcMassPropertiesSphere(Inertia::fnCalcMassPropertiesSphere extRoutine)
{
	extCalcMassPropertiesSphereRoutine = extRoutine;
}

void Inertia::SetCalcMassPropertiesBox(Inertia::fnCalcMassPropertiesBox extRoutine)
{
	extCalcMassPropertiesBoxRoutine = extRoutine;
}

void Inertia::SetCalcMassPropertiesCylinder(Inertia::fnCalcMassPropertiesCylinder extRoutine)
{
	extCalcMassPropertiesCylinderRoutine = extRoutine;
}

void Inertia::SetCalcMassPropertiesCapsule(Inertia::fnCalcMassPropertiesCapsule extRoutine)
{
	extCalcMassPropertiesCapsuleRoutine = extRoutine;
}

void Inertia::SetCalcMassPropertiesPolyhedron(Inertia::fnCalcMassPropertiesPolyhedron extRoutine)
{
	extCalcMassPropertiesPolyhedronRoutine = extRoutine;
}

/*! Define external mass property combination routine */
void Inertia::SetCombineMassProperties(Inertia::fnCombineMassProperties extRoutine)
{
	extCombineMassPropertiesRoutine = extRoutine;
}

void Inertia::CalcMassPropertiesSphere(float radius,
	float density, bool solid,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCalcMassPropertiesSphereRoutine)
	{
		extCalcMassPropertiesSphereRoutine(radius, density, solid, mass, volume, center, inertia);
		return;
	}
	float inertiaScalar;
	if(solid)
	{
		mass = density * (4.0f * float(M_PI) * pow(radius, 3.0f)) / 3.0f;
		inertiaScalar = (2.0f * mass * pow(radius, 2.0f)) / 5.0f;
	}
	else
	{
		mass = density * 4.0f * float(M_PI) * pow(radius, 2.0f);
		inertiaScalar = (2.0f * mass * pow(radius, 2.0f)) / 3.0f;
	}
	center = Vector3();
	inertia = InertiaMatrix::IDENTITY;
	inertia[0][0] = inertia[1][1] = inertia[2][2] = inertiaScalar;
}

void Inertia::CalcMassPropertiesBox(Vector3 size,
	float density, bool solid,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCalcMassPropertiesBoxRoutine)
	{
		extCalcMassPropertiesBoxRoutine(size, density, solid, mass, volume, center, inertia);
		return;
	}

	Vector3 tmp;
	if(solid)
	{
		mass = density * (size[0] * size[1] * size[2]);
		tmp[0] = mass * pow(size[0], 2.0f) / 12.0f;
		tmp[1] = mass * pow(size[1], 2.0f) / 12.0f;
		tmp[2] = mass * pow(size[2], 2.0f) / 12.0f;
	}
	else
	{
		mass = density * ((size[0] * size[1] * 2.0f) + (size[0] * size[2] * 2.0f) + (size[1] * size[2] * 2.0f));
		tmp[0] = mass * pow(size[0], 2.0f) / 6.0f;
		tmp[1] = mass * pow(size[1], 2.0f) / 6.0f;
		tmp[2] = mass * pow(size[2], 2.0f) / 6.0f;
		//TODO: just guessing here, calculate it
	}
	inertia = InertiaMatrix::IDENTITY;
	inertia[0][0] = tmp[1] + tmp[2];
	inertia[1][1] = tmp[2] + tmp[0];
	inertia[2][2] = tmp[0] + tmp[1];
	center = Vector3();
}

void Inertia::CalcMassPropertiesCylinder(Vector3 startAxis, Vector3 endAxis, float radius,
	float density, bool solid,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCalcMassPropertiesCylinderRoutine)
	{
		extCalcMassPropertiesCylinderRoutine(startAxis, endAxis, radius, density, solid, mass, volume, center, inertia);
		return;
	}
	float height = (startAxis - endAxis).Magnitude();
	center = (startAxis + endAxis) / 2.0f;

	inertia = InertiaMatrix::IDENTITY;
	if(solid)
	{
		mass = density * height * float(M_PI) * pow(radius, 2.0f);
		inertia[0][0] =
			inertia[1][1] = mass * (3.0f * pow(radius, 3.0f) + pow(height, 2.0f)) / 12.0f;
		inertia[2][2] = mass * (pow(radius, 2.0f)) / 2.0f;
	}
	else
	{
		mass = density * height * float(M_PI) * pow(radius, 2.0f);
		inertia[0][0] =
			inertia[1][1] = mass * (6.0f * pow(radius, 3.0f) + pow(height, 2.0f)) / 12.0f;
		inertia[2][2] = mass * (pow(radius, 2.0f));
	}
}

void Inertia::CalcMassPropertiesCapsule(Vector3 startAxis, Vector3 endAxis, float radius,
	float density, bool solid,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCalcMassPropertiesCapsuleRoutine)
	{
		extCalcMassPropertiesCapsuleRoutine(startAxis, endAxis, radius, density, solid, mass, volume, center, inertia);
		return;
	}

	float height = (startAxis - endAxis).Magnitude();
	center = (startAxis + endAxis) / 2.0f;

	// cylinder + caps, and caps have volume of a sphere
	inertia = InertiaMatrix::IDENTITY;
	if(solid)
	{
		mass = density * (height * float(M_PI) * pow(radius, 2.0f) + (4.0f * float(M_PI) * pow(radius, 3.0f)) / 3.0f);
		inertia[0][0] = mass * (3.0f * pow(radius, 3.0f) + pow(height, 2.0f)) / 12.0f;
		inertia[1][1] = inertia[0][0];
		inertia[2][2] = mass * (pow(radius, 2.0f)) / 2.0f;
	}
	else
	{
		mass = density * (height * 2.0f * float(M_PI) * radius + 2.0f * float(M_PI) * pow(radius, 2.0f));
		inertia[0][0] = mass * (6.0f * pow(radius, 2.0f) + pow(height, 2.0f)) / 12.0f;
		inertia[1][1] = inertia[0][0];
		inertia[2][2] = mass * pow(radius, 2.0f);
	}
}

//
// References
// ----------
//
// Jonathan Blow, Atman J Binstock
// "How to find the inertia tensor (or other mass properties) of a 3D solid body represented by a triangle mesh"
// http://number-none.com/blow/inertia/bb_inertia.doc
//
// David Eberly
// "Polyhedral Mass Properties (Revisited)"
// http://www.geometrictools.com//LibPhysics/RigidBody/Wm4PolyhedralMassProperties.pdf
//
// The function is an implementation of the Blow and Binstock algorithm,
// extended for the case where the polygon is a surface (set parameter
// solid = False).
void Inertia::CalcMassPropertiesPolyhedron(const vector<Vector3>& vertices,
	const vector<Triangle>& triangles,
	float density, bool solid,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCalcMassPropertiesPolyhedronRoutine)
	{
		extCalcMassPropertiesPolyhedronRoutine(
			int(vertices.size()), &vertices[0],
			int(triangles.size()), triangles.empty() ? NULL : &triangles[0],
			density, solid, mass, volume, center, inertia);
		return;
	}

	vector<Triangle>::const_iterator triBegin, triEnd;
	vector<Triangle> tris;
	if(triangles.size() == 0)
	{
		tris = NifQHull::compute_convex_hull(vertices);
		triBegin = tris.begin();
		triEnd = tris.end();
	}
	else
	{
		triBegin = triangles.begin();
		triEnd = triangles.end();
	}

	// 120 times the covariance matrix of the canonical tetrahedron
	// (0,0,0),(1,0,0),(0,1,0),(0,0,1)
	// integrate(integrate(integrate(z*z, x=0..1-y-z), y=0..1-z), z=0..1) = 1/120
	// integrate(integrate(integrate(y*z, x=0..1-y-z), y=0..1-z), z=0..1) = 1/60
	Matrix33 covariance_canonical(2.0f, 1.0f, 1.0f,
		1.0f, 2.0f, 1.0f,
		1.0f, 1.0f, 2.0f);
	vector<Matrix44> covariances;
	vector<float> masses;
	vector<Vector3> centers;

	// for each triangle
	// construct a tetrahedron from triangle + (0,0,0)
	// find its matrix, mass, and center (for density = 1, will be corrected at
	// the end of the algorithm)
	for(vector<Triangle>::const_iterator itr = triBegin, end = triEnd; itr != end; ++itr)
	{
		// Calc vertices
		const Vector3& vert0 = vertices[(*itr)[0]];
		const Vector3& vert1 = vertices[(*itr)[1]];
		const Vector3& vert2 = vertices[(*itr)[2]];

		// construct a transform matrix that converts the canonical tetrahedron
		// into (0,0,0),vert0,vert1,vert2
		Matrix44 transform_transposed(Matrix33(
			vert0[0], vert0[1], vert0[2],
			vert1[0], vert1[1], vert1[2],
			vert2[0], vert2[1], vert2[2]));
		Matrix44 transform = transform_transposed.Transpose();

		// find the covariance matrix of the transformed tetrahedron/triangle
		if(solid)
		{
			// we shall be needing the determinant more than once, so
			// precalculate it
			float determinant = transform.Determinant();

			// C' = det(A) * A * C * A^T
			covariances.push_back(transform * covariance_canonical * transform_transposed * determinant);
			// m = det(A) / 6.0
			masses.push_back(determinant / 6.0f);
			// find center of gravity of the tetrahedron
			centers.push_back(
				Vector3(0.25f * (vert0[0] + vert1[0] + vert2[0]),
				0.25f * (vert0[1] + vert1[1] + vert2[1]),
				0.25f * (vert0[2] + vert1[2] + vert2[2]))
				);
		}
		else
		{
			// find center of gravity of the triangle
			Vector3 com((vert0[0] + vert1[0] + vert2[0]) / 3.0f,
				(vert0[1] + vert1[1] + vert2[1]) / 3.0f,
				(vert0[2] + vert1[2] + vert2[2]) / 3.0f);
			centers.push_back(com);

			// find mass of triangle
			// mass is surface, which is half the norm of cross product
			// of two edges
			float calc_mass = ((vert1 - vert0) ^ (vert2 - vert0)).Magnitude() / 2.0f;
			masses.push_back(calc_mass);

			// find covariance at center of this triangle
			// (this is approximate only as it replaces triangle with point mass
			// TODO: find better way)
			Matrix33 calc_c(com[0] * com[0], com[0] * com[1], com[0] * com[2],
				com[1] * com[0], com[1] * com[1], com[1] * com[2],
				com[2] * com[0], com[2] * com[1], com[2] * com[2]);
			covariances.push_back(Matrix44(calc_c));
		}
	}
	// accumulate the results
	mass = std::accumulate(masses.begin(), masses.end(), 0.0f);
	if(mass < 0.0001f)
	{
		// dimension is probably badly chosen
		//raise ZeroDivisionError("mass is zero (consider calculating inertia with a lower dimension)")
		//printf("WARNING: mass is zero");
		mass = 0.0f, volume = 0.0f;
		center = Vector3();
		inertia = InertiaMatrix::IDENTITY;
		return;
	}

	// weighed average of centers with masses
	center = Vector3();
	for(size_t i = 0; i < masses.size(); ++i)
		center += (centers[i] * (masses[i] / mass));

	// add covariances, and correct the values
	Matrix44 total_covariance;
	if(solid)
	{
		for(size_t i = 0; i < covariances.size(); ++i)
			total_covariance *= covariances[i];
	}

	// translate covariance to center of gravity:
	// C' = C - m * ( x dx^T + dx x^T + dx dx^T )
	// with x the translation vector and dx the center of gravity

	Matrix44 translate_correction(
		Matrix33(center[0] * center[0], center[0] * center[1], center[0] * center[2],
		center[1] * center[0], center[1] * center[1], center[1] * center[2],
		center[2] * center[0], center[2] * center[1], center[2] * center[2]
		)
		);
	translate_correction *= mass;

	total_covariance = total_covariance - translate_correction;

	// convert covariance matrix into inertia tensor
	float trace = total_covariance[0][0] + total_covariance[1][1] + total_covariance[2][2];
	Matrix44 trace_matrix;
	trace_matrix[0][0] = trace_matrix[1][1] = trace_matrix[2][2] = trace;

	// correct for given density
	inertia = InertiaMatrix((trace_matrix - total_covariance).GetRotation()) * density;
	mass *= density;
}

void Inertia::CombineMassProperties(
	vector<float> masses,
	vector<float> volumes,
	vector<Vector3> centers,
	vector<InertiaMatrix> inertias,
	vector<Matrix44> transforms,
	float& mass, float& volume, Vector3& center, InertiaMatrix &inertia)
{
	if(extCombineMassPropertiesRoutine)
	{
		extCombineMassPropertiesRoutine(
			int(masses.size()),
			&masses[0], &volumes[0], &centers[0], &inertias[0], &transforms[0],
			mass, volume, center, inertia);
		return;
	}

	for(size_t i = 0; i < masses.size(); ++i)
	{
		mass += masses[i];
	}
	// TODO: doubt this inertia calculation is even remotely close
	for(size_t i = 0; i < masses.size(); ++i)
	{
		center += centers[i] * (masses[i] / mass);
		inertia *= inertias[i];
	}
}


text:
package uk.gov.nationalarchives.droid.core.interfaces.archive;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

import org.jwat.arc.ArcReader;
import org.jwat.arc.ArcReaderFactory;
import org.jwat.arc.ArcRecord;
import org.jwat.arc.ArcRecordBase;

import uk.gov.nationalarchives.droid.core.interfaces.ResourceId;
import uk.gov.nationalarchives.droid.core.interfaces.RequestIdentifier;
import uk.gov.nationalarchives.droid.core.interfaces.IdentificationRequest;
import uk.gov.nationalarchives.droid.core.interfaces.resource.RequestMetaData;

/**
 * @author rflitcroft
 * @author gseaman
 *
 */
public class ArcArchiveHandler extends WebArchiveHandler implements ArchiveHandler {
    /**
     * Used to generate URIs within Arc file
     */
    protected static final String WEB_ARCHIVE_TYPE = "arc";

    /**
     * {@inheritDoc}
     */
    @Override
    public final void handle(IdentificationRequest request) throws IOException {

        final InputStream arcIn = request.getSourceInputStream();
        try {

            Iterable<ArcRecordBase> iterable = new Iterable<ArcRecordBase>() {
                @Override
                public final Iterator<ArcRecordBase> iterator() {
                    return new ArcArchiveEntryIterator(arcIn);
                }
            };

            ArcArchiveWalker walker = new ArcArchiveWalker(request.getIdentifier(), arcIn);
            walker.walk(iterable);
        } finally {
            if (arcIn != null) {
                arcIn.close();
            }
        }
    }

    /**
     * Adapts the JWAT ByteCountingPushbackInputStream to generate arc entries.
     * @author gseaman
     *
     */
    private static final class ArcArchiveEntryIterator
            extends ArchiveInputStreamIterator<ArcRecordBase, InputStream> {

        private Iterator<ArcRecordBase> iterator;

        ArcArchiveEntryIterator(InputStream in) {
            super(in); // dummy call - we override most of supers methods
            try {
                ArcReader arcReader = ArcReaderFactory.getReader(in);
                this.iterator = arcReader.iterator();
            } catch (IOException e) {
                // TODO log
                System.err.println(e);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected ArcRecordBase getNextEntry(InputStream in) throws IOException {
            ArcRecordBase base = null;
            //get the next real ARC record (not header) and return it as an ArcRecord
            if (this.iterator.hasNext()) {
                base = this.iterator.next();
                // skip the header record at the start, any dns requests, and non 200 responses
                while (!(base instanceof ArcRecord) || "dns".equals(base.getScheme())
                    || base.getHttpHeader().statusCode != HTTP_ACCEPTED) {
                    if (this.iterator.hasNext()) {
                        base = this.iterator.next();
                    } else {
                        base = null;
                    }
                }
            }
            return base;
        }

    }

    /**
     * Submits a request to droid.
     * @param entry the arc entry to submit
     * @param entryName the name of the entry
     * @param parentName the name of the parent file
     * @param in the archive input stream
     * @param correlationId the correlation Id for the request
     * @param originatorNodeId the Id of the originator node
     * @throws IOException if the input stream could not be read
     */
    final void submit(ArcRecordBase entry, String entryName, URI parentName,
                      InputStream in, ResourceId correlationId, long originatorNodeId) throws IOException {
        long size = entry.getArchiveLength();
        Date time = entry.getArchiveDate();

        RequestMetaData metaData = new RequestMetaData(
                size == -1 ? null : size,
                time == null ? null : time.getTime(),
                entryName);

        super.submit(WEB_ARCHIVE_TYPE, metaData, parentName,
                entry.getPayloadContent(), correlationId, originatorNodeId);
    }

    /**
     * Archive walker for ARC archives.
     * modelled on walker for TAR archives
     * @author rflitcroft
     * @author gseaman
     */
    private final class ArcArchiveWalker extends ArchiveFileWalker<ArcRecordBase> {

        private final ResourceId parentId;
        private final long originatorNodeId;
        private final URI parentName;
        private final InputStream in;
        private final Map<String, ResourceId> directories = new HashMap<String, ResourceId>();

        ArcArchiveWalker(RequestIdentifier parent, InputStream in) {
            this.in = in;
            this.parentId = parent.getResourceId();
            this.parentName = parent.getUri();
            this.originatorNodeId = parent.getAncestorId();
        }

        @Override
        protected void handleEntry(ArcRecordBase entry) throws IOException {
            final int maxLEN = 4095;

            //String entryUri = entry.getUrl().toString();
            String entryUri = entry.getUrlStr();
            String entryPath = new URL(entryUri).getFile();
            // remove querystring to get prefix (may include slashes)
            final int queryPos = entryPath.indexOf('?');
            String querylessPath = queryPos > 0 ? entryPath.substring(0, queryPos) : entryPath;
            String entryName = entryPath.substring(querylessPath.lastIndexOf('/') + 1);
            String prefixPath = entryUri.substring(0, entryUri.length() - entryName.length());
            ResourceId correlationId = parentId; // by default, files are correlated to the parent.
            String requestUri = entry.getHttpHeader().requestUri;

            // If there is a path, get the actual correlation id for its parent folder:
            if (!prefixPath.isEmpty()) {
                correlationId = directories.get(prefixPath);
                // If we haven't seen the path before, add the ancestor folders not yet seen:
                if (correlationId == null) {
                    correlationId = processAncestorFolders(WEB_ARCHIVE_TYPE, prefixPath,
                        requestUri, parentId, parentName, directories);
                }
            }
            // if the file name (including querystring) is > 4096 chars, truncate it for the DB
            String truncatedName = entryName.length() < maxLEN ? entryName : entryName.substring(0, maxLEN);

            submit(entry, truncatedName, parentName, in, correlationId, originatorNodeId);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
Enclose SwiftyJSON which implement:

- **JSON->Model** : Transform JsonString or Dictionary/Array etc to Model, for more information [SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)

- **Model->JSON** : Transform Model which impements protocol **JSONConvertibleMappable**

[**中文文档**](http://www.jianshu.com/p/5a564585e0ea)

## Installation

You can use cocoapod utility to import it to your Project

```
pod 'SwiftyJSONMappable'
```

**Or** : Use it with [Moya](https://github.com/Moya/Moya)

```
pod 'SwiftyJSONMappable/Moya'
```

**Or** : Use it with [RxSwift](https://github.com/ReactiveX/RxSwift)

```
pod 'SwiftyJSONMappable/RxSwift'
```

## Usage

### Model define

```
class HttpBin: JSONMappable {
    var args: [String: Any]
    var headers: HttpBinHeaders
    var origin: String
    var url: String

    required init(json: JSON) {
        args = json["args"].dictionaryValue
        headers = HttpBinHeaders(json: json["headers"])
        origin = json["origin"].stringValue
        url = json["url"].stringValue
    }
}
```

### Transform to JSON/JSONString

```
let httpBin = ...

let JSON = httpBin.mapJSON()    // transform to SwiftyJSON
let JSONString = httpBin.mapString()   // transform to json String
```

You will get Result like this:

```
{
  "headers" : {
    "acceptEncoding" : "gzip;q=1.0, compress;q=0.5",
    "acceptLanguage" : "en;q=1.0",
    "connection" : "close",
    "accept" : "*\/*",
    "host" : "httpbin.org"
  },
  "origin" : "118.113.69.83",
  "args" : {

  },
  "url" : "https:\/\/httpbin.org\/get"
}
```

### Ignore and Replace Property when transfrom to JSON/JSONString

```
class HttpBin: JSONMappable {
    var args: [String: Any]
    var headers: HttpBinHeaders
    var origin: String
    var url: String

    required init(json: JSON) {
        args = json["args"].dictionaryValue
        headers = HttpBinHeaders(json: json["headers"])
        origin = json["origin"].stringValue
        url = json["url"].stringValue
    }
}

public var ignoreProperties: [String]? {
	return ["args"]
}

public var replacedProperties: [String : String]? {
	return ["origin": "newOrigin"]
}
```

You will get Result like this:

```
{
  "newOrigin" : "118.113.69.83",
  "url" : "https:\/\/httpbin.org\/get",
  "headers" : {
    "acceptEncoding" : "gzip;q=1.0, compress;q=0.5",
    "acceptLanguage" : "en;q=1.0",
    "connection" : "close",
    "accept" : "*\/*",
    "host" : "httpbin.org"
  }
}
```

### Use with Moya

```
MoyaProvider<APIService>().request(.testGet) { (result) in
	switch result {
	case let .success(response):
		do {
            let httpBin = try response.mapJSONMappable(HttpBin.self)
            print(httpBin.mapString() ?? "")
         } catch {
            print(error)
        }
    case let .failure(error):
    	print(error)
    }
}
```

### Use with RxSwift

```
RxMoyaProvider<APIService>().request(.testGet)
     .mapJSONMappable(HttpBin.self)
     .observeOn(SerialDispatchQueueScheduler(internalSerialQueueName: "test"))
     .subscribe { (event) in
          switch event {
          case let .next(httpBin):
               print(httpBin.mapString() ?? "请求完毕")
          case let .error(error):
               print(error)
          default:
               print(event)
          }
     }.addDisposableTo(disposeBag)

```

## Author

ApterKing, wangccong@foxmail.com

## License

SwiftyJSONMappable is available under the MIT license. See the LICENSE file for more info.


text:
Improved Fortran syntax highlighting for Vim.

# Installation

### OS X
A setup script `setup.sh` is provided for adding vim.fortran to .vim folder. To do so run `setup.sh` from this repository's directory. `setup.sh` assumes the users vim directory is located in `~/.vim`.


text:
{% extends "frog/gallery.html" %}
<script>
    {% block script %}
    window.addEvent('domready', function() {
        var viewer = new Frog.Viewer();
        viewer.addEvent('hide', function() {
            location.href = '/frog/gallery/1';
        });
        var img = JSON.parse('{{object.serialize|safe}}');
        viewer.show();
        viewer.setImages([img]);
    });
    {% endblock %}
</script>


text:
function debug {

TAG=iogov
logger -p local1.notice -t $TAG "$@"

}

function subtract()
{

  SET1=( $1 )
  SET2=( $2 )
  OLDIFS="$IFS"
  IFS=$'\n'
  SET3=( $(grep -Fxv "${SET1[*]}" <<< "${SET2[*]}") )
  IFS="$OLDIFS"
  echo "${SET3[*]}"
  # SET3 = SET2-SET1

}

# mounting - Not necessary on RHEL

# Ubuntu does this by default once the cgroups packages are installed
# if [ ! -e /sys/fs/cgroup ]; then
#  mount -t cgroup none /sys/fs/cgroup
#fi

# this one is not done by default
#if [ ! -e /sys/fs/cgroup/blkio ]; then
#  mkdir /sys/fs/cgroup/blkio
#  mount -t cgroup -o blkio none /sys/fs/cgroup/blkio
#fi

# add all the users to the proper group where we assume all UID compliant users should be in group
gpasswd -M $(awk -F: '{ if ($3 > 2999) print $1 }' /etc/passwd | sort | tr '\n' ',') faculty

SYSCPU=4096
MAXLOGGEDUSERS=4
USERBLKIO=500
# TODO: what is the best value to ensure emergency responsivness?
SYSBLKIO=500

TMPLIST=$( awk -F: '{ if ($3 > 2999) print $1 }' /etc/passwd | sort | tr '\n' ' ' )
TMP=$( find /cgroup/blkio/* -type d )
for u in $TMP; do
  DONELIST="$DONELIST $( basename $u )";
done

# users whose cgroups need to be created
USERLIST=$( subtract "$DONELIST" "$TMPLIST" )
# garbage collection - users that don't exist must have their cgroups deleted
DELLIST=$( subtract  "$TMPLIST others system" "$DONELIST" )

for i in $DELLIST; do
  cgdelete  cpu:/$i
  cgdelete  blkio:/$i
done

for i in $USERLIST; do
  cgcreate -g cpu:/$i
  cgcreate -g blkio:/$i
  cgset -r blkio.weight=$USERBLKIO /$i
done

# other users that have processes running
if [ ! -e /sys/fs/cgroup/cpu/others ]; then
  cgcreate -g cpu:/others
  cgcreate -g blkio:/others
  cgset -r blkio.weight=$USERBLKIO /others
fi

# for anything that runs as root and something else that cgrules.conf puts in thys group
if [ ! -e /sys/fs/cgroup/cpu/system ]; then
  cgcreate -g cpu:/system
  cgcreate -g blkio:/system
  # reserved for root ssh actions - default shares value is 1024
  cgset -r cpu.shares=$SYSCPU /system
  # default value is 500, max value is 1000
  cgset -r  blkio.weight=$SYSBLKIO /system
fi


text:
/*	$OpenBSD: agp_machdep.c,v 1.1 2002/07/12 20:17:03 mickey Exp $	*/

/*
 * Copyright (c) 2002 Michael Shalayeff
 * All rights reserved.
 *
 * 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 THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES 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 MIND, 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.
 */

#include <sys/param.h>
#include <sys/device.h>

#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcidevs.h>
#include <dev/pci/agpvar.h>

#include <machine/cpufunc.h>

const struct agp_product agp_products[] = {
	{ PCI_VENDOR_ALI, -1, agp_ali_attach },
	{ PCI_VENDOR_AMD, -1, agp_amd_attach },
	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_82810_GC, agp_i810_attach },
	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_82810_DC100_GC, agp_i810_attach },
	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_82810E_GC, agp_i810_attach },
	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_82815_FULL_GRAPH, agp_i810_attach },
/*	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_82830MP_IV, agp_i810_attach }, */
	{ PCI_VENDOR_INTEL, -1, agp_intel_attach },
	{ PCI_VENDOR_SIS, -1, agp_sis_attach },
	{ PCI_VENDOR_VIATECH, -1, agp_via_attach },
	{ 0, 0, NULL }
};

void
agp_flush_cache(void)
{
	wbinvd();
}


text:
<?php _e( 'Footer', 'satus' ); ?>

          <?php bloginfo('name'); ?>

            Street Address

            City,
            State
            Zip Code

            Country

          Phone: 1-555-555-5555

          Fax: 1-555-555-5555

          <a href="<?php echo home_url('/'); ?>" property="url" rel="bookmark">website.com

          you@yourdomain.com

© <?php echo date('Y');?> <?php bloginfo('name'); ?>

design by Your Design Company

<?php if (GOOGLE_ANALYTICS_ID) : ?>

<?php endif; ?>

<?php wp_footer(); ?>


text:
/*
 * vfprintf - formatted output without ellipsis
 */
/* $Id$ */

#include	<stdio.h>
#include	<stdarg.h>
#include	"loc_incl.h"

int
vfprintf(FILE *stream, const char *format, va_list arg)
{
	return _doprnt (format, arg, stream);
}


text:
package specific.sysml.parser

import de.dfki.cps.specific.ocl.parser.OclTokens

import scala.collection.SortedSet
import scala.util.parsing.combinator.token.Tokens
import scala.util.parsing.input.Positional

/**
  * Created by martin on 18.04.16.
  */
object SysMLTokens {
  type Token = OclTokens.Token
  type Delimiter = OclTokens.Delimiter

  case class SysmlComment(chars: String) extends Token with Positional

  sealed trait Indentation extends Token { val n: Int; val chars = "" }

  object Indentation {
    case object None extends Indentation { val n = 0 }
    case class Tabs(n: Int) extends Indentation {
      override def toString = s"$n tabs"
    }
    case class Spaces(n: Int) extends Indentation {
      override def toString = s"$n spaces"
    }
  }

  sealed trait IndentationToken extends Token { val chars = "" }
  case object SEPARATOR extends IndentationToken {
    override def toString = "end of line"
  }
  case object INDENT extends IndentationToken {
    override def toString = "start of indented block"
  }
  case object DEDENT extends IndentationToken {
    override def toString = "end of indented block"
  }
  case class UNMATCHED_DEDENT(indentation: Indentation) extends IndentationToken {
    override def toString = s"unmatched dedentation (no previous line was indented with $indentation)"
  }
  case class INCONSISTENT_INDENTATION(before: Indentation, now: Indentation) extends IndentationToken {
    override def toString = s"inconsistent indentation (started with $before and continued with $now)"
  }
  case class MIXED_INDENTATION(start: Indentation) extends IndentationToken {
    override def toString = start match {
      case Indentation.Spaces(n) => s"mixed indentation characters in one line (tab afer $n spaces)"
      case Indentation.Tabs(n) => s"mixed indentation characters in one line (space afer $n tabs)"
      case Indentation.None => sys.error("invalid indentation state")
    }
  }

  val delimiters = OclTokens.delimiters ++ SortedSet[Delimiter](
    ELIPSIS, HASH, LEFT_ARROW, TILDE
  ) (Ordering.by[Delimiter,(Int,String)](k => (k.chars.length, k.chars)).reverse)

  case object ELIPSIS extends Delimiter("..")
  case object HASH extends Delimiter("#")
  case object LEFT_ARROW extends Delimiter("<-")
  case object TILDE extends Delimiter("~")
}


text:
<?php
namespace DTS\eBaySDK\OAuth\Types;

use DTS\eBaySDK\StatusCodeTrait;
use DTS\eBaySDK\HttpHeadersTrait;

/**
 *
 * @property string $access_token
 * @property string $token_type
 * @property integer $expires_in
 * @property string $refresh_token
 * @property string $error
 * @property string $error_description
 * @property string $error_uri
 */
class RefreshUserTokenRestResponse  extends \DTS\eBaySDK\Types\BaseType
{
    use StatusCodeTrait;
    use HttpHeadersTrait;

    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'access_token' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'access_token'
        ],
        'token_type' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'token_type'
        ],
        'expires_in' => [
            'type' => 'integer',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'expires_in'
        ],
        'refresh_token' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'refresh_token'
        ],
        'error' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'error'
        ],
        'error_description' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'error_description'
        ],
        'error_uri' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'error_uri'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     * @param int $statusCode Status code
     * @param array $headers HTTP Response headers.
     */
    public function __construct(array $values = [], $statusCode = 200, array $headers = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        $this->setValues(__CLASS__, $childValues);

        $this->statusCode = (int)$statusCode;

        $this->setHeaders($headers);
    }
}


text:
package petablox.analyses.alias;

import java.util.Iterator;
import java.util.Set;

import soot.SootMethod;
import soot.Unit;
import soot.toolkits.graph.Block;
import petablox.analyses.method.DomM;
import petablox.bddbddb.Rel.RelView;
import petablox.project.analyses.ProgramRel;
import petablox.util.ArraySet;
import petablox.util.SetUtils;
import petablox.util.graph.AbstractGraph;
import petablox.util.soot.ICFG;
import petablox.util.soot.SootUtilities;
import petablox.util.tuple.object.Pair;

/**
 * Implementation of a context-sensitive call graph.
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
public class CSCG extends AbstractGraph<Pair<Ctxt, SootMethod>> implements ICSCG {
    protected DomM domM;
    protected ProgramRel relRootCM;
    protected ProgramRel relReachableCM;
    protected ProgramRel relCICM;
    protected ProgramRel relCMCM;
    public CSCG(DomM domM, ProgramRel relRootCM, ProgramRel relReachableCM,
            ProgramRel relCICM, ProgramRel relCMCM) {
        this.domM = domM;
        this.relRootCM = relRootCM;
        this.relReachableCM = relReachableCM;
        this.relCICM = relCICM;
        this.relCMCM = relCMCM;
    }
    public Set<Pair<Ctxt, SootMethod>> getNodes() {
        if (!relReachableCM.isOpen())
            relReachableCM.load();
        Iterable<Pair<Ctxt, SootMethod>> res = relReachableCM.getAry2ValTuples();
        return SetUtils.iterableToSet(res, relReachableCM.size());
    }
    public Set<Pair<Ctxt, SootMethod>> getRoots() {
        if (!relRootCM.isOpen())
            relRootCM.load();
        Iterable<Pair<Ctxt, SootMethod>> res = relRootCM.getAry2ValTuples();
        return SetUtils.iterableToSet(res, relRootCM.size());
    }
    public Set<Pair<Ctxt, SootMethod>> getPreds(Pair<Ctxt, SootMethod> cm) {
        if (!relCMCM.isOpen())
            relCMCM.load();
        RelView view = relCMCM.getView();
        view.selectAndDelete(2, cm.val0);
        view.selectAndDelete(3, cm.val1);
        Iterable<Pair<Ctxt, SootMethod>> res = view.getAry2ValTuples();
        return SetUtils.iterableToSet(res, view.size());
    }
    public Set<Pair<Ctxt, SootMethod>> getSuccs(Pair<Ctxt, SootMethod> cm) {
        if (!relCMCM.isOpen())
            relCMCM.load();
        RelView view = relCMCM.getView();
        view.selectAndDelete(0, cm.val0);
        view.selectAndDelete(1, cm.val1);
        Iterable<Pair<Ctxt, SootMethod>> res = view.getAry2ValTuples();
        return SetUtils.iterableToSet(res, view.size());
    }
    public boolean hasNode(Pair<Ctxt, SootMethod> node) {
        if (!relReachableCM.isOpen())
            relReachableCM.load();
        return relReachableCM.contains(node.val0, node.val1);
    }
    public boolean hasRoot(Pair<Ctxt, SootMethod> node) {
        if (!relRootCM.isOpen())
            relRootCM.load();
        if (relRootCM.contains(node.val0, node.val1))
            return true;
        return false;
    }
    public int numSuccs(Pair<Ctxt, SootMethod> node) {
        if (!relCMCM.isOpen())
            relCMCM.load();
        RelView view = relCMCM.getView();
        view.selectAndDelete(0, node.val0);
        view.selectAndDelete(1, node.val1);
        return view.size();
    }
    public Set<Ctxt> getContexts(SootMethod SootMethod) {
        if (!relReachableCM.isOpen())
            relReachableCM.load();
        RelView view = relReachableCM.getView();
        view.selectAndDelete(1, SootMethod);
        Iterable<Ctxt> res = view.getAry1ValTuples();
        Set<Ctxt> ctxts = SetUtils.newSet(view.size());
        for (Ctxt ctxt : res)
            ctxts.add(ctxt);
        return ctxts;
    }
    public Set<Pair<Ctxt, Unit>> getCallers(Ctxt ctxt, SootMethod meth) {
        if (!relCICM.isOpen())
            relCICM.load();
        RelView view = relCICM.getView();
        view.selectAndDelete(2, ctxt);
        view.selectAndDelete(3, meth);
        Iterable<Pair<Ctxt, Unit>> res = view.getAry2ValTuples();
        Set<Pair<Ctxt, Unit>> CIs = SetUtils.newSet(view.size());
        for (Pair<Ctxt, Unit> ci : res)
            CIs.add(ci);
        return CIs;
    }
    public Set<Pair<Ctxt, SootMethod>> getTargets(Ctxt ctxt, Unit invk) {
        if (!relCICM.isOpen())
            relCICM.load();
        RelView view = relCICM.getView();
        view.selectAndDelete(0, ctxt);
        view.selectAndDelete(1, invk);
        Iterable<Pair<Ctxt, SootMethod>> res = view.getAry2ValTuples();
        Set<Pair<Ctxt, SootMethod>> CMs = SetUtils.newSet(view.size());
        for (Pair<Ctxt, SootMethod> cm : res)
            CMs.add(cm);
        return CMs;
    }
    public Set<Unit> getLabels(Pair<Ctxt, SootMethod> origNode, Pair<Ctxt, SootMethod> destNode) {
        SootMethod meth1 = origNode.val1;
        Set<Unit> invks = new ArraySet<Unit>();
        ICFG cfg = SootUtilities.getCFG(meth1);
        Ctxt ctxt1 = origNode.val0;
        SootMethod meth2 = destNode.val1;
        Ctxt ctxt2 = destNode.val0;
        for (Block bb : cfg.reversePostOrder()) {
        	Iterator<Unit> uit = bb.iterator();
            while (uit.hasNext()) {
            	Unit q = uit.next();
            	if (SootUtilities.isInvoke(q) && calls(ctxt1, q, ctxt2, meth2)) {
            		invks.add(q);
            	}
            }
        }
        return invks;
    }
    public boolean hasEdge(Pair<Ctxt, SootMethod> node1, Pair<Ctxt, SootMethod> node2) {
        if (!relCMCM.isOpen())
            relCMCM.load();
        return relCMCM.contains(node1.val0, node1.val1, node2.val0, node2.val1);
    }
    public int numRoots() {
        if (!relRootCM.isOpen())
            relRootCM.load();
        return relRootCM.size();
    }
    public int numNodes() {
        if (!relReachableCM.isOpen())
            relReachableCM.load();
        return relReachableCM.size();
    }
    public int numPreds(Pair<Ctxt, SootMethod> node) {
        if (!relCMCM.isOpen())
            relCMCM.load();
        RelView view = relCMCM.getView();
        view.selectAndDelete(2, node.val0);
        view.selectAndDelete(3, node.val1);
        return view.size();
    }
    public boolean calls(Ctxt origCtxt, Unit origInvk, Ctxt destCtxt, SootMethod destMeth) {
        if (!relCICM.isOpen())
            relCICM.load();
        return relCICM.contains(origCtxt, origInvk, destCtxt, destMeth);
    }
    /**
     * Frees relations used by this call graph if they are in memory.
     * <p>
     * This method must be called after clients are done exercising
     * the interface of this call graph.
     */
    public void free() {
        if (relRootCM.isOpen())
            relRootCM.close();
        if (relReachableCM.isOpen())
            relReachableCM.close();
        if (relCICM.isOpen())
            relCICM.close();
        if (relCMCM.isOpen())
            relCMCM.close();
    }
}


text:
package de.mhu.com.morse.obj;

import java.util.Date;

import de.mhu.com.morse.utils.MorseException;

public interface ITable extends ITableRead,ITableWrite {

	public int getSize();
	public void setCursor( int pos ) throws MorseException;
	public int getCursor();

	public void createRow() throws MorseException;
	public void appendRow() throws MorseException;
	public void insertRow( int pos ) throws MorseException;
	// public void copyRow() throws MorseException;
	public void removeRow() throws MorseException;
	public void removeRow( int pos ) throws MorseException;

}


text:
// +build darwin

package util

import (
	"os"
	"syscall"
)

func Fdatasync(file *os.File) error {
	return syscall.Fsync(int(file.Fd()))
}


text:
using Rhino.Security.Interfaces;
using Rhino.Security.Model;

namespace Rhino.Security.Interfaces
{
	/// <summary>
	/// Allow to define permissions using a fluent interface
	/// </summary>
	public interface IPermissionsBuilderService
	{
		/// <summary>
		/// Allow permission for the specified operation.
		/// </summary>
		/// <param name="operationName">Name of the operation.</param>
		/// <returns></returns>
		IForPermissionBuilder Allow(string operationName);

		/// <summary>
		/// Deny permission for the specified operation
		/// </summary>
		/// <param name="operationName">Name of the operation.</param>
		/// <returns></returns>
		IForPermissionBuilder Deny(string operationName);

		/// <summary>
		/// Allow permission for the specified operation.
		/// </summary>
		/// <param name="operation">The operation.</param>
		IForPermissionBuilder Allow(Operation operation);

		/// <summary>
		/// Deny permission for the specified operation
		/// </summary>
		/// <param name="operation">The operation.</param>
		IForPermissionBuilder Deny(Operation operation);
	}
}


text:
package org.traccar.api;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.traccar.Context;
import org.traccar.Main;
import org.traccar.api.resource.SessionResource;
import org.traccar.database.StatisticsManager;
import org.traccar.helper.Log;
import org.traccar.model.Device;

public class MediaFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {
            HttpSession session = ((HttpServletRequest) request).getSession(false);
            Long userId = null;
            if (session != null) {
                userId = (Long) session.getAttribute(SessionResource.USER_ID_KEY);
                if (userId != null) {
                    Context.getPermissionsManager().checkUserEnabled(userId);
                    Main.getInjector().getInstance(StatisticsManager.class).registerRequest(userId);
                }
            }
            if (userId == null) {
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

            String path = ((HttpServletRequest) request).getPathInfo();
            String[] parts = path != null ? path.split("/") : null;
            if (parts != null && parts.length >= 2) {
                Device device = Context.getDeviceManager().getByUniqueId(parts[1]);
                if (device != null) {
                    Context.getPermissionsManager().checkDevice(userId, device.getId());
                    chain.doFilter(request, response);
                    return;
                }
            }

            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (SecurityException e) {
            httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            httpResponse.getWriter().println(Log.exceptionStack(e));
        } catch (SQLException e) {
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.getWriter().println(Log.exceptionStack(e));
        }
    }

    @Override
    public void destroy() {
    }

}


text:
<resources>
    <string name="app_name">SimpleTodo</string>
    <string name="action_settings">Settings</string>
    <string name="etNewItemHint">Enter New Item</string>
    <string name="title_activity_edit_item">EditItemActivity</string>
    <string name="labelEditText">Edit Text Below</string>
    <string-array name="priority_array">
        <item>High</item>
        <item>Medium</item>
        <item>Low</item>
    </string-array>
</resources>


text:
package org.apache.accumulo.core.rpc;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class SaslClientDigestCallbackHandlerTest {

  @Test
  public void testEquality() {
    SaslClientDigestCallbackHandler handler1 =
        new SaslClientDigestCallbackHandler("user", "mypass".toCharArray()),
        handler2 = new SaslClientDigestCallbackHandler("user", "mypass".toCharArray());
    assertEquals(handler1, handler2);
    assertEquals(handler1.hashCode(), handler2.hashCode());
  }

}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable
  devise :database_authenticatable, :registerable, :recoverable,
         :rememberable, :trackable, :validatable

  devise :omniauthable, :omniauth_providers => [:github]

  validates :bitcoin_address, :bitcoin_address => true

  has_many :tips

  def github_url
    "https://github.com/#{nickname}"
  end

  def balance
  	tips.unpaid.sum(:amount)
  end

  after_create :generate_login_token!
  def generate_login_token!
    if login_token.blank?
      self.update login_token: SecureRandom.urlsafe_base64
    end
  end

  def full_name
    if !name.blank?
      name
    elsif !nickname.blank?
      nickname
    else
      email
    end
  end

  def self.update_cache
    commits_counts = Tip.group(:user_id).count
    paid_sums = Tip.paid.group(:user_id).sum(:amount)

    find_each do |user|
      user.commits_count = commits_counts[user.id] || 0
      user.withdrawn_amount = paid_sums[user.id] || 0
      user.save
    end
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <!--个人信息-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iv_comment_avatar"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@mipmap/default_avatar"/>

            <TextView
                android:id="@+id/tv_comment_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:textColor="@color/text_black"
                android:textSize="12dp"
                tools:text="用户名11111111"/>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:background="@color/gap"/>

            <TextView
                android:id="@+id/tv_comment_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/item_info"
                android:textSize="12dp"
                tools:text="刚刚"/>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="18dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_weight="1"
                android:gravity="right|center_vertical"
                android:orientation="horizontal">

                <CheckBox
                    android:id="@+id/cb_comment_praise"
                    android:layout_width="wrap_content"
                    android:layout_height="18dp"
                    android:button="@null"
                    android:drawableLeft="@drawable/selector_comment_item_praise"
                    android:drawablePadding="3dp"
                    android:textColor="@drawable/selector_comment_item_praise_text"
                    android:textSize="12sp"
                    tools:text="2000"/>

                <TextView
                    android:id="@+id/tv_comment_amount"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="12dp"
                    android:drawableLeft="@mipmap/ic_comment"
                    android:drawablePadding="3dp"
                    android:textColor="@color/text_grey"
                    android:textSize="12sp"
                    android:visibility="gone"
                    tools:text="9527"/>
            </LinearLayout>
        </LinearLayout>
        <!--评论内容-->
        <TextView
            android:id="@+id/tv_comment_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="6dp"
            android:lineSpacingExtra="3dp"
            tools:text="《绝命毒师》系列创作者文斯·吉里根确定正在与索尼展开合作,将会在PSVR平台推出一款以《绝命毒师》为主题的"非游戏"类VR体验作品!体验者将可从【独特的角度】深入了解该系列的世界观![群体围观]"/>
        <!--回复内容-->
        <LinearLayout
            android:id="@+id/ll_comment_reply"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:background="@drawable/ic_reply_box"
            android:orientation="vertical"
            android:visibility="gone">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_reply"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="3dp"
                android:paddingLeft="3dp">
            </android.support.v7.widget.RecyclerView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingBottom="6dp"
                android:text="更多10条回复"
                android:textColor="@color/mainColor"
                android:textSize="12sp"/>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


text:
version=`git describe --tags --long --match ?.?.?`
branch=`echo %build.branch.name% | rev | cut -d/ -f1 | rev`
buildCounter=%build.counter%

if [[ $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9]+)$ ]]
then
    majorVersion="${BASH_REMATCH[1]}"
    minorVersion="${BASH_REMATCH[2]}"
    patchVersion="${BASH_REMATCH[3]}"
    commitCount="${BASH_REMATCH[4]}"
    shortHash="${BASH_REMATCH[5]}"

    packageVersion="$majorVersion.$minorVersion.$patchVersion.$commitCount"

    echo "##teamcity[setParameter name='system.MajorVersion' value='$majorVersion']"
    echo "##teamcity[setParameter name='system.MinorVersion' value='$minorVersion']"
    echo "##teamcity[setParameter name='system.PatchVersion' value='$patchVersion']"
    echo "##teamcity[setParameter name='system.CommitCount' value='$commitCount']"
    echo "##teamcity[setParameter name='system.PackageVersion' value='$packageVersion']"
    echo "##teamcity[setParameter name='system.ShortHash' value='$shortHash']"
    echo "##teamcity[buildNumber '$packageVersion-$branch.$buildCounter']"
else
    echo "$version doesn't match regular expression"
    exit 1
fi


text:
var utils = require('./utils');

module.exports.generateI18N = function (localeTranslations) {
    return makePairValue(localeTranslations);
};

module.exports.angularReadme = function() {
    return 'How to use translations from Transmogrifier  for angular\n\n' +
        '1) 2 possibilities:\n' +
        '\t-> $ bower install angular-translate\n' +
        '\t-> download file from http://angular-translate.github.io/\n' +
        '2) Import angular-translate(.min).js in your index.html (before app.js)\n' +
        '3) Declare pascalprecht.translate as module in your angular.module(\'app_name\', [place "pascalprecht.translate here"]);\n' +
        '4) Import the translation files in your index.html\n' +
        '5) Finally choose your preferred language:\n\n' +
        'app.config([\'$translateProvider\', function ($translateProvider) {\n' +
        '\t$translateProvider.preferredLanguage(\'be_nl\');\n' +
        '}]);\n\n' +
        'Thank you for using Transmogrifier';
};

function makePairValue(localeTranslations) {
    if (!localeTranslations) return null;
    else {
        var angular = '/*\nTransmogrifier\nAngular Translations\n\nDate: ' + new Date() + '\n*/\n\n' +
            "var app = angular.module('place_your_appname_here');\n\n" +
            "app.config(['$translateProvider', function($translateProvider) {\n" +
            "$translateProvider.translations('" + localeTranslations.isoCode + '_' + localeTranslations.countryCode + "', {\n";
        for (var i = 0; i < localeTranslations.keys.length; i++) {
            var key = localeTranslations.keys[i];
            key.key = key.key.replace(/ /g, '_');
            angular += '\n' + key.key + ': "' + key.translation.value + '",';
            if (key.pluralizable) {
                var props = ['zero', 'one', 'two', 'few', 'many', 'other'];
                for (var plural in key.translation.plurals) {
                    if (props.indexOf(plural.toString()) != -1 && key.translation.plurals.hasOwnProperty(plural)) {
                        if (key.translation.plurals[plural]) angular += '\n' + key.key + '_' + plural + ': "' + key.translation.plurals[plural] + '",';
                    }
                }
            }
        }
        angular.split('%d').join('{{replace_by_your_quantity}}');
        angular = angular.substr(0,angular.length-1);
        angular += "\n});\n}]);";
        return angular;
    }
}


text:
import { stringify, clone, shallowCompare } from './util';
import { isReadOnly } from './readonly';

const NON_EXIST_VAL = { };

// Make all nodes on the key path are mutable(clone them first)
export default function select(keyPath) {
  const keys = parseKeyPath(keyPath) || [];

  // Check the container, the top node
  if (isReadOnly(this)) throw new Error('Only mutable object allowed in select()');
  if (!this.$updatex) {
    Object.defineProperty(this, '$updatex', {
      value: { selectedPaths: {} },
      writable: true,
    });
  }

  // node on the path, it is always mutable,
  // which is cloned and safe to mutate directly
  let node;
  let original; // the node's original value
  const path = []; // the node's path

  node = this;
  for (let ii = 0, len = keys.length; ii < len; ++ii) {
    const key = keys[ii];
    path.push(key);

    let child;
    if (!node.hasOwnProperty(key)) {
      original = NON_EXIST_VAL;
      child = {};
      node[key] = child;
    } else {
      child = node[key];
      if (!child || typeof child !== 'object') {
        throw new TypeError(`Cannot select a non-object value at ${path.join('.')}: ${stringify(child)}`);
      }

      if (isReadOnly(child)) {
        original = child;
        child = clone(child);
        node[key] = child;
      }
      // else means child already has been selected in prev operation
    }

    node = child;

    // No original value means that key path is sub string of the prev selected path;
    if (original) addSelectedPath.call(this, path);
  }

  return node;
}

function addSelectedPath(path) {
  const pathString = path.join('.');
  const { selectedPaths } = this.$updatex;
  if (selectedPaths[pathString]) return;

  // Check whether prev selected path is sub string of current
  const selectedPathStrings = Object.keys(selectedPaths);
  for (let ii = 0, len = selectedPathStrings.length; ii < len; ++ii) {
    const selectedPathString = selectedPathStrings[ii],
      matchPathString = `${selectedPathString}.`;
    if (pathString.slice(0, matchPathString.length) === matchPathString) {
      delete selectedPaths[selectedPathString];
      break;
    }
  }

  selectedPaths[pathString] = path;
}

export function checkOverSelect(cloned, original) {
  const { selectedPaths } = cloned.$updatex;
  const pathStrings = Object.keys(selectedPaths);
  for (let ii = 0, len = pathStrings.length; ii < len; ++ii) {
    const pathString = pathStrings[ii];
    const path = selectedPaths[pathString];

    const oldVal = getValueFromPath(original, path);
    const newVal = getValueFromPath(cloned, path);

    if (shallowCompare(newVal, oldVal)) {
      console.warn(`No value changed in path(${pathString}), you may over select path`);
    }
  }
}

function getValueFromPath(obj, path) {
  if (!obj) return;

  for (let ii = 0, len = path.length; ii < len; ++ii) {
    if (!obj) return;

    const key = path[ii];
    if (!obj.hasOwnProperty(key)) return;

    obj = obj[key];
  }

  return obj;
}

function parseKeyPath(keyPath) {
  if (keyPath === null || keyPath === undefined) return [];

  if (Array.isArray(keyPath)) {
    const result = [];
    for (let ii = 0, len = keyPath.length; ii < len; ++ii) {
      let key = keyPath[ii];
      if (key === undefined || key === null) continue;
      if (typeof key !== 'string') key += '';
      result.push(key);
    }
    return result;
  } else {
    const type = typeof keyPath;
    if (type === 'string') {
      return keyPath.split('.').filter(key => !!key);
    } else if (type === 'number') {
      return [`${keyPath}`];
    } else {
      throw new TypeError(`Invalid key path: ${stringify(keyPath)}, expect string or array`);
    }
  }
}


text:
var ATM = can.DefineMap.extend({
	state: {type: "string", value: "readingCard"}
});

can.Component.extend({
	tag: "atm-machine",
	view: can.stache.from("atm-template"),
	ViewModel: ATM,
});

document.body.insertBefore(
	can.stache.from("app-template")({}),
    document.body.firstChild
);

// ========================================
// TESTS
// ========================================

QUnit.module("ATM system", {
	setup: function() {
		can.fixture.delay = 1;
	},
	teardown: function() {
		can.fixture.delay = 2000;
	}
});

QUnit.asyncTest("Valid Card", function() {

	var c = new Card({
		number: "01234567890",
		pin: 1234
	});

	QUnit.equal(c.state, "unverified");

	c.verify();

	QUnit.equal(c.state, "verifying", "card is verifying");

	c.on("state", function(ev, newVal) {

		QUnit.equal(newVal, "verified", "card is verified");

		QUnit.start();
	});
});

QUnit.asyncTest("Invalid Card", function() {

	var c = new Card({});

	QUnit.equal(c.state, "unverified");

	c.verify();

	QUnit.equal(c.state, "verifying", "card is verifying");

	c.on("state", function(ev, newVal) {

		QUnit.equal(newVal, "invalid", "card is invalid");

		QUnit.start();
	});
});


text:
@interface CDABundleSyncModule : CDANSOperationBaseModule

@end


text:
'use strict';

// Package config
var packageConfig = require('../package.json');

// Node utils
var cartridgeUtil = require('cartridge-module-util')(packageConfig);
var path          = require('path');

var TASK_NAME = 'local-server';

// Exit if NODE_ENV is development
cartridgeUtil.exitIfDevEnvironment();
// Make sure that the .cartridgerc file exists
cartridgeUtil.ensureCartridgeExists();
// Run through the project setup
cartridgeUtil.addToRc()
	.then(function(){
		return cartridgeUtil.addModuleConfig(path.resolve('_config', 'task.' + TASK_NAME + '.js'));
	})
	.then(cartridgeUtil.finishInstall);


text:
using NodaTime;
using TimeSimulator.Abstractions.Clock;
using TimeSimulator.Abstractions.Timer;

namespace TimeSimulator.NodaTime
{
    public class NodaTimer : Timer<Instant, Duration>
    {
        public NodaTimer(ICanAddTime<Duration> clock) : base(clock) { }

        public override int AddToBuffer(Duration interval)
        {
            intervalBuffer = intervalBuffer + interval;
            var repetitions = intervalBuffer / Interval;
            if (repetitions > 0)
            {
                intervalBuffer -= ((int)repetitions * Interval);
            }
            return (int)repetitions;
        }
    }
}


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/pci.h>
#include <linux/gpio.h>
#include <linux/mfd/rdc321x.h>
#include <linux/slab.h>

struct rdc321x_gpio {
	spinlock_t		lock;
	struct pci_dev		*sb_pdev;
	u32			data_reg[2];
	int			reg1_ctrl_base;
	int			reg1_data_base;
	int			reg2_ctrl_base;
	int			reg2_data_base;
	struct gpio_chip	chip;
};

/* read GPIO pin */
static int rdc_gpio_get_value(struct gpio_chip *chip, unsigned gpio)
{
	struct rdc321x_gpio *gpch;
	u32 value = 0;
	int reg;

	gpch = gpiochip_get_data(chip);
	reg = gpio < 32 ? gpch->reg1_data_base : gpch->reg2_data_base;

	spin_lock(&gpch->lock);
	pci_write_config_dword(gpch->sb_pdev, reg,
					gpch->data_reg[gpio < 32 ? 0 : 1]);
	pci_read_config_dword(gpch->sb_pdev, reg, &value);
	spin_unlock(&gpch->lock);

	return (1 << (gpio & 0x1f)) & value ? 1 : 0;
}

static void rdc_gpio_set_value_impl(struct gpio_chip *chip,
				unsigned gpio, int value)
{
	struct rdc321x_gpio *gpch;
	int reg = (gpio < 32) ? 0 : 1;

	gpch = gpiochip_get_data(chip);

	if (value)
		gpch->data_reg[reg] |= 1 << (gpio & 0x1f);
	else
		gpch->data_reg[reg] &= ~(1 << (gpio & 0x1f));

	pci_write_config_dword(gpch->sb_pdev,
			reg ? gpch->reg2_data_base : gpch->reg1_data_base,
			gpch->data_reg[reg]);
}

/* set GPIO pin to value */
static void rdc_gpio_set_value(struct gpio_chip *chip,
				unsigned gpio, int value)
{
	struct rdc321x_gpio *gpch;

	gpch = gpiochip_get_data(chip);
	spin_lock(&gpch->lock);
	rdc_gpio_set_value_impl(chip, gpio, value);
	spin_unlock(&gpch->lock);
}

static int rdc_gpio_config(struct gpio_chip *chip,
				unsigned gpio, int value)
{
	struct rdc321x_gpio *gpch;
	int err;
	u32 reg;

	gpch = gpiochip_get_data(chip);

	spin_lock(&gpch->lock);
	err = pci_read_config_dword(gpch->sb_pdev, gpio < 32 ?
			gpch->reg1_ctrl_base : gpch->reg2_ctrl_base, &reg);
	if (err)
		goto unlock;

	reg |= 1 << (gpio & 0x1f);

	err = pci_write_config_dword(gpch->sb_pdev, gpio < 32 ?
			gpch->reg1_ctrl_base : gpch->reg2_ctrl_base, reg);
	if (err)
		goto unlock;

	rdc_gpio_set_value_impl(chip, gpio, value);

unlock:
	spin_unlock(&gpch->lock);

	return err;
}

/* configure GPIO pin as input */
static int rdc_gpio_direction_input(struct gpio_chip *chip, unsigned gpio)
{
	return rdc_gpio_config(chip, gpio, 1);
}

/*
 * Cache the initial value of both GPIO data registers
 */
static int rdc321x_gpio_probe(struct platform_device *pdev)
{
	int err;
	struct resource *r;
	struct rdc321x_gpio *rdc321x_gpio_dev;
	struct rdc321x_gpio_pdata *pdata;

	pdata = dev_get_platdata(&pdev->dev);
	if (!pdata) {
		dev_err(&pdev->dev, "no platform data supplied\n");
		return -ENODEV;
	}

	rdc321x_gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct rdc321x_gpio),
					GFP_KERNEL);
	if (!rdc321x_gpio_dev)
		return -ENOMEM;

	r = platform_get_resource_byname(pdev, IORESOURCE_IO, "gpio-reg1");
	if (!r) {
		dev_err(&pdev->dev, "failed to get gpio-reg1 resource\n");
		return -ENODEV;
	}

	spin_lock_init(&rdc321x_gpio_dev->lock);
	rdc321x_gpio_dev->sb_pdev = pdata->sb_pdev;
	rdc321x_gpio_dev->reg1_ctrl_base = r->start;
	rdc321x_gpio_dev->reg1_data_base = r->start + 0x4;

	r = platform_get_resource_byname(pdev, IORESOURCE_IO, "gpio-reg2");
	if (!r) {
		dev_err(&pdev->dev, "failed to get gpio-reg2 resource\n");
		return -ENODEV;
	}

	rdc321x_gpio_dev->reg2_ctrl_base = r->start;
	rdc321x_gpio_dev->reg2_data_base = r->start + 0x4;

	rdc321x_gpio_dev->chip.label = "rdc321x-gpio";
	rdc321x_gpio_dev->chip.owner = THIS_MODULE;
	rdc321x_gpio_dev->chip.direction_input = rdc_gpio_direction_input;
	rdc321x_gpio_dev->chip.direction_output = rdc_gpio_config;
	rdc321x_gpio_dev->chip.get = rdc_gpio_get_value;
	rdc321x_gpio_dev->chip.set = rdc_gpio_set_value;
	rdc321x_gpio_dev->chip.base = 0;
	rdc321x_gpio_dev->chip.ngpio = pdata->max_gpios;

	platform_set_drvdata(pdev, rdc321x_gpio_dev);

	/* This might not be, what others (BIOS, bootloader, etc.)
	   wrote to these registers before, but it's a good guess. Still
	   better than just using 0xffffffff. */
	err = pci_read_config_dword(rdc321x_gpio_dev->sb_pdev,
					rdc321x_gpio_dev->reg1_data_base,
					&rdc321x_gpio_dev->data_reg[0]);
	if (err)
		return err;

	err = pci_read_config_dword(rdc321x_gpio_dev->sb_pdev,
					rdc321x_gpio_dev->reg2_data_base,
					&rdc321x_gpio_dev->data_reg[1]);
	if (err)
		return err;

	dev_info(&pdev->dev, "registering %d GPIOs\n",
					rdc321x_gpio_dev->chip.ngpio);
	return gpiochip_add_data(&rdc321x_gpio_dev->chip, rdc321x_gpio_dev);
}

static int rdc321x_gpio_remove(struct platform_device *pdev)
{
	struct rdc321x_gpio *rdc321x_gpio_dev = platform_get_drvdata(pdev);

	gpiochip_remove(&rdc321x_gpio_dev->chip);

	return 0;
}

static struct platform_driver rdc321x_gpio_driver = {
	.driver.name	= "rdc321x-gpio",
	.driver.owner	= THIS_MODULE,
	.probe		= rdc321x_gpio_probe,
	.remove		= rdc321x_gpio_remove,
};

module_platform_driver(rdc321x_gpio_driver);

MODULE_AUTHOR("Florian Fainelli <florian@openwrt.org>");
MODULE_DESCRIPTION("RDC321x GPIO driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:rdc321x-gpio");


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.6">
  <compounddef id="structboost_1_1geometry_1_1resolve__strategy_1_1distance__result" kind="struct" prot="public">
    <compoundname>boost::geometry::resolve_strategy::distance_result</compoundname>
    <basecompoundref refid="structboost_1_1geometry_1_1strategy_1_1distance_1_1services_1_1return__type" prot="public" virt="non-virtual">boost::geometry::strategy::distance::services::return_type< Strategy, point_type< Geometry1 >::type, point_type< Geometry2 >::type ></basecompoundref>
    <derivedcompoundref refid="structboost_1_1geometry_1_1resolve__variant_1_1distance__result" prot="public" virt="non-virtual">boost::geometry::resolve_variant::distance_result< Geometry1, Geometry2, Strategy ></derivedcompoundref>
    <includes local="no">distance_result.hpp</includes>
    <templateparamlist>
      <param>
        <type>typename</type>
        <declname>Geometry1</declname>
        <defname>Geometry1</defname>
      </param>
      <param>
        <type>typename</type>
        <declname>Geometry2</declname>
        <defname>Geometry2</defname>
      </param>
      <param>
        <type>typename</type>
        <declname>Strategy</declname>
        <defname>Strategy</defname>
      </param>
    </templateparamlist>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <inheritancegraph>
      <node id="731">
        boost::geometry::resolve_variant::distance_result< Geometry1, Geometry2, Strategy >
        <link refid="structboost_1_1geometry_1_1resolve__variant_1_1distance__result"/>
        <childnode refid="729" relation="public-inheritance">
        </childnode>
      </node>
      <node id="733">
        boost::geometry::distance_result< Geometry1, Geometry2, void >
        <link refid="structboost_1_1geometry_1_1distance__result_3_01_geometry1_00_01_geometry2_00_01void_01_4"/>
        <childnode refid="732" relation="public-inheritance">
        </childnode>
      </node>
      <node id="734">
        boost::geometry::default_distance_result< Geometry1, Geometry2 >
        <link refid="structboost_1_1geometry_1_1default__distance__result"/>
        <childnode refid="733" relation="public-inheritance">
        </childnode>
      </node>
      <node id="729">
        boost::geometry::resolve_strategy::distance_result< Geometry1, Geometry2, Strategy >
        <link refid="structboost_1_1geometry_1_1resolve__strategy_1_1distance__result"/>
        <childnode refid="730" relation="public-inheritance">
        </childnode>
      </node>
      <node id="732">
        boost::geometry::distance_result< Geometry1, Geometry2, Strategy >
        <link refid="structboost_1_1geometry_1_1distance__result"/>
        <childnode refid="731" relation="public-inheritance">
        </childnode>
      </node>
      <node id="730">
        boost::geometry::strategy::distance::services::return_type< Strategy, point_type< Geometry1 >::type, point_type< Geometry2 >::type >
        <link refid="structboost_1_1geometry_1_1strategy_1_1distance_1_1services_1_1return__type"/>
      </node>
    </inheritancegraph>
    <collaborationgraph>
      <node id="735">
        boost::geometry::resolve_strategy::distance_result< Geometry1, Geometry2, Strategy >
        <link refid="structboost_1_1geometry_1_1resolve__strategy_1_1distance__result"/>
        <childnode refid="736" relation="public-inheritance">
        </childnode>
      </node>
      <node id="736">
        boost::geometry::strategy::distance::services::return_type< Strategy, point_type< Geometry1 >::type, point_type< Geometry2 >::type >
        <link refid="structboost_1_1geometry_1_1strategy_1_1distance_1_1services_1_1return__type"/>
      </node>
    </collaborationgraph>
    <location file="/home/travis/build/boostorg/boost/boost/geometry/strategies/distance_result.hpp" line="57" column="1" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/strategies/distance_result.hpp" bodystart="50" bodyend="57"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1strategy_1_1distance_1_1services_1_1return__type_1aaa63d9f53da472aa093e480ae634b79c" prot="public" virt="non-virtual"><scope>boost::geometry::resolve_strategy::distance_result</scope><name>BOOST_MPL_ASSERT_MSG</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
.. _dane_z_pliku:

Dane z pliku
##################

Dane z tabel w bazach MS Accessa lub LibreOffice Base'a możemy eksportować
do formatu *csv*, czyli pliku tekstowego, w którym każda linia reprezentuje
pojedynczy rekord, a wartości pól oddzielone są jakimś separatorem, najczęściej
przecinkiem.

Załóżmy więc, że mamy plik :download:`uczniowie.csv` zawierający dane uczniów
w formacie: ``Jan,Nowak,2``. Poniżej podajemy przykład funkcji, która
odczyta dane i zwróci je w użytecznej postaci:

.. raw:: html

Kod nr

.. literalinclude:: dane.py
    :linenos:

Na początku funkcji ``pobierz_dane()`` sprawdzamy, czy istnieje plik
podany jako argumet. Wykorzystujemy metodę ``isfile()`` z modułu ``os``,
który należy wcześniej zaimportować. Następnie w konstrukcji ``with``
otwieramy plik i wczytujemy jego treść do zmiennej ``zawartosc``.
Pętla ``for`` pobiera kolejne linie, które oczyszczamy ze znaków końca linii
(``.replace('\n','')``, ``.replace('\r','')``) i dekodujemy jako zapisane w standardzie *utf-8*.
Poszczególne wartości oddzielone przecinkiem wyodrębniamy (``.split(',')``)
do tupli, którą dodajemy do zdefiniowanej wcześniej listy (``dane.append()``).

Na koniec funkcja zwraca listę przekształconą na tuplę (a więc zagnieżdzone tuple),
która po przypisaniu do jakiejś zmiennej może zostać użyta np.
jako argument metody ``.executemany()`` (zob. przykład poniżej).

Powyższy kod można zmodyfikować, aby zwracał dane w strukturę wymaganą
przez ORM Peewee, tj. listę słowników zawierających dane w formacie
"klucz":"wartość" (zob. :ref:`Systemy ORM -> Operacje CRUD <systemy_orm>`).

.. attention::

    Znaki w pliku wejściowym powinny być zakodowane w standardzie ``utf-8``.

Przykład użycia
****************

W skrypcie omówionym w materiale :ref:`SQL <sql_raw>` można wykorzystać poniższy kod:

.. code-block:: python

    from dane import pobierz_dane

    # ...

    uczniowie = pobierz_dane('uczniowie.csv')
    cur.executemany(
    'INSERT INTO uczen (imie,nazwisko,klasa_id) VALUES(?,?,?)', uczniowie)


text:
//
//  Copyright (C) 2015 Greg Landrum and NextMove Software
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#ifndef _RD_SEQUENCEPARSE_H_
#define _RD_SEQUENCEPARSE_H_
#include <string>

namespace RDKit{
  class RWMol;

  // \brief construct a molecule from a sequence string (currently only supports peptides)
  /*!
   *   \param seq      - the string to be processed
   *   \param sanitize - toggles sanitization and stereochemistry perception of the molecule
   *   \param lowerD   - if set, lower case letters will be parsed as the d form of the corresponding amino acid
   *
   */
  RWMol *SequenceToMol(const char *seq, bool sanitize=true, bool lowerD=false);
  //! \overload
  RWMol *SequenceToMol(const std::string &seq, bool sanitize=true,
                       bool lowerD=false);

  // \brief construct a molecule from a FASTA string (currently only supports peptides)
  /*!
   *   \param seq      - the string to be processed
   *   \param sanitize - toggles sanitization and stereochemistry perception of the molecule
   *   \param lowerD   - if set, lower case letters will be parsed as the d form of the corresponding amino acid
   *
   */
  RWMol *FASTAToMol(const char *seq, bool sanitize=true, bool lowerD=false);
  //! \overload
  RWMol *FASTAToMol(const std::string &seq, bool sanitize=true,
                    bool lowerD=false);

  // \brief construct a molecule from a HELM string (currently only supports peptides)
  /*!
   *   \param seq      - the string to be processed
   *   \param sanitize - toggles sanitization and stereochemistry perception of the molecule
   *
   */
  RWMol *HELMToMol(const char *helm, bool sanitize=true);
  //! \overload
  RWMol *HELMToMol(const std::string &helm, bool sanitize=true);
}

#endif


text:
@cls
@%SystemRoot%\Microsoft.NET\Framework\v3.5\MSBuild buildkit35.build


text:
class PowerManagerPro < Cask
  version :latest
  sha256 :no_check

  url 'https://www.dssw.co.uk/powermanager/dsswpowermanagerpro.dmg'
  appcast 'http://version.dssw.co.uk/powermanager/professional'
  homepage 'https://www.dssw.co.uk/powermanager'

  app 'Power Manager Pro.app'
end


text:
/*
 * kernel/src/fs/pub.c
 */

#include <stddef.h>
#include "pub.h"

fs_entry_t * pub_fs_aquire(const char * name, fs_entry_t * cd)
{
	fs_entry_t * f;

	f = fs_retrieve(name, cd);
	if (f == NULL) return NULL;
	if (!trylock(&f->lock)) return NULL;

	/* TODO check file permissions */
	/* TODO associate lock with thread */

	return f;
}

void pub_fs_release(fs_entry_t * f)
{
	/* TODO check lock is associated with thread */
	unlock(&f->lock);
}

fs_entry_t * pub_fs_first(fs_entry_t * f)
{
	/* TODO check permissions */
	return fs_first(f);
}

fs_entry_t * pub_fs_next(fs_entry_t * f)
{
	/* TODO check permissions */
	return fs_next(f);
}

fs_entry_t * pub_fs_mkdir(const char * name, fs_entry_t * par)
{
	/* TODO check permissions */
	return fs_mkdir(name, par);
}

fs_entry_t * pub_fs_mkvdir(const char * name, fs_entry_t * par)
{
	/* TODO check permissions */
	return fs_mkvdir(name, par);
}

qword pub_fs_size(fs_entry_t * f)
{
	/* TODO check permissions */
	return fs_size(f);
}

qword pub_fs_read(byte * buf, qword addr, qword size, fs_entry_t * f)
{
	/* TODO check permissions */
	return fs_read(buf, addr, size, f);
}

qword pub_fs_write(byte * buf, qword addr, qword size, fs_entry_t * f)
{
	/* TODO check permissions */
	return fs_write(buf, addr, size, f);
}


text:
package org.gradle.internal.featurelifecycle;

public class SimulatedDeprecationMessageLogger {
    public static final String DIRECT_CALL = "direct call";
    public static final String INDIRECT_CALL = "indirect call";
    public static final String INDIRECT_CALL_2 = "second-level indirect call";

    public static DeprecatedFeatureUsage indirectlySecondLevel(String message) {
        return indirectly(message);
    }

    public static DeprecatedFeatureUsage indirectly(String message) {
        return nagUserWith(message);
    }

    public static DeprecatedFeatureUsage nagUserWith(String message) {
        return new DeprecatedFeatureUsage(message, SimulatedDeprecationMessageLogger.class).withStackTrace();
    }
}


text:
//
// ´ËÎļþÊÇÓÉ JavaTM Architecture for XML Binding (JAXB) ÒýÓÃʵÏÖ v2.2.7 Éú³ÉµÄ
// Çë·ÃÎÊ http://java.sun.com/xml/jaxb
// ÔÚÖØбàÒëԴģʽʱ, ¶Ô´ËÎļþµÄËùÓÐÐ޸Ķ¼½«¶ªÊ§¡£
// Éú³Éʱ¼ä: 2014.11.23 ʱ¼ä 07:49:23 PM EST
//

package edu.stevens.cs548.clinic.service.web.rest.data;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
providerType complex typeµÄ Java Àà¡£
 *
 *
ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
 *
 *

 * <complexType name="providerType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="NPI" type="{http://www.w3.org/2001/XMLSchema}long"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="specialization" type="{http://cs548.stevens.edu/clinic/service/web/rest/data}SpeicalizationType"/>
 *         <element name="treatments" type="{http://cs548.stevens.edu/clinic/service/web/rest/data/dap}LinkType" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "providerType", propOrder = {
    "npi",
    "name",
    "specialization",
    "treatments"
})
public class ProviderType {

    @XmlElement(name = "NPI")
    protected long npi;
    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = false)
    protected SpeicalizationType specialization;
    @XmlElement(required = true, nillable = true)
    protected List<LinkType> treatments;

    /**
     * »ñÈ¡npiÊôÐÔµÄÖµ¡£
     *
     */
    public long getNPI() {
        return npi;
    }

    /**
     * ÉèÖÃnpiÊôÐÔµÄÖµ¡£
     *
     */
    public void setNPI(long value) {
        this.npi = value;
    }

    /**
     * »ñÈ¡nameÊôÐÔµÄÖµ¡£
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * ÉèÖÃnameÊôÐÔµÄÖµ¡£
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * »ñÈ¡specializationÊôÐÔµÄÖµ¡£
     *
     * @return
     *     possible object is
     *     {@link SpeicalizationType }
     *
     */
    public SpeicalizationType getSpecialization() {
        return specialization;
    }

    /**
     * ÉèÖÃspecializationÊôÐÔµÄÖµ¡£
     *
     * @param value
     *     allowed object is
     *     {@link SpeicalizationType }
     *
     */
    public void setSpecialization(SpeicalizationType value) {
        this.specialization = value;
    }

    /**
     * Gets the value of the treatments property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the treatments property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getTreatments().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link LinkType }
     *
     *
     */
    public List<LinkType> getTreatments() {
        if (treatments == null) {
            treatments = new ArrayList<LinkType>();
        }
        return this.treatments;
    }

}


text:
ALPHABETICAL_PAGINATE_CONFIG = {
  db_field: "users.name",
  numbers: false,
  others: false,
  include_all: false,
  js: false,
  bootstrap3: true,
  db_mode: true,
}.freeze


text:
module ApplicationHelper

  def full_title(page_title="")
    base_title = "Institute of Technology, Gopeshwar"
    if page_title.empty?
      base_title
    else
      "#{page_title} | #{base_title}"
    end
  end
end


text:
package types

type NullVal struct{}

func (b *NullVal) SetBoolean(v bool) {
	panic("Unable to assign boolean to null field")
}

func (b *NullVal) SetInt(v int32) {
	panic("Unable to assign boolean to null field")
}

func (b *NullVal) SetLong(v int64) {
	panic("Unable to assign long to null field")
}

func (b *NullVal) SetFloat(v float32) {
	panic("Unable to assign float to null field")
}

func (b *NullVal) SetUnionElem(v int64) {
	panic("Unable to assign union elem to null field")
}

func (b *NullVal) SetDouble(v float64) {
	panic("Unable to assign double to null field")
}

func (b *NullVal) SetBytes(v []byte) {
	panic("Unable to assign bytes to null field")
}

func (b *NullVal) SetString(v string) {
	panic("Unable to assign string to null field")
}

func (b *NullVal) Get(i int) Field {
	panic("Unable to get field from null field")
}

func (b *NullVal) SetDefault(i int) {
	panic("Unable to set default on null field")
}

func (b *NullVal) AppendMap(key string) Field {
	panic("Unable to append map key to from null field")
}

func (b *NullVal) AppendArray() Field {
	panic("Unable to append array element to from null field")
}

func (b *NullVal) NullField(int) {
	panic("Unable to null field in null field")
}

func (b *NullVal) Finalize() {}


text:
/**
 * Generic search/higlight component that honours depths and
 * expanded/collapsed trees.
 * @see VirtualTextSearch
 * @see TextSearch
 * @constructor
 */
var ListTextSearch = function()
{
  const
  SEARCH_DELAY = 50; // in ms

  var
  self = this,
  search_term = '',
  search_results = [],
  cursor = -1,
  container = null,
  input = null,
  timeouts = new Timeouts(),
  cache = {},
  current_id = '',
  current_context = null,
  go_back = {},
  highlightColor = '';

  this.search = function(new_search_term)
  {
    var cur = null, cur_2 = null, depth = 0, display = '';

    if( new_search_term != search_term )
    {
      if(go_back[current_id])
      {
        delete go_back[current_id];
      }
      search_results = [];
      cache[current_id] = search_term = new_search_term;
      cur = container.getElementsByTagName('start-search-scope')[0];
      while( cur && ( cur = cur.nextSibling ) && cur.nodeName.toLowerCase() != "end-search-scope" )
      {
        display =
          cur.getElementsByTagName('key')[0].textContent.indexOf(search_term) == -1
          && 'none'
          || '';
        cur.style.display = display;
        if( !display )
        {
          search_results[search_results.length] = cur;
        }
        depth = parseInt( cur.getAttribute('depth'));
        cur_2 = cur;
        while( ( cur_2 = cur_2.nextSibling )
                  && cur_2.nodeName.toLowerCase() != "end-search-scope"
                  && ( parseInt( cur.getAttribute('depth')) < depth ) )
        {
          cur = cur_2;
          cur.style.display = display;
        }
      }
    }
  }

  this.searchDelayed = function(new_search_term)
  {
    timeouts.set(this.search, SEARCH_DELAY, new_search_term);
  }

  var __selected_element = null;

  var selectNextInput = function(start, next, direction)
  {
    var
    cur = __selected_element && __selected_element.parentNode
      || container.getElementsByTagName(start)[0],
    scrollTop = 0,
    scrollBottom = 0,
    targetTop = 0,
    targetBottom = 0;

    while( ( cur = cur[next] )
      && !( cur.nodeName.toLowerCase() == 'item'
      && cur.style.display != 'none'
      && ( cur.firstChild && /input/i.test(cur.firstChild.nodeName) ) ) );
    if( cur && cur.nodeName.toLowerCase() == 'item' )
    {
      if( __selected_element )
      {
        //__selected_element.parentNode.removeClass('selected');
        __selected_element.parentNode.style.removeProperty('background-color');
      }
      __selected_element = cur.firstChild;
      //cur.addClass('selected');
      cur.style.backgroundColor = highlightColor;
      scrollTop = container.scrollTop;
      scrollBottom = scrollTop + container.offsetHeight;
      targetTop = cur.offsetTop;
      targetBottom = targetTop + cur.offsetHeight;
      if( targetBottom > scrollBottom )
      {
        container.scrollTop += 50 + targetBottom - scrollBottom;
      }
      else if( targetTop < scrollTop )
      {
        container.scrollTop += targetTop - scrollTop - 50;
      }
    }
    else
    {
      container.scrollTop += direction * 50;
    }
  }

  this.handleKey = function(event, target)
  {
    event.stopPropagation();
    event.preventDefault();
    switch( event.keyCode)
    {
      case 40: // down
      {
        selectNextInput('start-search-scope', 'nextSibling', 1);
        break;
      }

      case 38: // up
      {
        selectNextInput('end-search-scope', 'previousSibling', -1);
        break;
      }

      case 13:
      {
        if( __selected_element )
        {
          __selected_element.click();
        }
        break;
      }

      default:
      {
        if( __selected_element )
        {
          __selected_element.parentNode.removeClass('selected');
          __selected_element = null;
        }

      }
    }
  }

  this.handleEnterKey = function()
  {
    switch( event.keyCode)
    {
      case 13:
      {
        if( search_results.length == 1 )
        {
          var _input = search_results[0].getElementsByTagName('input')[0];
          if( _input )
          {
            _input.click();
          }
        }
        break;
      }
      case 8:
      {
        if(input && !input.value)
        {
          var target = getTarget();
          if( target && ( target = target.getElementsByTagName('input')[0] ) )
          {
            // TODO this call causes problems
            if( go_back[current_id] )
            {
              target.click();
            }
            else
            {
              go_back[current_id] = 1;
            }
            //target.click();
          }
        }

        break;
      }
    }
  }

  var getTarget = function(str_id)
  {
    var items = null, item = null, i = 0;
    if( container && current_context )
    {
      items = container.getElementsByTagName('item');
      for( ; item = items[i]; i++)
      {
        if( item.getAttribute('obj-id') == current_context.obj_id
            && item.getAttribute('depth') == current_context.depth
            && item.getElementsByTagName('key')[0].textContent == current_context.key )
        {
          break;
        }
      }
    }
    return item;
  }

  this.onNewContext = function(msg)
  {
    current_context = msg;
    current_id = msg.rt_id + "." + msg.obj_id + "." + msg.depth;
    if( input )
    {
      if( cache[current_id] )
      {
        input.value = cache[current_id];
        //this.search(cache[current_id]);
      }
      else
      {
        input.value = '';
      }
    }
  }

  this.setInput = function(target)
  {
    input = target;
  }

  this.setContainer = function(_container)
  {
    if( container != _container )
    {
      container = _container;
      if( !highlightColor )
      {
        highlightColor =
          document.styleSheets.getPropertyValue('item.selected', 'background-color');
      }
    }
  }

  this.cleanup = function()
  {
    /*
    search_term = '';
    search_results = [];
    cursor = -1;
    */
    current_id = '';
    current_context = null;
    search_results = [];
    input = null;
    container = null;
  }

};


text:
#pragma once

#include <iostream>

#include <cstdint>
#include <functional>

#include "util.hh"

class Station {
public:
	Station(std::uint_fast32_t cicle, std::int_fast32_t id, std::string uname) : _mBlocked(false), _mAlive(true), \
		_mActiveTime(0), _mStartTime(cicle), _mID(id), _userName(uname)
		{ _mSubKey = ClockSubject::get().registerObserver(std::bind(&Station::updateTime, this)); }

	bool getBlocked() const { return _mBlocked; }
	bool getTerminated() const { return !(_mAlive); }
	std::int_fast16_t getID() const { return _mID; }
	std::string getUserName() const { return _userName; }
	std::int_fast32_t getActiveTime() const { return _mActiveTime; }

	void unblock();
	void block() { _mBlocked = true; ClockSubject::get().unregisterObserver(_mSubKey); _mSubKey = 0; }
	void message(std::string msg, std::int_fast32_t senderID, std::string senderName) { /* OH HAI */ }
	void terminate(uint_fast32_t cycle) { _mStoptTime = cycle; _mAlive = false; \
										  ClockSubject::get().unregisterObserver(_mSubKey); _mSubKey = 0; }
	void updateTime() { _mActiveTime++; }
private:
	std::int_fast16_t _mID;
	std::string _userName;
	std::uint_fast32_t _mStartTime;
	std::uint_fast32_t _mActiveTime;
	std::uint_fast32_t _mStoptTime;
	std::size_t _mSubKey;
	bool _mBlocked;
	bool _mAlive;
};