text:
using System;
using System.Collections.Generic;
using System.Text;

namespace ZM.Media.Info
{
    /// <summary>
    /// Contains an menu stream details.
    /// </summary>
    public class MenuStream : MediaStream
    {
        /// <summary>
        /// Position of first chapter in the chapter list.
        /// </summary>
        public int Chapters_Pos_Begin { get; set; }
        /// <summary>
        /// Position of last chapter in the chapter list.
        /// </summary>
        public int Chapters_Pos_End { get; set; }

        /// <summary>
        /// List of chapters.
        /// </summary>
        [IgnoreProperty]
        public List<string> Chapters { get; private set; }

        /// <summary>
        /// Creates a new instance of MenuStream.
        /// </summary>
        public MenuStream() : base()
        {
            Chapters = new List<string>();
        }

        public override string Display(bool ShowEmptyProperties = false)
        {
            return string.Format("{0} chapters:\n{1}", Chapters.Count, string.Join("\n", Chapters));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { PageComponent } from './pages.component';

const routes: Routes = [
    {
        path: '', component: PageComponent,
        children: [
            { path: 'starter', loadChildren: './starter/starter.module#StarterModule' },
            { path: 'accordion', loadChildren: './component/accordion/accordion.module#AccordionModule' },
            { path: 'alert', loadChildren: './component/alert/alert.module#NgAlertModule' },
            { path: 'carousel', loadChildren: './component/carousel/carousel.module#ButtonsModule' },
            { path: 'datepicker', loadChildren: './component/datepicker/datepicker.module#DatepickerModule' },
            { path: 'dropdown', loadChildren: './component/dropdown-collapse/dropdown-collapse.module#DropdownModule' },
            { path: 'modal', loadChildren: './component/modal/modal.module#ModalModule' },
            { path: 'pagination', loadChildren: './component/pagination/pagination.module#paginationModule' },
            { path: 'poptool', loadChildren: './component/popover-tooltip/popover-tooltip.module#PopoverTooltipModule' },
            { path: 'progressbar', loadChildren: './component/progressbar/progressbar.module#progressbarModule' },
            { path: 'rating', loadChildren: './component/rating/rating.module#RatingModule' },
            { path: 'tabs', loadChildren: './component/tabs/tabs.module#TabsModule' },
            { path: 'timepicker', loadChildren: './component/timepicker/timepicker.module#TimepickerModule' },
            { path: 'typehead', loadChildren: './component/typehead/typehead.module#TypeheadModule' },
            { path: 'fontawesome', loadChildren: './icons/fontawesome/fontawesome.module#FontawesomeModule' },
            { path: 'simpleline', loadChildren: './icons/simpleline/simpleline.module#SimplelineIconModule' },
            { path: 'material', loadChildren: './icons/material/material.module#MaterialComponentModule' },
            { path: 'basicform', loadChildren: './form/basic/basic.module#BasicFormModule' },
            { path: 'basictable', loadChildren: './table/basic/basic.module#BasicTableModule' }

        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class PagesRoutingModule { }


text:
package org.apache.commons.digester3.examples.api.addressbook;

import org.apache.commons.digester3.Digester;

/**
 * A simple program to demonstrate the basic functionality of the
 * Commons Digester module.
 *

 * This code will parse the provided "example.xml" file to build a tree
 * of java objects, then cause those objects to print out their values
 * to demonstrate that the input file has been processed correctly.
 *

 * As with all code, there are many ways of achieving the same goal;
 * the solution here is only one possible solution to the problem.
*

 * Very verbose comments are included here, as this class is intended
 * as a tutorial; if you look closely at method "addRules", you will
 * see that the amount of code required to use the Digester is actually
 * quite low.
 *

 * Usage: java Main example.xml
 */
public class Main
{

    /**
     * Main method : entry point for running this example program.
     *

     * Usage: java Example example.xml
     */
    public static void main( final String[] args )
    {
        if ( args.length != 1 )
        {
            usage();
            System.exit( -1 );
        }

        final String filename = args[0];

        // Create a Digester instance
        final Digester d = new Digester();

        // Prime the digester stack with an object for rules to
        // operate on. Note that it is quite common for "this"
        // to be the object pushed.
        final AddressBook book = new AddressBook();
        d.push( book );

        // Add rules to the digester that will be triggered while
        // parsing occurs.
        addRules( d );

        // Process the input file.
        try
        {
            final java.io.File srcfile = new java.io.File( filename );
            d.parse( srcfile );
        }
        catch ( final java.io.IOException ioe )
        {
            System.out.println( "Error reading input file:" + ioe.getMessage() );
            System.exit( -1 );
        }
        catch ( final org.xml.sax.SAXException se )
        {
            System.out.println( "Error parsing input file:" + se.getMessage() );
            System.exit( -1 );
        }

        // Print out all the contents of the address book, as loaded from
        // the input file.
        book.print();
    }

    private static void addRules( final Digester d )
    {

        // --------------------------------------------------
        // when we encounter a "person" tag, do the following:

        // create a new instance of class Person, and push that
        // object onto the digester stack of objects
        d.addObjectCreate( "address-book/person", Person.class );

        // map *any* attributes on the tag to appropriate
        // setter-methods on the top object on the stack (the Person
        // instance created by the preceeding rule).
        //
        // For example:
        // if attribute "id" exists on the xml tag, and method setId
        // with one parameter exists on the object that is on top of
        // the digester object stack, then a call will be made to that
        // method. The value will be type-converted from string to
        // whatever type the target method declares (where possible),
        // using the commons ConvertUtils functionality.
        //
        // Attributes on the xml tag for which no setter methods exist
        // on the top object on the stack are just ignored.
        d.addSetProperties( "address-book/person" );

        // call the addPerson method on the second-to-top object on
        // the stack (the AddressBook object), passing the top object
        // on the stack (the recently created Person object).
        d.addSetNext( "address-book/person", "addPerson" );

        // --------------------------------------------------
        // when we encounter a "name" tag, call setName on the top
        // object on the stack, passing the text contained within the
        // body of that name element [specifying a zero parameter count
        // implies one actual parameter, being the body text].
        // The top object on the stack will be a person object, because
        // the pattern address-book/person always triggers the
        // ObjectCreateRule we added previously.
        d.addCallMethod( "address-book/person/name", "setName", 0 );

        // --------------------------------------------------
        // when we encounter an "email" tag, call addEmail on the top
        // object on the stack, passing two parameters: the "type"
        // attribute, and the text within the tag body.
        d.addCallMethod( "address-book/person/email", "addEmail", 2 );
        d.addCallParam( "address-book/person/email", 0, "type" );
        d.addCallParam( "address-book/person/email", 1 );

        // --------------------------------------------------
        // When we encounter an "address" tag, create an instance of class
        // Address and push it on the digester stack of objects. After
        // doing that, call addAddress on the second-to-top object on the
        // digester stack (a "Person" object), passing the top object on
        // the digester stack (the "Address" object). And also set things
        // up so that for each child xml element encountered between the start
        // of the address tag and the end of the address tag, the text
        // contained in that element is passed to a setXXX method on the
        // Address object where XXX is the name of the xml element found.
        d.addObjectCreate( "address-book/person/address", Address.class );
        d.addSetNext( "address-book/person/address", "addAddress" );
        d.addSetNestedProperties( "address-book/person/address" );
    }

    private static void usage()
    {
        System.out.println( "Usage: java Main example.xml" );
    }

}


text:
package org.atlasapi.output.writers;

import java.io.IOException;

import org.atlasapi.content.ReleaseDate;
import org.atlasapi.output.EntityListWriter;
import org.atlasapi.output.FieldWriter;
import org.atlasapi.output.OutputContext;

public final class ReleaseDateWriter implements EntityListWriter<ReleaseDate> {

    @Override
    public void write(ReleaseDate entity, FieldWriter writer, OutputContext ctxt)
            throws IOException {
        writer.writeField("release_date", entity.date());
        writer.writeField("country", entity.country());
        writer.writeField("type", entity.type().toString().toLowerCase());
    }

    @Override
    public String listName() {
        return "release_dates";
    }

    @Override
    public String fieldName(ReleaseDate entity) {
        return "release_date";
    }
}


text:
package com.example.meteo.meteo.model;

/**
 * Created by dirceu on 16/04/17.
 */

public class WeatherHistory{

    private String date;
    private String condition;
    private String max;
    private String min;
    private String icon;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getMax() {
        return max;
    }

    public void setMax(String max) {
        this.max = max;
    }

    public String getMin() {
        return min;
    }

    public void setMin(String min) {
        this.min = min;
    }

    public String getIcon() {
        return icon;
    }

    public void setIconId(String iconId) {
        this.icon = iconId;
    }

    public WeatherHistory() {
    }

}


text:
package main

import (
	"fmt"
	"io"
	"os"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/log"
	"github.com/urfave/cli"
)

var imagesImportCommand = cli.Command{
	Name:      "import",
	Usage:     "import an image",
	ArgsUsage: "[flags] <ref> <in>",
	Description: `Import an image from a tar stream
`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "ref-object",
			Value: "",
			Usage: "reference object e.g. tag@digest (default: use the object specified in ref)",
		},
	},
	Action: func(clicontext *cli.Context) error {
		var (
			ref       = clicontext.Args().First()
			in        = clicontext.Args().Get(1)
			refObject = clicontext.String("ref-object")
		)

		ctx, cancel := appContext(clicontext)
		defer cancel()

		client, err := newClient(clicontext)
		if err != nil {
			return err
		}

		var r io.ReadCloser
		if in == "-" {
			r = os.Stdin
		} else {
			r, err = os.Open(in)
			if err != nil {
				return err
			}
		}
		img, err := client.Import(ctx,
			ref,
			r,
			containerd.WithRefObject(refObject),
		)
		if err != nil {
			return err
		}
		if err = r.Close(); err != nil {
			return err
		}

		log.G(ctx).WithField("image", ref).Debug("unpacking")

		// TODO: Show unpack status
		fmt.Printf("unpacking %s...", img.Target().Digest)
		err = img.Unpack(ctx, clicontext.String("snapshotter"))
		fmt.Println("done")
		return err
	},
}


text:
package net.wildbill22.draco_too;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import net.wildbill22.draco.lib.BALANCE;
import net.wildbill22.draco.lib.LogHelper;
import net.wildbill22.draco_too.blocks.ModBlocks;
import cpw.mods.fml.common.IWorldGenerator;

/**
 *
 * @author WILLIAM
 *
 */
public class WorldGenDracoAnimus implements IWorldGenerator {

	private void addSurfaceStructures(World world, Random random, int x, int z) {
		int chance = random.nextInt(1000);
		BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(x, z);

		// Eggs with the normal spawn chance from the configuration
		int spawnChance = BALANCE.DRAGON_EGG_SPAWN_CHANCE;
		if (chance < spawnChance) {
			// TODO: Set which biomes you want the egg to appear in
			if (biome == BiomeGenBase.extremeHills || biome == BiomeGenBase.extremeHillsEdge || biome == BiomeGenBase.extremeHillsPlus) {
				if (generateDragonEgg(world, random, x, world.getTopSolidOrLiquidBlock(x, z), z, ModBlocks.myDragonEgg))
					LogHelper.info("WorldGenDracoAnimus: Spawned a Draco Mia Egg at: " + x + "," + world.getTopSolidOrLiquidBlock(x, z) + "," + z);
			}
		}
	}

	@Override
	public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {

		switch (world.provider.dimensionId) {
		case -1:
			generateNether(world, random, chunkX * 16, chunkZ * 16);
		case 0:
			generateSurface(world, random, chunkX * 16, chunkZ * 16);
		case 1:
			generateEnd(world, random, chunkX * 16, chunkZ * 16);
		}
	}

	private void generateEnd(World world, Random random, int x, int z) {
	}

	private void generateNether(World world, Random random, int x, int z) {
	}

	private void generateSurface(World world, Random random, int x, int z) {
		addSurfaceStructures(world, random, x, z);
	}

	// Place just one egg
    public boolean generateDragonEgg(World world, Random random, int x, int y, int z, Block eggBlock) {
        for (int l = 0; l < 32; ++l) {
            int chunkX = x + random.nextInt(8) - random.nextInt(8);
            int chunkY = y + random.nextInt(4) - random.nextInt(4);
            int chunkZ = z + random.nextInt(8) - random.nextInt(8);

            if ((world.isAirBlock(chunkX, chunkY, chunkZ) || world.getBlock(chunkX, chunkY, chunkZ) == Blocks.water)
            		&& eggBlock.canPlaceBlockAt(world, chunkX, chunkY, chunkZ) && !world.isAirBlock(chunkX, chunkY-1, chunkZ)) {
                world.setBlock(chunkX, chunkY, chunkZ, eggBlock);
                return true;
            }
        }
        return false;
    }
}


text:
namespace GreenPipes.Agents
{
    public interface StopSupervisorContext :
        StopContext
    {
        /// <summary>
        /// The agents available when the Stop was initiated
        /// </summary>
        IAgent[] Agents { get; }
    }
}


text:
<?php

namespace Drupal\Core\Entity\Annotation;

use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Defines a config entity type annotation object.
 *
 * The annotation properties of entity types are found on
 * \Drupal\Core\Config\Entity\ConfigEntityType and are accessed using
 * get/set methods defined in \Drupal\Core\Entity\EntityTypeInterface.
 *
 * @ingroup entity_api
 *
 * @Annotation
 */
class ConfigEntityType extends EntityType {

  /**
   * {@inheritdoc}
   */
  public $entity_type_class = 'Drupal\Core\Config\Entity\ConfigEntityType';

  /**
   * {@inheritdoc}
   */
  public $group = 'configuration';

  /**
   * {@inheritdoc}
   */
  public function get() {
    $this->definition['group_label'] = new TranslatableMarkup('Configuration', [], ['context' => 'Entity type group']);

    return parent::get();
  }

}


text:
package org.kaazing.gateway.service;

import static java.lang.String.format;
import static java.util.Collections.unmodifiableMap;
import static java.util.ServiceLoader.load;

import java.util.Collection;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class ServiceFactory {

    private final Map<String, ServiceFactorySpi> serviceFactoriesByType;

    private ServiceFactory(Map<String, ServiceFactorySpi> serviceFactoriesByType) {
        this.serviceFactoriesByType = unmodifiableMap(serviceFactoriesByType);
    }

    public static ServiceFactory newServiceFactory() {
        return newServiceFactory(load(ServiceFactorySpi.class));
    }

    public static ServiceFactory newServiceFactory(ClassLoader loader) {
        return newServiceFactory(load(ServiceFactorySpi.class, loader));
    }

    public Service newService(String serviceType) {
        ServiceFactorySpi serviceFactory = serviceFactoriesByType.get(serviceType);
        if (serviceFactory == null) {
            throw new IllegalArgumentException("Unrecognized service type: " + serviceType);
        }
        return serviceFactory.newService(serviceType);
    }

    private static ServiceFactory newServiceFactory(ServiceLoader<ServiceFactorySpi> serviceFactories) {
        ConcurrentMap<String, ServiceFactorySpi> serviceFactoriesByType = new ConcurrentHashMap<>();
        for (ServiceFactorySpi serviceFactory : serviceFactories) {
            Collection<String> serviceTypes = serviceFactory.getServiceTypes();
            for (String serviceType : serviceTypes) {
                ServiceFactorySpi oldServiceFactory = serviceFactoriesByType.putIfAbsent(serviceType, serviceFactory);
                if (oldServiceFactory != null) {
                    // TODO: ignore, log warning?
                    throw new RuntimeException(format("Duplicate type service factory: %s", serviceType));
                }
            }
        }
        return new ServiceFactory(serviceFactoriesByType);
    }
}


text:
import pychrono as chrono
import pychrono.irrlicht as chronoirr

# The path to the Chrono data directory containing various assets (meshes, textures, data files)
# is automatically set, relative to the default location of this demo.
# If running from a different directory, you must change the path to the data directory with:
#chrono.SetChronoDataPath('path/to/data')

# ---------------------------------------------------------------------
#
#  Create the simulation system.
#  (Do not create parts and constraints programmatically here, we will
#  load a mechanism from file)

sys = chrono.ChSystemNSC()

# Set the collision margins. This is expecially important for very large or
# very small objects (as in this example)! Do this before creating shapes.
chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001);
chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001);

# ---------------------------------------------------------------------
#
#  load the file generated by the SolidWorks CAD plugin
#  and add it to the system
#

print ("Loading C::E scene...");

exported_items = chrono.ImportSolidWorksSystem(chrono.GetChronoDataFile('solid_works/swiss_escapement'))

print ("...done!");

# Print exported items
for item in exported_items:
    print (item.GetName())

# Add items to the physical system
for item in exported_items:
    sys.Add(item)

# ---------------------------------------------------------------------
#
#  Create an Irrlicht application to visualize the system
#

vis = chronoirr.ChVisualSystemIrrlicht()
sys.SetVisualSystem(vis)
vis.SetWindowSize(1024,768)
vis.SetWindowTitle('Test: using data exported by Chrono::Solidworks')
vis.Initialize()
vis.AddLogo(chrono.GetChronoDataFile('logo_pychrono_alpha.png'))
vis.AddSkyBox()
vis.AddCamera(chrono.ChVectorD(0.3,0.3,0.4))
vis.AddTypicalLights()

# ---------------------------------------------------------------------
#
#  Run the simulation
#

sys.SetMaxPenetrationRecoverySpeed(0.002);

while vis.Run():
    vis.BeginScene()
    vis.DrawAll()
    vis.EndScene()
    sys.DoStepDynamics(0.002)


text:
package transfer

import (
	"testing"

	"github.com/juntaki/transparent"
	"github.com/juntaki/transparent/test"
)

func TestTransfer(t *testing.T) {
	serverAddr := "localhost:8080"
	r := NewSimpleLayerReceiver(serverAddr)
	d := test.NewSource(0)
	s := transparent.NewStack()
	s.Stack(d)
	s.Stack(r)
	s.Start()

	tra := NewSimpleLayerTransmitter(serverAddr)

	test.BasicTransmitterFunc(t, tra)
	s.Stop()
}


text:
/**
 This header is private to the Twitter Core SDK and not exposed for public SDK consumption
 */

#import <Foundation/Foundation.h>
#import "TWTRNetworkingPipeline.h"

/**
 * Abstraction to read off the `date` header from Twitter's API. This offset value can be used to
 * set the correct GTM time to our OAuth requests
 */
@interface TWTRAPIDateSync : NSObject

/**
 *  @param response     response from the API request
 *  @param responseData data from the request response
 */
- (nullable instancetype)initWithHTTPResponse:(nullable NSURLResponse *)response NS_DESIGNATED_INITIALIZER;

- (nullable instancetype)init NS_UNAVAILABLE;

/**
 * Parses http response header and syncs OAuth offsets if necessary
 *
 * @return YES if there was a delta
 */
- (BOOL)sync;

@end


text:
package org.openspaces.core;

import com.gigaspaces.internal.metadata.converter.ConversionException;

import org.springframework.dao.InvalidDataAccessResourceUsageException;

/**
 * Thrown when a conversion error occurred. For example, when trying to convert a Pojo into an entry in the space.
 * A wrapper for {@link com.gigaspaces.internal.metadata.converter.ConversionException}.
 *
 * @author kimchy
 */
public class ObjectConversionException extends InvalidDataAccessResourceUsageException {

    private static final long serialVersionUID = 1406696928164962971L;

    public ObjectConversionException(ConversionException e) {
        super(e.getMessage(), e);
    }
}


text:
clean-pslg
============

Resolves all self intersections, t-junctions, and removes duplicate vertices/edges from a [planar straight line graph](https://en.wikipedia.org/wiki/Planar_straight-line_graph) using [iterated snap rounding](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.220).

# [Demo](https://mikolalysenko.github.io/clean-pslg)

Click on the following link to try out `clean-pslg` in your browser:

[](https://mikolalysenko.github.io/clean-pslg)

* [Demo link](https://mikolalysenko.github.io/clean-pslg)

# Example

This module really only does one thing, which is clean up planar straight line graphs.  You invoke it by passing it an array of points and an array of edges like so:

```javascript
var cleanPSLG = require('clean-pslg')

//Create a planar straight line graph with many degenerate crossings
var points      = [
  [ 0.25, 0.5  ],
  [ 0.75, 0.5  ],
  [ 0.5,  0.25 ],
  [ 0.5,  0.75 ],
  [ 0.25, 0.25 ],
  [ 0.75, 0.75 ],
  [ 0.25, 0.75 ],
  [ 0.75, 0.25 ]
]

//These are the edges of the graph
//They are defined by pairs of indices of vertices
var edges       = [
  [0, 1],
  [2, 3],
  [4, 5],
  [6, 7]
]

//Run clean up on the graph
if(cleanPSLG(points, edges)) {
  console.log('removed degeneracies from graph')
}

//clean-pslg operates on the graph in place, so after running it the points/edges will be modified
console.log('points = \n', points)
console.log('edges = \n', edges)
```

#### Output

The program will output the following text:

```
removed degeneracies from graph
points =
 [ [ 0.25, 0.5 ],
  [ 0.75, 0.5 ],
  [ 0.5, 0.25 ],
  [ 0.5, 0.75 ],
  [ 0.25, 0.25 ],
  [ 0.75, 0.75 ],
  [ 0.25, 0.75 ],
  [ 0.75, 0.25 ],
  [ 0.5, 0.5 ] ]
edges =
 [ [ 8, 0 ],
  [ 1, 8 ],
  [ 8, 2 ],
  [ 3, 8 ],
  [ 8, 4 ],
  [ 5, 8 ],
  [ 8, 6 ],
  [ 7, 8 ],
  [ 8, 8 ] ]
```

Visually, this corresponds to the following refinement of a planar graph:

# Install

```
npm i clean-pslg
```

# API

#### `require('clean-pslg')(points, edges[, colors])`
Processes an unoriented planar straight line graph defined by `points` and `edges` in place.

* `points` is an array encoding the vertices of the planar straight line graph as pairs of numbers
* `edges` is an array encoding the edges of the planar straight line graph as pairs of indices
* `colors` is an optional array of edge colors.  If specified, only merge edges if they have the same color.  This can be used to implement orientation preservation or handle solid geometry.

The following degeneracies are handled:

* Duplicate points are merged
* Duplicate edges are merged
* T-junctions are split
* Edge crossings are split

The resulting graph meets all invariants required by `cdt2d`, so it may be triangulated.  Note that this procedure *does not preserve orientation*.

**Returns** `true` if repairs were necessary, otherwise `false`

**Note** This is a destructive procedure, which means that the contents of `points` and `edges` may change.  If you don't want this to happen, you should make a deep copy of `points` and `edges` before calling `clean-pslg`

# License
(c) 2015 Mikola Lysenko. MIT License


text:
namespace AnimalHierarchy.Models
{
    using System;

    using Enumerations;
    using Interfaces;

    /// <summary>
    /// Parent class for animals. Only constuctor require all properties set!
    /// Sound() is abstract. All prop are read-only.
    /// </summary>
    public abstract class Animal : ISound
    {
        private string name;

        private int age;

        private Gender sex;

        public Animal(string name, int age, Gender sex)
        {
            this.Name = name;
            this.Age = age;
            this.Sex = sex;
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            private set
            {
                ValidateName(value);
                this.name = value;
            }
        }

        public int Age
        {
            get
            {
                return this.age;
            }
            private set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Age cannot be negative number!");
                }

                this.age = value;
            }
        }

        public Gender Sex
        {
            get
            {
                return this.sex;
            }
            private set
            {
                this.sex = value;
            }
        }

        public abstract string Sound();

        public void IncreaseAge(int years)
        {
            if (years < 1)
            {
                throw new ArgumentException("Years is 0 or negative! Are you sure you really want to increase age?");
            }

            if (years > 100)
            {
                throw new ArgumentException(string.Format("{0} years is really too much!", years));
            }

            this.age += years;
        }

        public void Rename(string newName)
        {
            this.Name = newName;
        }

        private void ValidateName(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Name have to be set!");
            }

            if (name.Length > 0)
            {
                foreach (var ch in name)
                {
                    if (!char.IsLetter(ch))
                    {
                        throw new ArgumentException("Invalid name!");
                    }
                }
            }
        }
    }
}


text:
import logging
from time import time

from . import utils
from ._compat import to_unicode

class AuthenticationMixin(object):

    def prepare_password(self, secret):
        return u'{pepper}{secret}'.format(
            pepper=to_unicode(self.pepper),
            secret=to_unicode(secret)
        )

    def hash_password(self, secret):
        if secret is None:
            return None

        len_secret = len(secret)
        if len_secret < self.password_minlen:
            raise ValueError(
                'Password is too short. Must have at least {} chars long'.format(
                    self.password_minlen))
        if len_secret > self.password_maxlen:
            raise ValueError(
                'Password is too long. Must have at most {} chars long'.format(
                    self.password_maxlen))

        secret = self.prepare_password(secret)
        hashed = self.hasher.encrypt(secret)
        return hashed

    def password_is_valid(self, secret, hashed):
        if secret is None or hashed is None:
            return False

        # To help preventing denial-of-service via large passwords
        # See: https://www.djangoproject.com/weblog/2013/sep/15/security/
        if len(secret) > self.password_maxlen:
            return False

        secret = self.prepare_password(secret)
        try:
            return self.hasher.verify(secret, hashed)
        except ValueError:
            return False

    def authenticate(self, credentials):
        for backend in self.backends:
            user = backend(credentials)
            if user:
                return user
        return None

    def auth_password(self, credentials):
        logger = logging.getLogger(__name__)
        login = credentials.get('login')
        secret = credentials.get('password')
        if login is None or secret is None:
            return None

        user = self.User.by_login(login)
        if not user:
            logger.debug(u'User `{0}` not found'.format(login))
            return None

        if not user.password:
            logger.debug(u'User `{0}` has no password'.format(login))
            return None

        if not self.password_is_valid(secret, user.password):
            logger.debug(u'Invalid password for user `{0}`'.format(login))
            return None

        self._update_password_hash(secret, user)
        return user

    def _update_password_hash(self, secret, user):
        if not self.update_hash:
            return
        new_hash = self.hash_password(secret)
        if new_hash.split('$')[:3] == user.password.split('$')[:3]:
            return
        user.set_raw_password(new_hash)

    def auth_token(self, credentials, token_life=None):
        logger = logging.getLogger(__name__)
        token = credentials.get('token')
        if token is None:
            return None
        try:
            timestamp, uid = utils.split_token(str(token))
        except ValueError:
            logger.info(u'Invalid auth token format')
            return None

        token_life = token_life or self.token_life
        user = self.User.by_id(uid)
        if not user:
            logger.info(u'Tampered auth token? uid `{0} not found'.format(uid[:20]))
            return None

        valid = user.get_token(timestamp) == token
        not_expired = timestamp + token_life >= int(time())
        if valid and not_expired:
            return user
        logger.info(u'Invalid auth token')
        return None

    def get_user(self, session=None):
        if session is None:
            session = self.session
        user = None
        uhmac = session.get(self.session_key)
        if uhmac:
            try:
                uid = utils.split_uhmac(uhmac)
                user = self.User.by_id(uid)
                if not user or uhmac != user.get_uhmac() or not user.login:
                    raise ValueError
            except ValueError:
                logger = logging.getLogger(__name__)
                logger.warn(u'Tampered uhmac?')
                user = None
                self.logout(session)
        return user

    def login(self, user, remember=True, session=None):
        """Sets the current user UID in the session.

        Instead of just storing the user's id, it generates a hash from the
        password *salt*. That way, an admin or the user herself can invalidate
        the login in other computers just by changing (or re-saving)
        her password.

        """
        logger = logging.getLogger(__name__)
        logger.debug(u'User `{0}` logged in'.format(user.login))
        if session is None:
            session = self.session
        session['permanent'] = remember
        session[self.session_key] = user.get_uhmac()
        if callable(getattr(session, 'save', None)):
            session.save()

    def logout(self, session=None):
        if session is None:
            session = self.session
        if self.session_key in session:
            del session[self.session_key]
        if self.clear_session_on_logout:
            session.clear()
        if callable(getattr(session, 'save', None)):
            session.save()


text:
For further details please consult the following:

* [DICE Monitoring Platform (D-Mon)](https://github.com/dice-project/DICE-Monitoring/blob/master/src/README.md)
	* [DICE Monitoring Agent](https://github.com/dice-project/DICE-Monitoring/blob/master/dmon-agent/README.md)
	* [DICE Logstash Service](https://github.com/dice-project/DICE-Monitoring/blob/master/dmon-logstash/README.md)
	* [DICE ElasticSearch Service](https://github.com/dice-project/DICE-Monitoring/blob/master/dmon-elasticsearch/Readme.md)
* [Vagrantfile for D-Mon](https://github.com/dice-project/DICE-Monitoring/blob/master/vagrant/Vagrant%20CDH%20Cluster/README.md)
* [Vagrantfile for DICE Protable Monitoring Testbed](https://dice-project/DICE-Monitoring/blob/master/vagrant/Monitoring/README.md)


text:
============
Installation
============

At the command line::

    $ easy_install django-formaggio

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv django-formaggio
    $ pip install django-formaggio


text:
package com.containersolutions.mesoshelloworld.systemtest;

import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import static com.jayway.awaitility.Awaitility.await;

/**
 * Response which waits until endpoint is ready
 */
public class HelloWorldResponse {

    private boolean discoverySuccessful;

    public HelloWorldResponse(Set<String> ipAddresses, List<Integer> ports, long timeout) {
        await().atMost(timeout, TimeUnit.SECONDS).until(new TasksCall(ipAddresses, ports));
    }

    public boolean isDiscoverySuccessful() {
        return discoverySuccessful;
    }

    class TasksCall implements Callable<Boolean> {

        private final Set<String> ipAddresses;
        private final List<Integer> ports;

        public TasksCall(Set<String> ipAddresses, List<Integer> ports) {
            this.ipAddresses = ipAddresses;
            this.ports = ports;
        }

        @Override
        public Boolean call() throws Exception {

            final Set<String> goodHosts = new HashSet<>(ipAddresses.size());

            ipAddresses.forEach(ip -> {

                if( !goodHosts.contains(ip) ) {
                    ports.forEach(p -> {

                        if (!goodHosts.contains(ip)) {
                            String url = "http://" + ip + ":" + p;
                            try {
                                System.out.println( goodHosts.size() + ". " + url + " => " + Unirest.get(url).asString().getBody());
                                goodHosts.add( ip );
                            } catch (UnirestException e) {
                                // do nothing
                            }
                        }
                    });

                }

            });

            discoverySuccessful = (goodHosts.size() == ipAddresses.size());
            return discoverySuccessful;

        }

    }
}


text:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Demo code illustrating the SCM semi-empirical model for deformable soil
// =============================================================================

#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/physics/ChLinkMotorRotationAngle.h"
#include "chrono/physics/ChLoadContainer.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#ifdef CHRONO_COLLISION
    #include "chrono/collision/ChCollisionSystemChrono.h"
#endif

#include "chrono_irrlicht/ChVisualSystemIrrlicht.h"

#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/SCMDeformableTerrain.h"

#include "chrono_thirdparty/filesystem/path.h"

using namespace chrono;
using namespace chrono::irrlicht;

using namespace irr;

bool output = false;
const std::string out_dir = GetChronoOutputPath() + "SCM_DEF_SOIL";

// Type of tire (controls both contact and visualization)
enum class TireType { CYLINDRICAL, LUGGED };
TireType tire_type = TireType::LUGGED;

// SCM grid spacing
double mesh_resolution = 0.04;

// Enable/disable bulldozing effects
bool enable_bulldozing = true;

// Enable/disable moving patch feature
bool enable_moving_patch = true;

// If true, use provided callback to change soil properties based on location
bool var_params = true;

// Custom callback for setting location-dependent soil properties.
// Note that the location is given in the SCM reference frame.
// Here, the vehicle moves in the terrain's negative y direction!
class MySoilParams : public vehicle::SCMDeformableTerrain::SoilParametersCallback {
  public:
    virtual void Set(const ChVector<>& loc,
                     double& Bekker_Kphi,
                     double& Bekker_Kc,
                     double& Bekker_n,
                     double& Mohr_cohesion,
                     double& Mohr_friction,
                     double& Janosi_shear,
                     double& elastic_K,
                     double& damping_R) override {
        if (loc.y() > 0) {
            Bekker_Kphi = 0.2e6;
            Bekker_Kc = 0;
            Bekker_n = 1.1;
            Mohr_cohesion = 0;
            Mohr_friction = 30;
            Janosi_shear = 0.01;
            elastic_K = 4e7;
            damping_R = 3e4;
        } else {
            Bekker_Kphi = 5301e3;
            Bekker_Kc = 102e3;
            Bekker_n = 0.793;
            Mohr_cohesion = 1.3e3;
            Mohr_friction = 31.1;
            Janosi_shear = 1.2e-2;
            elastic_K = 4e8;
            damping_R = 3e4;
        }
    }
};

int main(int argc, char* argv[]) {
    GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";

    // Set world frame with Y up
    vehicle::ChWorldFrame::SetYUP();

    // Global parameter for tire:
    double tire_rad = 0.8;
    ChVector<> tire_center(0, 0.02 + tire_rad, -1.5);

    // Create a Chrono::Engine physical system
    auto collsys_type = collision::ChCollisionSystemType::BULLET;
    ChSystemSMC sys;
    sys.SetNumThreads(4, 8, 1);
    if (collsys_type == collision::ChCollisionSystemType::CHRONO) {
#ifdef CHRONO_COLLISION
        auto collsys = chrono_types::make_shared<collision::ChCollisionSystemChrono>();
        collsys->SetBroadphaseGridResolution(ChVector<int>(20, 20, 10));
        sys.SetCollisionSystem(collsys);
#endif
    }

    auto mtruss = chrono_types::make_shared<ChBody>(collsys_type);
    mtruss->SetBodyFixed(true);
    sys.Add(mtruss);

    // Initialize output
    if (output) {
        if (!filesystem::create_directory(filesystem::path(out_dir))) {
            std::cout << "Error creating directory " << out_dir << std::endl;
            return 1;
        }
    }
    utils::CSV_writer csv(" ");

    //
    // Create a rigid body with a mesh or a cylinder collision shape
    //

    auto mrigidbody = chrono_types::make_shared<ChBody>(collsys_type);
    sys.Add(mrigidbody);
    mrigidbody->SetMass(500);
    mrigidbody->SetInertiaXX(ChVector<>(20, 20, 20));
    mrigidbody->SetPos(tire_center + ChVector<>(0, 0.3, 0));

    auto material = chrono_types::make_shared<ChMaterialSurfaceSMC>();
    mrigidbody->GetCollisionModel()->ClearModel();
    switch (tire_type) {
        case TireType::LUGGED: {
            auto trimesh = geometry::ChTriangleMeshConnected::CreateFromWavefrontFile(
                GetChronoDataFile("models/tractor_wheel/tractor_wheel.obj"));

            std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape);
            mrigidmesh->SetMesh(trimesh);
            mrigidmesh->SetColor(ChColor(0.3f, 0.3f, 0.3f));
            mrigidbody->AddVisualShape(mrigidmesh);

            mrigidbody->GetCollisionModel()->AddTriangleMesh(material, trimesh, false, false, VNULL, ChMatrix33<>(1),
                                                             0.01);
            break;
        }
        case TireType::CYLINDRICAL: {
            double radius = 0.5;
            double width = 0.4;
            mrigidbody->GetCollisionModel()->AddCylinder(material, radius, radius, width / 2, ChVector<>(0), Q_from_AngZ(CH_C_PI_2));

            auto cyl_shape = chrono_types::make_shared<ChCylinderShape>();
            cyl_shape->GetCylinderGeometry().rad = radius;
            cyl_shape->GetCylinderGeometry().p1 = ChVector<>(+width / 2, 0, 0);
            cyl_shape->GetCylinderGeometry().p2 = ChVector<>(-width / 2, 0, 0);
            cyl_shape->SetColor(ChColor(0.3f, 0.3f, 0.3f));
            mrigidbody->AddVisualShape(cyl_shape);

            break;
        }
    }
    mrigidbody->GetCollisionModel()->BuildModel();
    mrigidbody->SetCollide(true);

    auto motor = chrono_types::make_shared<ChLinkMotorRotationAngle>();
    motor->SetSpindleConstraint(ChLinkMotorRotation::SpindleConstraint::OLDHAM);
    motor->SetAngleFunction(chrono_types::make_shared<ChFunction_Ramp>(0, CH_C_PI / 4.0));
    motor->Initialize(mrigidbody, mtruss, ChFrame<>(tire_center, Q_from_AngY(CH_C_PI_2)));
    sys.Add(motor);

    //
    // THE DEFORMABLE TERRAIN
    //

    // Create the 'deformable terrain' object
    vehicle::SCMDeformableTerrain mterrain(&sys);

    // Displace/rotate the terrain reference plane.
    // Note that SCMDeformableTerrain uses a default ISO reference frame (Z up). Since the mechanism is modeled here in
    // a Y-up global frame, we rotate the terrain plane by -90 degrees about the X axis.
    mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(-CH_C_PI_2)));

    // Initialize the geometry of the soil

    // Use either a regular grid:
    double length = 6;
    double width = 2;
    mterrain.Initialize(width, length, mesh_resolution);

    // Or use a height map:
    ////mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), width, length, 0, 0.5, mesh_resolution);

    // Or use a mesh:
    ////mterrain.Initialize(vehicle::GetDataFile("terrain/meshes/test_terrain_irregular.obj"), mesh_resolution);

    // Set the soil terramechanical parameters
    if (var_params) {
        // Location-dependent soil properties
        auto my_params = chrono_types::make_shared<MySoilParams>();
        mterrain.RegisterSoilParametersCallback(my_params);
    } else {
        // Constant soil properties
        mterrain.SetSoilParameters(0.2e6,  // Bekker Kphi
                                   0,      // Bekker Kc
                                   1.1,    // Bekker n exponent
                                   0,      // Mohr cohesive limit (Pa)
                                   30,     // Mohr friction limit (degrees)
                                   0.01,   // Janosi shear coefficient (m)
                                   4e7,    // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi
                                   3e4     // Damping (Pa s/m), proportional to negative vertical speed (optional)
        );

        // LETE sand parameters
        ////mterrain.SetSoilParameters(5301e3,  // Bekker Kphi
        ////                           102e3,   // Bekker Kc
        ////                           0.793,   // Bekker n exponent
        ////                           1.3e3,   // Mohr cohesive limit (Pa)
        ////                           31.1,    // Mohr friction limit (degrees)
        ////                           1.2e-2,  // Janosi shear coefficient (m)
        ////                           4e8,     // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi
        ////                           3e4      // Damping (Pa s/m), proportional to negative vertical speed (optional)
        ////);
    }

    if (enable_bulldozing) {
        mterrain.EnableBulldozing(true);  // inflate soil at the border of the rut
        mterrain.SetBulldozingParameters(
            55,   // angle of friction for erosion of displaced material at the border of the rut
            1,    // displaced material vs downward pressed material.
            5,    // number of erosion refinements per timestep
            6);  // number of concentric vertex selections subject to erosion
    }

    // Optionally, enable moving patch feature (reduces number of ray casts)
    if (enable_moving_patch) {
        mterrain.AddMovingPatch(mrigidbody, ChVector<>(0, 0, 0), ChVector<>(0.5, 2 * tire_rad, 2 * tire_rad));
    }

    // Set some visualization parameters: either with a texture, or with falsecolor plot, etc.
    ////mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
    mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE, 0, 30000.2);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE, 0, 0.15);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_ISLAND_ID, 0, 8);
    ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_IS_TOUCHED, 0, 8);
    mterrain.SetMeshWireframe(true);

    // Create the Irrlicht visualization system
    auto vis = chrono_types::make_shared<ChVisualSystemIrrlicht>();
    sys.SetVisualSystem(vis);
    vis->SetWindowSize(800, 600);
    vis->SetWindowTitle("Deformable soil");
    vis->Initialize();
    vis->AddLogo();
    vis->AddSkyBox();
    vis->AddCamera(ChVector<>(2.0, 1.4, 0.0), ChVector<>(0, tire_rad, 0));
    vis->AddTypicalLights();

    //
    // THE SOFT-REAL-TIME CYCLE
    //
    /*
        // Change the timestepper to HHT:
        sys.SetTimestepperType(ChTimestepper::Type::HHT);
        auto integrator = std::static_pointer_cast<ChTimestepperHHT>(sys.GetTimestepper());
        integrator->SetAlpha(-0.2);
        integrator->SetMaxiters(8);
        integrator->SetAbsTolerances(1e-05, 1.8e00);
        integrator->SetMode(ChTimestepperHHT::POSITION);
        integrator->SetModifiedNewton(true);
        integrator->SetScaling(true);
        integrator->SetVerbose(true);
    */
    /*
        sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT);
    */

    while (vis->Run()) {
        double time = sys.GetChTime();
        if (output) {
            vehicle::TerrainForce frc = mterrain.GetContactForce(mrigidbody);
            csv << time << frc.force << frc.moment << frc.point << std::endl;
        }

        ////std::cout << "\nTime: " << time << std::endl;
        ////std::cout << "Wheel pos: " << mrigidbody->GetPos() << std::endl;
        ////std::cout << "Wheel rot: " << mrigidbody->GetRot() << std::endl;

        vis->BeginScene();
        vis->GetActiveCamera()->setTarget(core::vector3dfCH(mrigidbody->GetPos()));
        vis->DrawAll();
        tools::drawColorbar(vis.get(), 0, 30000, "Pressure yield [Pa]", 1180);
        vis->EndScene();

        sys.DoStepDynamics(0.002);
        ////mterrain.PrintStepStatistics(std::cout);
    }

    if (output) {
        csv.write_to_file(out_dir + "/output.dat");
    }

    return 0;
}


text:
package ibft

import (
	"encoding/binary"
	"fmt"
	"net"

	"github.com/u-root/u-root/pkg/uio"
)

var (
	signature  = [4]byte{'i', 'B', 'F', 'T'}
	oemID      = [6]byte{'G', 'o', 'o', 'g', 'l', 'e'}
	oemTableID = [8]byte{'G', 'o', 'o', 'g', 'I', 'B', 'F', 'T'}
)

type structureID uint8

const (
	reserved structureID = iota
	ibftControlID
	ibftInitiatorID
	ibftNICID
	ibftTargetID
	ibftExtensionsID
)

const (
	ibftControlLen   uint16 = 18
	ibftInitiatorLen uint16 = 74
	ibftNICLen       uint16 = 102
	ibftTargetLen    uint16 = 54
)

type acpiHeader struct {
	Signature       [4]byte
	Length          uint32
	Revision        uint8
	Checksum        uint8
	OEMID           [6]byte
	OEMTableID      [8]byte
	OEMRevision     uint64
	CreatorID       uint64
	CreatorRevision uint64
}

func flags(s ...bool) uint8 {
	var i uint8
	for bit, f := range s {
		if f {
			i |= 1 << uint8(bit)
		} else {
			i &= ^(1 << uint8(bit))
		}
	}
	return i
}

func writeIP6(l *uio.Lexer, ip net.IP) {
	if ip == nil {
		l.WriteBytes(net.IPv6zero)
	} else {
		l.WriteBytes(ip.To16())
	}
}

// ibftStructHeader is the header of each iBFT structure, as defined by iBFT Spec 1.4.2.
type ibftStructHeader struct {
	StructureID structureID
	Version     uint8
	Length      uint16
	Index       uint8
	Flags       uint8
}

// Initiator defines an iSCSI initiator.
type Initiator struct {
	// Name is the name of the initiator.
	//
	// Some servers apparently use initiator names for permissions.
	Name string

	Valid bool

	// Boot indicates that this initiator was used to boot.
	Boot bool

	// I have no clue what this stuff is.
	SNSServer             net.IP
	SLPServer             net.IP
	PrimaryRadiusServer   net.IP
	SecondaryRadiusServer net.IP
}

func (i *Initiator) marshal(h *heapTable) {
	header := ibftStructHeader{
		StructureID: ibftInitiatorID,
		Version:     1,
		Length:      ibftInitiatorLen,
		Index:       0,
		Flags:       flags(i.Valid, i.Boot),
	}
	h.Table.WriteData(&header)

	writeIP6(h.Table, i.SNSServer)
	writeIP6(h.Table, i.SLPServer)
	writeIP6(h.Table, i.PrimaryRadiusServer)
	writeIP6(h.Table, i.SecondaryRadiusServer)
	h.writeHeap([]byte(i.Name))
}

// BDF is a Bus/Device/Function Identifier of a PCI device.
type BDF struct {
	Bus      uint8
	Device   uint8
	Function uint8
}

func (b BDF) marshal(h *heapTable) {
	h.Table.Write16(uint16(uint16(b.Bus)<<8 | uint16(b.Device)<<3 | uint16(b.Function)))
}

// NIC defines NIC network configuration such as IP, gateway, DNS.
type NIC struct {
	// Valid NIC.
	Valid bool

	// Boot indicates this NIC was used to boot from.
	Boot bool

	// Global indicates a globally reachable IP (as opposed to a link-local IP).
	Global bool

	// IPNet is the IP and subnet mask for this network interface.
	IPNet *net.IPNet

	// Origin. Nobody knows what this is. Nobody cares.
	//
	// The spec links to a Microsoft.com 404 page. Yay.
	Origin uint8

	// Gateway is the network gateway. The gateway must be within the IPNet.
	Gateway net.IP

	// PrimaryDNS is the primary DNS server.
	PrimaryDNS net.IP

	// SecondaryDNS is a secondary DNS server.
	SecondaryDNS net.IP

	// DHCPServer is the address for the DHCP server, if one was used.
	DHCPServer net.IP

	// VLAN is the VLAN for this network interface.
	VLAN uint16

	// MACAddress is the MAC of the network interface.
	MACAddress net.HardwareAddr

	// PCIBDF is the Bus/Device/Function identifier of the PCI NIC device.
	PCIBDF BDF

	// HostName is the host name of the machine.
	HostName string
}

func (n *NIC) marshal(h *heapTable) {
	header := ibftStructHeader{
		StructureID: ibftNICID,
		Version:     1,
		Length:      ibftNICLen,
		Index:       0,
		Flags:       flags(n.Valid, n.Boot, n.Global),
	}
	h.Table.WriteData(&header)

	// IP + subnet mask prefix.
	if n.IPNet == nil {
		writeIP6(h.Table, net.IPv6zero)
		h.Table.Write8(0)
	} else {
		writeIP6(h.Table, n.IPNet.IP)
		ones, _ := n.IPNet.Mask.Size()
		h.Table.Write8(uint8(ones))
	}

	h.Table.Write8(n.Origin)

	writeIP6(h.Table, n.Gateway)
	writeIP6(h.Table, n.PrimaryDNS)
	writeIP6(h.Table, n.SecondaryDNS)
	writeIP6(h.Table, n.DHCPServer)

	h.Table.Write16(n.VLAN)
	copy(h.Table.WriteN(6), n.MACAddress)
	n.PCIBDF.marshal(h)
	h.writeHeap([]byte(n.HostName))
}

// Target carries info about an iSCSI target server.
type Target struct {
	Valid bool
	Boot  bool

	CHAP  bool
	RCHAP bool

	// Target is the server to connect to.
	Target *net.TCPAddr

	// BootLUN is the LUN to connect to.
	BootLUN uint64

	CHAPType uint8

	// NICAssociation is the Index of the NIC.
	NICAssociation uint8

	// TargetName is the name of the iSCSI target.
	//
	// The target name must be a valid iSCSI Qualifier Name or EUI.
	TargetName string

	CHAPName          string
	CHAPSecret        string
	ReverseCHAPName   string
	ReverseCHAPSecret string
}

func (t *Target) marshal(h *heapTable) {
	header := ibftStructHeader{
		StructureID: ibftTargetID,
		Version:     1,
		Length:      ibftTargetLen,
		Index:       0,
		Flags:       flags(t.Valid, t.Boot, t.CHAP, t.RCHAP),
	}
	h.Table.WriteData(&header)

	if t.Target == nil {
		writeIP6(h.Table, net.IPv6zero)
		h.Table.Write16(0)
	} else {
		writeIP6(h.Table, t.Target.IP)
		h.Table.Write16(uint16(t.Target.Port))
	}
	h.Table.Write64(t.BootLUN)
	h.Table.Write8(t.CHAPType)
	h.Table.Write8(t.NICAssociation)

	h.writeHeap([]byte(t.TargetName))
	h.writeHeap([]byte(t.CHAPName))
	h.writeHeap([]byte(t.CHAPSecret))
	h.writeHeap([]byte(t.ReverseCHAPName))
	h.writeHeap([]byte(t.ReverseCHAPSecret))
}

// IBFT defines the entire iSCSI boot firmware table.
type IBFT struct {
	SingleLoginMode bool

	// Initiator offset: 0x50
	Initiator Initiator

	// NIC offset: 0xa0
	NIC0 NIC

	// Target offset: 0x110
	Target0 Target
}

// String is a short summary of the iBFT contents.
func (i *IBFT) String() string {
	return fmt.Sprintf("iBFT(iSCSI target=%s, IP=%s)", i.Target0.Target, i.NIC0.IPNet)
}

type heapTable struct {
	heapOffset uint64

	Table *uio.Lexer
	Heap  *uio.Lexer
}

func (h *heapTable) writeHeap(item []byte) {
	if len(item) == 0 {
		// Length.
		h.Table.Write16(0)

		// Offset.
		h.Table.Write16(0)
	} else {
		offset := h.heapOffset + uint64(h.Heap.Len())

		// Length.
		h.Table.Write16(uint16(len(item)))

		// Offset from beginning of iBFT.
		h.Table.Write16(uint16(offset))

		// Write a null-terminated array item.
		//
		// iBFT Spec, Section 1.3.5: "All array items stored in the
		// Heap area will be followed by a separate NULL. This
		// terminating NULL is not counted as part of the array
		// [item's] length."
		h.Heap.WriteBytes(item)
		h.Heap.Write8(0)
	}
}

type ibftControl struct {
	SingleLoginMode bool
	Initiator       uint16
	NIC0            uint16
	Target0         uint16
	NIC1            uint16
	Target1         uint16
}

func (c ibftControl) marshal(h *heapTable) {
	header := ibftStructHeader{
		StructureID: ibftControlID,
		Version:     1,
		Length:      ibftControlLen,
		Index:       0,
		Flags:       flags(c.SingleLoginMode),
	}
	h.Table.WriteData(&header)

	// Extensions: none. EVER.
	h.Table.Write16(0)

	h.Table.Write16(c.Initiator)
	h.Table.Write16(c.NIC0)
	h.Table.Write16(c.Target0)
	h.Table.Write16(c.NIC1)
	h.Table.Write16(c.Target1)
}

func gencsum(b []byte) byte {
	var csum byte
	for _, bb := range b {
		csum += bb
	}
	return ^csum + 1
}

const lengthOffset = 4
const checksumOffset = 9

func fixACPIHeader(b []byte) []byte {
	binary.LittleEndian.PutUint16(b[lengthOffset:], uint16(len(b)))
	b[checksumOffset] = gencsum(b)
	return b
}

const (
	controlOffset   = 0x30
	initiatorOffset = 0x48
	nic0Offset      = 0x98
	target0Offset   = 0x100
	heapOffset      = 0x138
)

// Marshal returns a binary representation of the iBFT.
//
// Pointers within an iBFT is relative, so this can be placed anywhere
// necessary.
func (i *IBFT) Marshal() []byte {
	h := &heapTable{
		heapOffset: heapOffset,

		Table: uio.NewLittleEndianBuffer(nil),
		Heap:  uio.NewLittleEndianBuffer(nil),
	}

	header := &acpiHeader{
		Signature:       signature,
		Length:          0,
		Revision:        1,
		Checksum:        0,
		OEMID:           oemID,
		OEMTableID:      oemTableID,
		OEMRevision:     0,
		CreatorID:       0,
		CreatorRevision: 0,
	}
	h.Table.WriteData(header)

	// iBFT spec, Section 1.4.4.4 "Each structure must be aligned on an 8
	// byte boundary."

	// 0x30
	h.Table.Align(8)
	control := ibftControl{
		SingleLoginMode: i.SingleLoginMode,
		Initiator:       initiatorOffset,
		NIC0:            nic0Offset,
		Target0:         target0Offset,
	}
	control.marshal(h)

	// 0x48
	h.Table.Align(8)
	i.Initiator.marshal(h)

	// 0x98
	h.Table.Align(8)
	i.NIC0.marshal(h)

	// 0x100
	h.Table.Align(8)
	i.Target0.marshal(h)

	// 0x138
	h.Table.Align(8)
	h.Table.WriteBytes(h.Heap.Data())

	return fixACPIHeader(h.Table.Data())
}


text:
package com.hamdikavak.humanmobility.modeling;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.hamdikavak.humanmobility.modeling.exception.InsufficientUniqueLocationException;
import com.hamdikavak.humanmobility.modeling.helpers.LocationTraceHelper;
import com.hamdikavak.humanmobility.modeling.spatial.ExtendedLocationTrace;

/**
 * Preferential return is a term suggested by González, Hidalgo, and Barabási
 * (2008) to describe the probability to return to previously visited locations
 * based on their rankings. If GPS locations are used, these locations have to
 * be clustered using a classification algorithm such as DBSCAN and assigned a
 * location id.
 * <p>
 * Source: González, M. C., Hidalgo, C. A., & Barabási, A.-L. (2008).
 * Understanding individual human mobility patterns. Nature, 453(7196), 779–782.
 * https://doi.org/10.1038/nature06958
 *
 * @author Hamdi Kavak
 * @version 0.3.0
 *
 */
public class PreferentialReturn {

	protected final static Logger logger = Logger.getLogger(PreferentialReturn.class);
	private int defaultNumberOfLocationsToConsider = 5; // default 5

	/**
	 * Calculates preferential return ratios.
	 * @param traces list of traces that a user visited before.
	 * @param numOfLocations number of locations to be considered.
	 * @return ratios
	 * @throws InsufficientUniqueLocationException
	 */
	public double[] calculatePreferentialReturn (List<ExtendedLocationTrace> traces, int numOfLocations) throws InsufficientUniqueLocationException{

		List<Long> uniqueLocationIds = new ArrayList<Long>();
		LocationTraceHelper traceHelper = new LocationTraceHelper();
		uniqueLocationIds = traceHelper.extractUniqueLocationIds(traces);

		if (uniqueLocationIds.size() < numOfLocations){
			throw new InsufficientUniqueLocationException("This trace list needs to have at least " + numOfLocations
					+ " unique locations");
		}

		HashMap<Long, Long> countMap = new HashMap<Long, Long>();

		// resetting all location visit counts to 0.
		for(Long ul: uniqueLocationIds){
			countMap.put(ul, 0l);
		}

		// adding counts for each location ids.
		for(ExtendedLocationTrace aTrace: traces){
			countMap.put(aTrace.getLocationId(), countMap.get(aTrace.getLocationId())+1);
		}

		// get all count values
		Collection<Long> values = countMap.values();

		// sort them
		List< Long > valuesList = new ArrayList< Long >( values );

		Comparator<Long> comparator = new Comparator<Long>() {
		    public int compare(Long l1, Long l2) {
		        return (int)(l2 - l1);
		    }
		};

		Collections.sort(valuesList, comparator);

		Long total = 0l;

		for(Long val: valuesList){
			total += val;
		}

		double[] ratios = new double[valuesList.size()];

		for(int i=0; i<valuesList.size(); i++){
			ratios[i] = valuesList.get(i).doubleValue()/total.doubleValue();
		}

		return ratios;
	}

	public double[] calculatePreferentialReturn (List<ExtendedLocationTrace> traces) throws InsufficientUniqueLocationException{
		return calculatePreferentialReturn(traces, defaultNumberOfLocationsToConsider);
	}

}


text:
function addListener() {
    if (_initAdd)return !0;
    _initAdd = !0, chrome.devtools.network.onRequestFinished.addListener(function (e) {
        var t = e.request.url;
        if (!Fiddler.checkUrl(t))return !0;
        e.getContent(function (e) {
            var n = {method: "requestContent", url: t, content: e};
            chrome.runtime.sendMessage(n, function (e) {
            })
        })
    })
}
var _initAdd = !1;
chrome.runtime.sendMessage({method: "token", value: "devtools"}, function (e) {
    e.result == "ok" && addListener()
})


text:
. assert.sh

gvp=../bin/gvp

## gvp init should create a .godeps/ directory.
assert_raises "$gvp in"
assert_raises "[ -d .godeps ]"
assert_raises "[ -h bin ]"
## Cleanup
rm -rf .godeps

## source gvp in should change the original GOPATH and associated Env variables
## as well as creating a .godeps directory
original_GOPATH=$GOPATH
original_PATH=$PATH

. "$gvp"

assert_raises "[ -d .godeps ]"
assert_raises "[ -h bin ]"
assert "echo $GOPATH" "$PWD/.godeps:$PWD${original_GOPATH:+:}$original_GOPATH"
assert "echo $GOBIN"  "$PWD/.godeps/bin"
assert "echo $PATH"   "$PWD/.godeps/bin:$original_PATH"

## Cleanup
rm -rf .godeps

assert_end examples


text:
/* Licensed 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.
 */

angular.module('flowableModeler').controller('FlowableFormKeyDisplayCtrl',
  ['$scope', '$modal', '$http', 'editorManager', function ($scope, $modal, $http, editorManager) {

    if ($scope.property && $scope.property.value) {
      $scope.form={'name':$scope.property.value};
    }

  }]);

angular.module('flowableModeler').controller('FlowableFormKeyCtrl',
  ['$scope', '$modal', '$http', function ($scope, $modal, $http) {

    // Config for the modal window
    var opts = {
      template: 'views/properties/form-key-popup.html',
      scope: $scope
    };

    // Open the dialog
    _internalCreateModal(opts, $modal, $scope);
  }]);

angular.module('flowableModeler').controller('FlowableFormKeyPopupCtrl',
  ['$rootScope', '$scope', '$http', '$location','$window', 'editorManager', function ($rootScope, $scope, $http, $location,$window, editorManager) {

    $scope.state = {'loadingForms': true, 'formError': false};

    $scope.popup = {'state': 'formReference'};

    $scope.foldersBreadCrumbs = [];

    // Close button handler
    $scope.close = function () {
      $scope.property.mode = 'read';
      $scope.$hide();
    };

    $scope.findProcessFormKey = function (selectedShape) {
      if (selectedShape.parent) {
        return $scope.findProcessFormKey(selectedShape.parent);
      }
      return selectedShape.properties._object["oryx-process_namespace"]
    }

    // Selecting/deselecting a subprocess
    $scope.selectForm = function (form, $event) {
      $event.stopPropagation();
      if ($scope.selectedForm && $scope.selectedForm.id && form.key == $scope.selectedForm.key) {
        $scope.selectedForm = null;
      } else {
        $scope.selectedForm = form;
      }
    };

    // Saving the selected value
    $scope.save = function () {
      if ($scope.selectedForm) {
        $scope.property.value = $scope.selectedForm.key;
      } else {
        $scope.property.value = null;
      }
      console.info($scope.property.value)
      $scope.updatePropertyInModel($scope.property);
      $scope.close();
    };

    // Open the selected value
    $scope.open = function () {
      if ($scope.selectedForm) {
        $window.open(FLOWABLE.CONFIG.formWatch + '?formDefinitionId='+$scope.processFormKey+'&formLayoutKey='+$scope.selectedForm.key+'&token='+editorManager.getToken());
      }
    };

    $scope.cancel = function () {
      $scope.close();
    };

    $scope.loadForms = function () {
      $scope.processFormKey = $scope.findProcessFormKey($scope.selectedShape);
      if ($scope.processFormKey == null) {
        $scope.state.loadingForms = false;
        return;
      }

      $http({
        method: 'GET',
        headers: {
          'Token': editorManager.getToken()
        },
        url: FLOWABLE.CONFIG.formContextRoot + '/form-definitions/' + $scope.processFormKey + '/metadata'
      }).success(
        function (response) {
          $scope.state.loadingForms = false;
          $scope.state.formError = false;
          $scope.forms = response.layouts;
          $scope.convertForm();
        })
        .error(
          function () {
            $scope.state.loadingForms = false;
            $scope.state.formError = true;
          });
    };

    $scope.convertForm = function () {
      if ($scope.property && $scope.property.value) {
        angular.forEach($scope.forms, function (item) {
          if (item.key == $scope.property.value) {
            $scope.selectedForm = item;
          }
        })
      }
    };

    $scope.loadForms();
  }]);


text:
set( NETLIB_FOUND "YES" )
set( NETLIB_INCLUDE_DIR ${VXL_ROOT_SOURCE_DIR}/v3p/netlib )
set( NETLIB_INSTALL_INCLUDE_DIR ${CMAKE_INSTALL_PREFIX}/include/vxl/v3p/netlib )
set( NETLIB_LIBRARIES ${VXL_LIB_PREFIX}v3p_netlib )


text:
from __future__ import absolute_import, unicode_literals, division
import sys
import json
import armet
from armet import resources, attributes, exceptions

# Request the generic models module inserted by the test runner.
models = sys.modules['tests.connectors.models']

__all__ = [
    'SimpleResource',
    'SimpleTrailingResource',
    'PollResource',
    'StreamingResource',
    'AsyncResource',
    'AsyncStreamResource',
    'lightweight',
    'lightweight_streaming',
    'lightweight_async',
    'LeftResource',
    'RightResource',
    'echo',
    'cookie',
    'DirectResource',
    'ModelDirectResource',
    'IndirectResource',
    'ModelIndirectResource',
    'TwiceIndirectResource',
    'ModelTwiceIndirectResource',
    'ThriceIndirectResource',
    'ModelThriceIndirectResource',
    'MixinResource',
    'PollExcludeResource',
    'PollUnreadResource',
    'PollUnwriteResource',
    'PollNoNullResource',
    'PollRequiredResource',
    'PollValidResource',
    'PollNamedResource',
    'DirectConnectorResource',
    'IndirectConnectorResource',
    'TwiceIndirectConnectorResource',
    'ThriceIndirectConnectorResource',
    'DirectModelConnectorResource',
    'IndirectModelConnectorResource',
    'TwiceIndirectModelConnectorResource',
    'ThriceIndirectModelConnectorResource',
    'DirectModelConnectorMixinResource',
    'IndirectModelConnectorMixinResource',
    'TwiceIndirectModelConnectorMixinResource',
    'ThriceIndirectModelConnectorMixinResource',
]

class SimpleResource(resources.Resource):

    def get(self, request, response):
        # Do nothing and return nothing.
        pass

class SimpleTrailingResource(resources.Resource):

    class Meta:
        trailing_slash = False

    def get(self, request, response):
        # Do nothing and return nothing.
        pass

class StreamingResource(resources.Resource):

    def get(self, request, response):
        response.status = 412
        response['Content-Type'] = 'text/plain'

        yield 'this\n'

        response.write('where\n')
        response.flush()
        response.write('whence\n')

        yield
        yield 'that\n'

        response.write('why\n')

        yield 'and the other'

def spawn(connectors, function):
    import gevent
    gevent.spawn(function)

class AsyncResource(resources.Resource):

    class Meta:
        asynchronous = True

    def get(self, request, response):

        def writer():
            response.status = 412
            response['Content-Type'] = 'text/plain'
            response.write('Hello')
            response.close()

        spawn(self.meta.connectors, writer)

class AsyncStreamResource(resources.Resource):

    class Meta:
        asynchronous = True

    def get(self, request, response):

        def streamer():
            response.status = 412
            response['Content-Type'] = 'text/plain'
            response.write('this\n')
            response.flush()

            response.write('where\n')
            response.flush()

            response.write('whence\n')
            response.write('that\n')
            response.flush()

            response.write('why\n')
            response.write('and the other')
            response.close()

        spawn(self.meta.connectors, streamer)

@armet.resource(methods='GET')
def lightweight(request, response):
    response.status = 412
    response['Content-Type'] = 'text/plain'
    response.write('Hello')

@armet.resource(methods='POST')
def lightweight(request, response):
    response.status = 414
    response['Content-Type'] = 'text/plain'
    response.write('Hello POST')

@armet.resource(methods='GET')
def lightweight_streaming(request, response):
    response.status = 412
    response['Content-Type'] = 'text/plain'

    yield 'this\n'

    response.write('where\n')
    response.flush()
    response.write('whence\n')

    yield
    yield 'that\n'

    response.write('why\n')

    yield 'and the other'

@armet.asynchronous
@armet.resource(methods='GET')
def lightweight_async(request, response):
    def writer():
        response.status = 412
        response['Content-Type'] = 'text/plain'
        response.write('Hello')
        response.close()

    spawn(lightweight_async.meta.connectors, writer)

class PollResource(resources.ModelResource):

    class Meta:
        model = models.Poll

        slug = 'id'

    id = attributes.IntegerAttribute('id')

    question = attributes.TextAttribute('question')

    available = attributes.BooleanAttribute('available')

class LeftResource(resources.Resource):

    class Meta:
        http_allowed_methods = ('HEAD', 'GET', 'OPTIONS',)
        http_allowed_origins = ('http://127.0.0.1:80',)
        http_allowed_headers = ('Content-Type', 'Content-MD5', 'Accept',)

    def get(self):
        # Do nothing.
        pass

class RightResource(resources.Resource):

    class Meta:
        http_allowed_methods = ('HEAD', 'GET', 'DELETE', 'OPTIONS',)
        http_allowed_origins = ('*',)
        http_allowed_headers = ('Content-Type', 'Content-MD5', 'Accept')

    def get(self):
        # Do nothing.
        pass

@armet.resource(methods='POST')
def echo(request, response):
    # Read in the given data in the given format.
    data = request.read(deserialize=True)

    # Write out the parsed data in the requested format.
    response.write(data, serialize=True)

@armet.resource(methods='GET')
def cookie(request, response):
    response['Content-Type'] = 'text/plain'
    response.write(request.cookies['blue'].value)

class DirectResource(resources.Resource):

    def route(self, request, response):
        return super(DirectResource, self).route(request, response)

    def get(self, request, response):
        response.write(b'42')

class ModelDirectResource(resources.ModelResource):

    class Meta:
        model = models.Poll

    id = attributes.IntegerAttribute('id')

    question = attributes.TextAttribute('question')

    def route(self, request, response):
        return super(ModelDirectResource, self).route(request, response)

class IndirectResource(DirectResource):

    def route(self, request, response):
        return super(IndirectResource, self).route(request, response)

    def get(self, request, response):
        response.write(b'84')

class ModelIndirectResource(ModelDirectResource):

    class Meta:
        model = models.Poll

    def read(self):
        return super(ModelIndirectResource, self).read()

class TwiceIndirectResource(IndirectResource):

    def route(self, request, response):
        return super(TwiceIndirectResource, self).route(request, response)

    def get(self, request, response):
        response.write(b'84')

class ModelTwiceIndirectResource(ModelIndirectResource):

    class Meta:
        model = models.Poll

    def read(self):
        return super(ModelTwiceIndirectResource, self).read()

class ThriceIndirectResource(IndirectResource):

    def route(self, request, response):
        return super(ThriceIndirectResource, self).route(request, response)

    def get(self, request, response):
        response.write(b'84')

class ModelThriceIndirectResource(ModelIndirectResource):

    class Meta:
        model = models.Poll

    def read(self):
        return super(ModelThriceIndirectResource, self).read()

class ExtraStuff(object):

    def dispatch(self, *args):
        self.content = b'Hello'
        return super(ExtraStuff, self).dispatch(*args)

class MixinResource(ExtraStuff, IndirectResource):

    content = b'World'

    def route(self, request, response):
        return super(MixinResource, self).route(request, response)

    def get(self, request, response):
        response.write(self.content)

class PollExcludeResource(PollResource):

    question = attributes.TextAttribute('question', include=False)

class PollUnreadResource(PollResource):

    question = attributes.TextAttribute('question', read=False)

class PollUnwriteResource(PollResource):

    question = attributes.TextAttribute('question', write=False)

class PollNoNullResource(PollResource):

    question = attributes.TextAttribute('question', null=False)

class PollRequiredResource(PollResource):

    question = attributes.TextAttribute('question', required=True)

class PollNamedResource(PollResource):

    question = attributes.TextAttribute('question', name='superQuestion')

class PollValidResource(PollResource):

    votes = attributes.IntegerAttribute('votes')

    def clean_votes(self, value):
        assert value > 0, 'Must be greater than 0.'
        assert value < 51, 'Must be less than 51.'
        return value

    def clean_question(self, value):
        errors = []

        if len(value) <= 15:
            errors.append('Must be more than 15 characters.')

        if value.find('?') == -1:
            errors.append('Must have at least one question mark.')

        if errors:
            raise exceptions.ValidationError(*errors)

        return value

class DirectConnectorResource(resources.Resource):

    @classmethod
    def view(cls, *args, **kwargs):
        cls.status = 205
        return super(DirectConnectorResource, cls).view(*args, **kwargs)

    def get(self, request, response):
        response.status = self.status
        response.write(b'Hello World\n')

class IndirectConnectorResource(DirectConnectorResource):
    pass

class TwiceIndirectConnectorResource(IndirectConnectorResource):
    pass

class ThriceIndirectConnectorResource(TwiceIndirectConnectorResource):
    pass

class DirectModelConnectorResource(resources.ModelResource):

    class Meta:
        model = models.Poll

    id = attributes.IntegerAttribute('id')

    def route(self, request, response):
        response.status = 205
        return super(DirectModelConnectorResource, self).route(
            request, response)

    def get(self, request, response):
        response.write(json.dumps(self.read()).encode('utf8'))

    def read(self):
        return ['Hello', 'World']

class IndirectModelConnectorResource(DirectModelConnectorResource):
    pass

class TwiceIndirectModelConnectorResource(IndirectModelConnectorResource):
    pass

class ThriceIndirectModelConnectorResource(
        TwiceIndirectModelConnectorResource):
    pass

class DirectModelConnectorMixin(object):

    def destroy(self):
        self.response.status = 402
        return None

class DirectModelConnectorMixinResource(
        DirectModelConnectorMixin, resources.ModelResource):

    class Meta:
        model = models.Poll

    id = attributes.IntegerAttribute('id')

    def delete(self, request, response):
        self.response.status = 405
        self.destroy()

class IndirectModelConnectorMixinResource(DirectModelConnectorMixinResource):
    pass

class TwiceIndirectModelConnectorMixinResource(
        IndirectModelConnectorMixinResource):
    pass

class ThriceIndirectModelConnectorMixinResource(
        TwiceIndirectModelConnectorMixinResource):
    pass


text:
/*
 * Licensed 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.
 */
package com.facebook.presto.execution.buffer;

import com.facebook.presto.execution.Lifespan;
import com.facebook.presto.execution.buffer.SerializedPageReference.PagesReleasedListener;

import javax.annotation.Nullable;

import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;

import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

final class LifespanSerializedPageTracker
        implements PagesReleasedListener
{
    private final OutputBufferMemoryManager memoryManager;
    @Nullable
    private final PagesReleasedListener childListener;
    private final ConcurrentMap<Lifespan, AtomicLong> outstandingPageCountPerLifespan = new ConcurrentHashMap<>();
    private final Set<Lifespan> noMorePagesForLifespan = ConcurrentHashMap.newKeySet();
    private volatile Consumer<Lifespan> lifespanCompletionCallback;

    public LifespanSerializedPageTracker(OutputBufferMemoryManager memoryManager)
    {
        this(memoryManager, Optional.empty());
    }

    public LifespanSerializedPageTracker(OutputBufferMemoryManager memoryManager, Optional<PagesReleasedListener> childListener)
    {
        this.memoryManager = requireNonNull(memoryManager, "memoryManager is null");
        this.childListener = requireNonNull(childListener, "childListener is null").orElse(null);
    }

    public boolean isLifespanCompletionCallbackRegistered()
    {
        return lifespanCompletionCallback != null;
    }

    public void registerLifespanCompletionCallback(Consumer<Lifespan> callback)
    {
        checkState(lifespanCompletionCallback == null, "lifespanCompletionCallback is already set");
        this.lifespanCompletionCallback = requireNonNull(callback, "callback is null");
    }

    public void incrementLifespanPageCount(Lifespan lifespan, int pagesAdded)
    {
        // JDK-8 acquires the write lock unconditionally in computeIfAbsent
        // TODO: Remove this extra get call once Presto no longer supports JDK-8
        AtomicLong counter = outstandingPageCountPerLifespan.get(lifespan);
        if (counter == null) {
            counter = outstandingPageCountPerLifespan.computeIfAbsent(lifespan, ignore -> new AtomicLong());
        }
        counter.addAndGet(pagesAdded);
    }

    public void setNoMorePagesForLifespan(Lifespan lifespan)
    {
        requireNonNull(lifespan, "lifespan is null");
        noMorePagesForLifespan.add(lifespan);
    }

    public boolean isNoMorePagesForLifespan(Lifespan lifespan)
    {
        return noMorePagesForLifespan.contains(lifespan);
    }

    public boolean isFinishedForLifespan(Lifespan lifespan)
    {
        if (!noMorePagesForLifespan.contains(lifespan)) {
            return false;
        }

        AtomicLong outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan);
        return outstandingPageCount == null || outstandingPageCount.get() == 0;
    }

    @Override
    public void onPagesReleased(Lifespan lifespan, int releasedPageCount, long releasedSizeInBytes)
    {
        long outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan).addAndGet(-releasedPageCount);
        if (outstandingPageCount == 0 && noMorePagesForLifespan.contains(lifespan)) {
            Consumer<Lifespan> lifespanCompletionCallback = this.lifespanCompletionCallback;
            checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback is not null");
            lifespanCompletionCallback.accept(lifespan);
        }
        memoryManager.updateMemoryUsage(-releasedSizeInBytes);
        if (childListener != null) {
            childListener.onPagesReleased(lifespan, releasedPageCount, releasedSizeInBytes);
        }
    }
}


text:
''' <summary>
''' Converts an int to the appropriate label for the sort. This is used
''' in the sort history viewer.
''' </summary>
''' <remarks></remarks>

Public Class Int2SortLabel
    Implements IValueConverter

    Private labels As List(Of String) = New List(Of String)
    Public Sub New()
        labels.Add("Bubble Sort")
        labels.Add("Heap Sort")
        labels.Add("Quick Sort")
        labels.Add("Insert Sort")
    End Sub

    Public Function Convert(value As Object, targetType As Type, parameter As Object, language As String) As Object Implements IValueConverter.Convert
        Return labels(value)
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, language As String) As Object Implements IValueConverter.ConvertBack
        Return labels.IndexOf(value)
    End Function
End Class


text:
package eu.leads.processor.math;

/**
 * Created by vagvaz on 9/24/14.
 */
public enum FilterOpType {
  // Unary expression
  NOT,

  // Binary expression
  AND,
  OR,
  EQUAL,
  IS_NULL,
  NOT_EQUAL,
  LTH,
  LEQ,
  GTH,
  GEQ,
  //   PLUS(BinaryEval.class, "+"),
  //   MINUS(BinaryEval.class, "-"),
  //   MODULAR(BinaryEval.class, "%"),
  //   MULTIPLY(BinaryEval.class, "*"),
  //   DIVIDE(BinaryEval.class, "/"),

  // Binary Bitwise expressions
  //   BIT_AND(BinaryEval.class, "&"),
  //   BIT_OR(BinaryEval.class, "|"),
  //   BIT_XOR(BinaryEval.class, "|"),

  // Function
  //   WINDOW_FUNCTION(WindowFunctionEval.class),
  AGG_FUNCTION,
  FUNCTION,

  // String operator or pattern matching predicates
  LIKE,
  //   SIMILAR_TO,
  //   REGEX(RegexPredicateEval.class),
  //   CONCATENATE(BinaryEval.class, "||"),

  // Other predicates
  //   BETWEEN(BetweenPredicateEval.class),
  //   CASE(CaseWhenEval.class),
  //   IF_THEN(CaseWhenEval.IfThenEval.class),
  IN,

  // Value or Reference
  SIGNED,
  CAST,
  ROW_CONSTANT,
  FIELD,
  CONST;
}


text:
package com.voxelwind.server.game.level.block.behaviors;

import com.google.common.collect.ImmutableList;
import com.voxelwind.api.game.item.ItemStack;
import com.voxelwind.api.game.item.ItemType;
import com.voxelwind.api.game.item.ItemTypes;
import com.voxelwind.api.game.level.block.Block;
import com.voxelwind.api.game.level.block.data.Crops;
import com.voxelwind.api.server.Player;
import com.voxelwind.api.server.Server;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Random;

public class PumpkinMelonStemBlockBehavior extends SimpleBlockBehavior {
    public static final PumpkinMelonStemBlockBehavior PUMPKIN = new PumpkinMelonStemBlockBehavior(ItemTypes.PUMPKIN_SEEDS);
    public static final PumpkinMelonStemBlockBehavior MELON = new PumpkinMelonStemBlockBehavior(ItemTypes.MELON_SEEDS);

    private static final Random RANDOM = new Random();
    private final ItemType type;

    private PumpkinMelonStemBlockBehavior(ItemType type) {
        this.type = type;
    }

    @Override
    public Collection<ItemStack> getDrops(Server server, Player player, Block block, @Nullable ItemStack withItem) {
        Crops crop = (Crops) block.getBlockState().getBlockData();
        if (crop.isFullyGrown()) {
            int amount = RANDOM.nextInt(4);
            if (amount == 0) return ImmutableList.of();
            return ImmutableList.of(server.createItemStackBuilder()
                    .itemType(type)
                    .amount(amount)
                    .build());
        } else {
            return ImmutableList.of(server.createItemStackBuilder()
                    .itemType(type)
                    .amount(1)
                    .build());
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <solid android:color="#FFFFFF" />
            <stroke
                android:width="1dp"
                android:color="#ffa8abad" />
        </shape>
    </item>
    <item
        android:right="1dp"
        android:bottom="1dp"
        android:left="1dp"
        android:top="1dp">
        <shape>
            <padding android:left="12dp"
                android:top="12dp"
                android:right="12dp"
                android:bottom="12dp" />
            <solid android:color="#FFFFFF" />
            <stroke
                android:width="1dp"
                android:color="#ffffffff" />
        </shape>
    </item>
</layer-list>


text:
'use strict';

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

class Square extends Polygon {
  constructor(sideLength) {
    super(sideLength, sideLength);
  }
  get area() {
    return this.height * this.width;
  }
  set sideLength(newLength) {
    this.height = newLength;
    this.width = newLength;
  }
}

var square = new Square(2);
console.log(square);
console.log(square.getArea());


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
from hapi.release import status_pb2 as hapi_dot_release_dot_status__pb2

DESCRIPTOR = _descriptor.FileDescriptor(
  name='hapi/release/info.proto',
  package='hapi.release',
  syntax='proto3',
  serialized_pb=_b('\n\x17hapi/release/info.proto\x12\x0chapi.release\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x19hapi/release/status.proto\"\xd5\x01\n\x04Info\x12$\n\x06status\x18\x01 \x01(\x0b\x32\x14.hapi.release.Status\x12\x32\n\x0e\x66irst_deployed\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x31\n\rlast_deployed\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12+\n\x07\x64\x65leted\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x44\x65scription\x18\x05 \x01(\tB\tZ\x07releaseb\x06proto3')
  ,
  dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,hapi_dot_release_dot_status__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_INFO = _descriptor.Descriptor(
  name='Info',
  full_name='hapi.release.Info',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='status', full_name='hapi.release.Info.status', index=0,
      number=1, type=11, cpp_type=10, label=1,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='first_deployed', full_name='hapi.release.Info.first_deployed', index=1,
      number=2, type=11, cpp_type=10, label=1,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='last_deployed', full_name='hapi.release.Info.last_deployed', index=2,
      number=3, type=11, cpp_type=10, label=1,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='deleted', full_name='hapi.release.Info.deleted', index=3,
      number=4, type=11, cpp_type=10, label=1,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='Description', full_name='hapi.release.Info.Description', index=4,
      number=5, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=102,
  serialized_end=315,
)

_INFO.fields_by_name['status'].message_type = hapi_dot_release_dot_status__pb2._STATUS
_INFO.fields_by_name['first_deployed'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_INFO.fields_by_name['last_deployed'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_INFO.fields_by_name['deleted'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
DESCRIPTOR.message_types_by_name['Info'] = _INFO

Info = _reflection.GeneratedProtocolMessageType('Info', (_message.Message,), dict(
  DESCRIPTOR = _INFO,
  __module__ = 'hapi.release.info_pb2'
  # @@protoc_insertion_point(class_scope:hapi.release.Info)
  ))
_sym_db.RegisterMessage(Info)

DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('Z\007release'))
try:
  # THESE ELEMENTS WILL BE DEPRECATED.
  # Please use the generated *_pb2_grpc.py files instead.
  import grpc
  from grpc.framework.common import cardinality
  from grpc.framework.interfaces.face import utilities as face_utilities
  from grpc.beta import implementations as beta_implementations
  from grpc.beta import interfaces as beta_interfaces
except ImportError:
  pass
# @@protoc_insertion_point(module_scope)


text:
Yet another post

[meta:author]: <> (Jonas Colmsjo)
[meta:title]: <> (Cloud-solutions.md)
[meta:date]: <> (2012-01-01)
[meta:nested:key]: <> (Metadata value)

##!!truncate

[[Main_Page]]

== Cloud solutions ==

* [[Below OS]] - hardware, virtualization etc.
* [[Clusters]]
* [[Google App Engine]]
* [[KVM]]
* [[Xen]]
* [[libvirt]] - abstraction on top of several virtualization technologies
* [[Virtualbox]]
* [[Stacklet]] - pre-built images

== Amazon  and Rackspace ==

* [[AWS Tools]]
* [[Rackspace]]

== Private clouds ==

* [[Private clouds]]

* [[OpenQRM]]
* [[OpenNebula]]
* [[Eucalyptus]]
* [[cloud.com]]


text:
import { Point } from '../../point'

export interface IFractalCalculator {

    calculatepoint(posx: number, posy: number, sspix: number, sspix2: number): number

}