text:
platform=avr
extra_args=
mcu=
flash_target=

print_help_and_exit()
{
    echo "Usage: ./build_and_run.sh [options] example [add_build_opts]"
    echo "options:"
    echo "        -p      platform to compile for: avr, linux, esp32, stm32"
    echo "        -m      mcu to compiler for: atmega328p, attiny85, etc.."
    echo "        -f      flash controller after build or run executable for Linux"
    echo "        -e      start OLED emulation mode with SDL (Linux only)"
    echo "                OLED emulation allows to run simple demo without OLED hardware"
    echo "                OLED emulation mode requires installed libsdl2-dev package"
    echo "add_build_opts: (additional options)"
    echo "        FREQUENCY=<num>  frequency in Hz, passed as -DF_CPU=<num> to gcc/g++"
    echo "        ADAFRUIT=y       add Adafruit GFX support to ssd1306 library"
    echo ""
    echo "# example: run demo on linux with emulator"
    echo "    ./build_and_run.sh -p linux -e -f demos/ssd1306_demo"
    echo "# example: run demo on linux with real ssd1306 oled display"
    echo "    ./build_and_run.sh -p linux -f demos/ssd1306_demo"
    echo "# example: build demo and flash for AVR controller"
    echo "    ./build_and_run.sh -p avr -m attiny85 -f demos/ssd1306_demo"
    echo "# example: build demo for ESP32 controller"
    echo "    ./build_and_run.sh -p esp32 demos/ssd1306_demo"
    exit 1
}

while getopts "fep:m:" opt; do
  # echo $opt, $OPTARG
  case $opt in
    p) platform=$OPTARG;;
    m) mcu=$OPTARG;;
    f) flash_target=flash;;
    e) extra_args="$extra_args SDL_EMULATION=y";;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      print_help_and_exit
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      print_help_and_exit
      ;;
  esac
done

shift $((OPTIND-1))
if [ $# = 0 ]; then
    print_help_and_exit
fi

project=$1
shift

if [ "$mcu" != "" ]; then
    extra_args="MCU=$mcu $extra_args"
fi

make -C ../examples -f Makefile.${platform} PROJECT=${project} ${extra_args} ${flash_target} $@


text:
package com.puresoltechnologies.kickstart;

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

import org.junit.Test;

import com.puresoltechnologies.kickstart.Directories;
import com.puresoltechnologies.kickstart.KickStart;
import com.puresoltechnologies.kickstart.KickStartProperties;

import junit.framework.TestCase;

public class KickStartPropertiesTest extends TestCase {

	@Test
	public void testSingleton() {
		try {
			KickStartProperties instance1 = KickStartProperties.getInstance();
			assertNotNull(instance1);
			KickStartProperties instance2 = KickStartProperties.getInstance();
			assertNotNull(instance2);
			assertSame(instance1, instance2);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			fail("No exception was expected.");
		} catch (IOException e) {
			e.printStackTrace();
			fail("No exception was expected.");
		}
	}

	@Test
	public void testContent() {
		try {
			KickStartProperties instance = KickStartProperties.getInstance();
			assertNotNull(instance);
			assertTrue(instance.isRecursiveJarSearch());
			List<File> jarDirectories = instance.getJarDirectories();
			assertEquals(1, jarDirectories.size());
			assertEquals(
					new File(Directories.getInstallationDirectory(
							KickStart.class, true), "../lib"),
					jarDirectories.get(0));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			fail("No exception was expected.");
		} catch (IOException e) {
			e.printStackTrace();
			fail("No exception was expected.");
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Tests\Integration\Note;

/**
 * Por ahora extendemos AbstractUserIntegration,
 * porque no tenemos la necesidad en este momento de
 * crear otra clase especifica para Items y sus pruebas.
 * Considerando cambiar nombre de la clase de
 * AbstractUserIntegration -> AbstractGeneralIntegration o algo similar.
 */

use PCI\Models\Note;
use PCI\Models\User;
use Tests\Integration\User\AbstractUserIntegration;

/**
 * Class NoteRepositoryTest
 *
 * @package Tests\Integration\Note
 * @author  Alejandro Granadillo <slayerfat@gmail.com>
 * @link    https://github.com/slayerfat/sistemaPCI Repositorio en linea.
 */
class NoteRepositoryTest extends AbstractUserIntegration
{

    /**
     * @var Note[]|\Illuminate\Support\Collection
     */
    public $notes;

    /**
     * @var \PCI\Models\User
     */
    public $randomUser;

    public function testIndexReturnsCorrectAmountIfAdmin()
    {
        foreach (range(1, 5) as $index) {
            $this->notes[] = factory(Note::class)
                ->create(['comments' => "mocked_[$index]"]);
        }

        foreach ($this->notes as $note) {
            $this->actingAs($this->user)
                ->visit(route('notes.index'))
                ->seeLink($note->user->name, route('users.show', $note->user->name, $note->user->name));
        }
    }

    public function testIndexReturnsCeroNotesIfNotAdmin()
    {
        foreach (range(1, 5) as $index) {
            $this->notes[] = factory(Note::class)
                ->create(['comments' => "mocked_[$index]"]);
        }

        foreach ($this->notes as $note) {
            $this->actingAs($this->randomUser)
                ->visit(route('notes.index'))
                ->dontSee($note->user->email);
        }
    }

    /**
     * @return \PCI\Models\User
     */
    protected function getUser()
    {
        return $this->getGenericAdmin();
    }

    /**
     * @return void
     */
    protected function persistData()
    {
        $this->randomUser = factory(User::class, 'user')->create();
    }
}


text:
import pandas_gbq

# Select a few KB worth of data, to time downloading small result sets.
df = pandas_gbq.read_gbq(
    "SELECT * FROM `bigquery-public-data.utility_us.country_code_iso`",
    dialect="standard",
)


text:
package com.order.market.service;

import java.util.List;
import java.util.Map;

import com.order.market.bean.OrderBean;

import scala.util.parsing.combinator.testing.Str;

/**
 * 2017-8-31
 * @author zx.meng
 * 订单服务接口
 */
public interface OrderService {
	int save(OrderBean bean);
	List<OrderBean> selectall(Map<String,Object> param);
	List<OrderBean> selectbysn(String contractsn);
	int selectcount();
	OrderBean selectbyid(int id);
	/**
	 * 订单详情
	 * @param id
	 * @return
	 */
	Map<String, Object> getOrderDetails(int id);

	int update(OrderBean bean);

	int delete(String ordersn);
}


text:
package au.com.williamhill.flywheel.topic;

import static org.junit.Assert.*;

import java.io.*;
import java.net.*;

import org.junit.*;

import com.obsidiandynamics.assertion.*;

public final class TopicLibraryTest {
  @Test
  public void testConformance() throws Exception {
    Assertions.assertUtilityClassWellDefined(TopicLibrary.class);
  }

  @Test
  public void testFile() throws FileNotFoundException, IOException, URISyntaxException {
    assertSpec(TopicLibrary.load("file://src/test/resources/specs/tiny-all.yaml"));
  }

  @Test
  public void testClasspath() throws FileNotFoundException, IOException, URISyntaxException {
    assertSpec(TopicLibrary.load("cp://specs/tiny-all.yaml"));
    assertSpec(TopicLibrary.load("classpath://specs/tiny-all.yaml"));
  }

  private static void assertSpec(TopicSpec spec) {
    assertEquals(1, spec.getExactInterests().size());
    assertEquals(1, spec.getSingleLevelWildcardInterests().size());
    assertEquals(1, spec.getMultiLevelWildcardInterests().size());
  }
}


text:
void hospitalRibbon::update(float _dnSpeed){

    for(unsigned int i = 0; i < mPoints.size(); i++){
        mPoints[i].z -= _dnSpeed;
        //sumOfAllPoints += mPoints[i];
    }

}

//--------------------------------------------------------------
void hospitalRibbon::drawCamText(){
    if(mPoints.size()>0){
        ofDrawBitmapString(mCam, mPoints[mPoints.size()-1]);
    }
}

//--------------------------------------------------------------
void hospitalRibbon::drawCircles(ofColor _color, float _maxThickness
                                 ,int _nbCircles, float _circlesRadius
                                 ,float _radiusDephaser, float _freqDivider){

    if(mPoints.size()>0){

        ofPoint center = mPoints[mPoints.size()-1];

        // One big point to hide extremity
        ofPushStyle();
        ofSetColor(_color);
        ofFill();

        ofCircle(center, 1.25 * _maxThickness);
        ofPopStyle();

        // Concentric circles
        ofPushStyle();
        ofSetColor(_color);
        ofNoFill();

        for(int idxCircle=0; idxCircle<_nbCircles; idxCircle++){

            float radiusRatio = (float)idxCircle / (float)_nbCircles;
            float myOwnDivider = radiusRatio*_freqDivider;
            float radiusTimeRatio = fmod(mTimeStampf + radiusRatio*_radiusDephaser, myOwnDivider) / myOwnDivider;
            float lineWidth = 5 * fmod(mTimeStampf + radiusRatio*_radiusDephaser, myOwnDivider) / myOwnDivider;

            ofSetLineWidth(lineWidth);

            ofCircle(center, _circlesRadius * radiusTimeRatio);

        }
        ofPopStyle();
    }

}

//--------------------------------------------------------------
void hospitalRibbon::drawShape(ofColor _color
                               , float _minThickness, float _maxThickness
                               , int globalPointsDiv
                               , float _ribbonEffectLevel, float _ribbonIdxPointsDivider, float _ribbonTimeDivider){

    ofPushStyle();

    ofSetColor(_color);
    ofSetLineWidth(5);
    ofNoFill();

    //do the same thing from the first example...
    ofBeginShape();

    for(unsigned int i = 1; i < mPoints.size(); i++){

        if(i==1 || i==(mPoints.size()-1) || (i%globalPointsDiv == 1)){

        //find this point and the next point
        ofPoint thisPoint = mPoints[i-1];
        ofPoint nextPoint = mPoints[i];

        //get the direction from one to the next.
        //the ribbon should fan out from this direction
        ofPoint direction = (nextPoint - thisPoint);

        //get the distance from one point to the next
        float distance = direction.length();
        ofLogVerbose() << "Distance = " << ofToString(distance);

        //get the normalized direction. normalized vectors always have a length of one
        //and are really useful for representing directions as opposed to something with length
        ofPoint unitDirection = direction.normalized();

        //find both directions to the left and to the right
        ofPoint toTheLeft = unitDirection.getRotated(-90, ofVec3f(0,0,1));
        ofPoint toTheRight = unitDirection.getRotated(90, ofVec3f(0,0,1));

        //use the map function to determine the distance.
        //the longer the distance, the narrower the line.
        //this makes it look a bit like brush strokes

        // thickness depend on distance between point -> brush effect
        //float thickness = ofMap(distance, 0, 60, 20, 2, true);

        // thickness depend on distance between point -> brush effect
        float pointRatio = (float)i / (float)mPoints.size();
        float pointRatioInv = 1 - pointRatio;
        float thickness = ofMap(pointRatio*pointRatio, 0, 1, _minThickness, _maxThickness, true);

        //calculate the points to the left and to the right
        //by extending the current point in the direction of left/right by the length
        float ribbonPhase = (float)i / _ribbonIdxPointsDivider + ofGetElapsedTimef() / _ribbonTimeDivider;
        float ribbonEffect = pointRatioInv*_ribbonEffectLevel*sin(ribbonPhase*TWO_PI);

        ofPoint leftPoint = thisPoint+toTheLeft*thickness+toTheLeft*ribbonEffect;
        ofPoint rightPoint = thisPoint+toTheRight*thickness+toTheLeft*ribbonEffect;

        //add these mPoints to the triangle strip
            if (i==(mPoints.size()-1)) {
                ofVertex(leftPoint);
            }else{
                ofCurveVertex(leftPoint);
            }
//        ofNextContour();
        //ofCurveVertex(rightPoint);
        }
    }

    //end the shape
    ofEndShape();

    ofPopStyle();

}

//--------------------------------------------------------------
void hospitalRibbon::drawMesh(ofColor _color
                              , float _minThickness, float _maxThickness
                              , int globalPointsDiv
                              , float _ribbonEffectLevel, float _ribbonIdxPointsDivider, float _ribbonTimeDivider){

    ofPushStyle();

    ofSetColor(_color);

    //do the same thing from the first example...
    ofMesh mesh;
    mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);

    for(unsigned int i = 1; i < mPoints.size(); i++){
        if(i==1 || i==(mPoints.size()-1) || (i%globalPointsDiv == 1)){
        //find this point and the next point
        ofPoint thisPoint = mPoints[i-1];
        ofPoint nextPoint = mPoints[i];

        //get the direction from one to the next.
        //the ribbon should fan out from this direction
        ofPoint direction = (nextPoint - thisPoint);

        //get the distance from one point to the next
        float distance = direction.length();

        //get the normalized direction. normalized vectors always have a length of one
        //and are really useful for representing directions as opposed to something with length
        ofPoint unitDirection = direction.normalized();

        //find both directions to the left and to the right
        ofPoint toTheLeft = unitDirection.getRotated(-90, ofVec3f(0,0,1));
        ofPoint toTheRight = unitDirection.getRotated(90, ofVec3f(0,0,1));

        //use the map function to determine the distance.
        //the longer the distance, the narrower the line.
        //this makes it look a bit like brush strokes

        // thickness depend on distance between point -> brush effect
        //float thickness = ofMap(distance, 0, 60, 20, 2, true);

        // thickness depend on distance between point -> brush effect
        float pointRatio = (float)i / (float)mPoints.size();
        float pointRatioInv = 1 - pointRatio;
        float thickness = ofMap(pointRatio*pointRatio, 0, 1, _minThickness, _maxThickness, true);

        //calculate the mPoints to the left and to the right
        //by extending the current point in the direction of left/right by the length
        float ribbonPhase = (float)i / _ribbonIdxPointsDivider + ofGetElapsedTimef() / _ribbonTimeDivider;
        float ribbonEffect = pointRatioInv*_ribbonEffectLevel*sin(ribbonPhase*TWO_PI);

        ofPoint leftPoint = thisPoint+toTheLeft*thickness+toTheLeft*ribbonEffect;
        ofPoint rightPoint = thisPoint+toTheRight*thickness+toTheLeft*ribbonEffect;

        //add these mPoints to the triangle strip
        mesh.addVertex(ofPoint(leftPoint.x, leftPoint.y, leftPoint.z));
        mesh.addVertex(ofPoint(rightPoint.x, rightPoint.y, rightPoint.z));
        }
    }

    //end the shape
    mesh.draw();
    ofPopStyle();

}

//--------------------------------------------------------------
void hospitalRibbon::addPoint(ofPoint _p, string _cam, string _blobId){

    mPoints.push_back(_p);
    mTimeStampf = ofGetElapsedTimef();
    mCam = _cam;
    mBlobId = _blobId;

}

//--------------------------------------------------------------
bool hospitalRibbon::IsThereAPointNearToMe(ofPoint _p, float _matchingDistance){

    vector<ofPoint>::iterator onePoint;
    for (onePoint = mPoints.begin(); onePoint != mPoints.end(); onePoint++) {

        ofPoint entryPoint = _p;
        _p.z = 0;
        ofPoint testedPoint = *onePoint;
        testedPoint.z = 0;

        if (entryPoint.distance(testedPoint) <= _matchingDistance) {
            // Some point is near enough
            ofLogVerbose() << "Match Distance";
            return true;
        }
    }
    return false;

}


text:
class Vehicle {
    constructor() {
        this.passenger = [];
        console.log("Vehicle created");
    }

    addPassenger(p) {
        this.passenger.push(p);
    }
}

class Car extends Vehicle {
    constructor() {
        super();
        console.log("Car created");
    }

    deployAirbags() {
        console.log("BWOOSH!");
    }
}

// const v = new Vehicle()
// v.addPassenger("Frank");
// v.addPassenger("Judy");
// console.log(v.passenger);

// const c = new Car()
// c.addPassenger("Alice");
// c.addPassenger("Cameron");
// console.log(c.passenger);

// v.deployAirbags();
// c.deployAirbags();

// class Super {
//     constructor() {
//         this.name = "Super";
//         this.isSuper = true;
//     }
// }

// Super.prototype.sneaky = "not recommended";

// class Sub extends Super {
//     constructor() {
//         super();

//         this.name = "Sub";
//         this.isSub = true;
//     }

//     // toString() {
//     //     return `${this.name}`;
//     // }
// }

// const obj = new Sub();
// for(let p in obj) {
//     console.log(`${p} : ${obj[p]}` + (obj.hasOwnProperty(p) ? '' : '(inherited)'));
// }

// console.log(obj);

class InsurancePolicy{}
function makeInsurable(o) {
    o.addInsurancePolicy = function(p) {
        this.insurancePolicy = p;
    }

    o.getInsurancePolicy = function(){
        return this.insurancePolicy;
    }

    o.isInsured = function() {
        return !!this.insurancePolicy;
    }
}

// makeInsurable(Car)
// const car1 = new Car();
// car1.addInsurancePolicy(new InsurancePolicy());
// const car1 = new Car()
// makeInsurable(car1);
// car1.addInsurancePolicy(new InsurancePolicy());

makeInsurable(Car.prototype);
const car1 = new Car();
car1.addInsurancePolicy(new InsurancePolicy());

console.log(car1.isInsured());


text:
package zecuse.MCModTutorial.reference;

// This enumeration defines names for bound keys in the mod.
public enum Key
{
	UNKNOWN, CHARGE, RELEASE;
}


text:
================
kapacitor-formula
================

This formula will install and setup kapacitor.

Available states
================

.. contents::
    :local:

``kapacitor``
------------

Downloads and installs the kapacitor package, sets up configuration and service management.


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a
Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Added compatibility with PHP 8.0.

### Changed

- (internal) replaced Travis CI with Github Actions after travis-ci.org shut down.

## [6.1.0] - 2020-09-19

### Added

- Add support for Mako Framework 7. Support for Mako 6.x is unchanged.

### Fixed

- Fixed an issue in PHP 7.4 relating to `ReflectionType` string
  conversion.

## [6.0] - 2019-04-09

### Added

- TemplateCompilationTest now supports PHPUnit 6 or higher.
    - Note that this still needs PHP 7.2.

### Changed

- Require Mako 6.0 or compatible
- Require PHP 7.2

## [5.2.3]

### Added

- Add a utility template test class. Use it as a sanity check for your
  views.
- Better type hinting for internal function wrappers.

[Unreleased]: https://github.com/bertptrs/marty/compare/v6.1.0...HEAD
[6.1.0]: https://github.com/bertptrs/marty/compare/v6.0...v6.1.0
[6.0]: https://github.com/bertptrs/marty/compare/v5.2.3...v6.0
[5.2.3]: https://github.com/bertptrs/marty/compare/v5.2.2...v5.2.3


text:
.class Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;
.super Ljava/lang/Object;
.source "SemIndexScrollView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "LangAttributeValues"
.end annotation

# instance fields
.field alphabetArray:[Ljava/lang/String;

.field dotCount:I

.field height:F

.field indexCount:I

.field separatorHeight:F

.field final synthetic this$1:Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll;

.field totalCount:I

# direct methods
.method public constructor <init>(Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll;IIIFF)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->this$1:Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput p2, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->indexCount:I

    iput p3, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->dotCount:I

    iput p4, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->totalCount:I

    iput p5, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->height:F

    iput p6, p0, Lcom/samsung/android/widget/SemIndexScrollView$IndexScroll$LangAttributeValues;->separatorHeight:F

    return-void
.end method


text:
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongodb = require('mongodb');

let dbUri = process.env.DATABASE_URI || "mongodb://localhost:27017/dev";

const db = require('./databaseAdapter.js')(dbUri);
const emailSender = require('./emailAdapter.js')(process.env.EMAIL_KEY);

app.use(bodyParser.json({type: '*/*'}));

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

app.get('/users', function (req, res) {
  db.find(req.query)
  .then(data=>{
    if(!data){
      res.status(400).send('user not found');
    }else{
      res.send(data._id);
    }
  })
  .catch(err=>{
    console.log('get users failed', err);
    res.status(400).send('something wrong when get users');
  });
});

//{ usesrs:[]}
app.post('/users', function (req, res) {
  //console.log('users',req.params);
  db.insert(req.body.users)
  .then(()=>{
      res.send('success');
  })
  .catch(err=>{
    console.log('insert users failed', err);
    res.status(400).send('something wrong when insert users');
  });
});

app.put('/users/:id', function (req, res) {
  res.send('not implement yet');
});

app.delete('/users/:id', function (req, res) {
  db.delete({_id: new mongodb.ObjectId(req.params.id)})
  .then(result=>{
      res.send('ok');
  })
  .catch(err=>{
    console.log('delete users failed', err);
    res.status(400).send('something wrong when delete users');
  });

});

app.post('/functions/:fun', function (req, res) {
  //wait for complete or response directly
  console.log('body?', req.body);
  let promise;
  switch(req.params.fun){
    case 'notify':
      promise = notify(req.body);
      break;

    default:
      promise = Promise.reject('unsupported functions');
  }
  promise.then(()=>res.send('done'))
  .catch(err=>{
    console.log(err);
    res.status(400).send("something wrong when do " + req.params.fun);
  });
});

function notify(query) {
  return db.find(query)
  .then(user=> sendEmail(user.email));
}

function sendEmail(email){
  if(process.env.EMAIL_KEY){
    return emailSender.send(email);
  }else{
    return Promise.resolve();
  }
}

exports.db = db;
//ToDo: gracefull shutdown, catch exceptions


text:
typedef enum : NSUInteger {
    ContactTableViewCellPhoneNumber,
    ContactTableViewCellEmailId
} ContactSubDetailsType;

@interface ContactTableViewCell : UITableViewCell{
    IBOutlet UIImageView *imageViewSelection;
    IBOutlet UILabel *labelName;
    IBOutlet UILabel *labelContactSubDetails;
    IBOutlet UILabel *labelContactSubDetailsType;
}

+(UINib *)cellNib;
+(NSString *)cellIdentifier;
+(CGFloat )cellSize;
-(void)configCellWithContact:(APContact *)contact andContactSubDetailsType:(ContactSubDetailsType)contactSubDetailsType andIsSelected:(BOOL)isSelected;

@end


text:
uri = new URI(document.location);
var graphite_host = uri.search(true)['host'];
var dash_name = uri.search(true)['dash'] || "default";

// console.log(graphite_host);
// console.log(dash_name);

/*

All data is stored in a PouchDB database, "yolo-graphite".

Dashboards are stored in documents of type "dashboard".
{
    type: "dashboard",
    name: "name",
    targets: [... ids of targets ...]
}

*/
var db = new PouchDB('yolo-graphite');
var remoteCouch = false;

db.info(function(err, info) {
    console.log("Opened database: " + JSON.stringify(info, null, "  "));
});

// db.allDocs({include_docs: false}, function(err, response) {
//     console.log("[allDocs]: " + JSON.stringify(response, null, "  "));
// });

function dashboard_id(_dash_name) {
    var id = "yolo-dashboard-v1-" + _dash_name;
    return id;
}

function init_targets() {
    // make sure we've a document for this target
    var id = dashboard_id(dash_name);
    db.get(id, function(err, doc) {
        if (doc === undefined) {
            db.put(
                {
                    _id: id,
                    type: "dashboard",
                    name: dash_name,
                    "targets": []
                },
                function(err, response) {
                    console.log("Created dashboard doc: " + id);
                }
            );
        } else {
            console.log("Existing dashboard doc: " + id);
        }
    });
}

function all_dash_names(callback) {
    function map(doc) {
        // console.log("[map] " + JSON.stringify(doc));
        if(doc.type && doc.type === "dashboard") {
            emit(doc.name, null);
        }
    }
    db.query({map: map}, {reduce: false}, function(err, response) {
        var dashboards = [];
        response.rows.forEach(function(row) {
            dashboards.push(row.key);
        });
        console.log("[all_dash_names] " + dashboards);
        callback(dashboards);
    });
}

function all_targets_for_dash(_dash_name, callback) {
    var id = dashboard_id(_dash_name);
    db.get(id, function(err, doc) {
        console.log('[all_targets_for_dash] ' + JSON.stringify(doc, null, " "));
        callback(doc.targets);
    });
}

function update_targets_for_dash(_dash_name, _targets, callback) {
    var id = dashboard_id(_dash_name);
    db.get(id, function(err, doc) {
        console.log('[update_targets_for_dash] ' + JSON.stringify(doc, null, " "));
        doc.targets = _targets;
        db.put(doc, function(err, response) {
            if (err) {
                alert(err + ": " + response);
            } else {
                console.log("Saved update to targets");
            }
            if (callback) { callback(); }
        });
    });
}

function target_for_index(target_index, callback) {
    all_targets_for_dash(dash_name, function(targets) {
        callback(targets[target_index]);
    });
}

function prepend_target(target_details, callback) {
    all_targets_for_dash(dash_name, function(targets) {
        targets.push(target_details);
        update_targets_for_dash(dash_name, targets, function() {
            if (callback) { callback(); }
        });
    });
}

function remove_target(target_index, callback) {
    all_targets_for_dash(dash_name, function(targets) {
        targets.splice(target_index, 1);
        update_targets_for_dash(dash_name, targets, function() {
            if (callback) { callback(); }
        });
    });
}

function update_target(target_index, target_details, callback) {
    all_targets_for_dash(dash_name, function(targets) {
        targets.splice(target_index, 1, target_details);
        update_targets_for_dash(dash_name, targets, function() {
            if (callback) { callback(); }
        });
    });
}


text:
using System;
using NUnit.Framework;
using NodaTime.Fields;

namespace NodaTime.Test.Fields
{
    [TestFixture]
    public class ScaledDurationTest
    {
        private readonly ScaledDurationField sample = new ScaledDurationField(TicksDurationField.Instance, DurationFieldType.Minutes, 90);
        private readonly LocalInstant localInstant = new LocalInstant(567L);

        [Test]
        public void Constructor_WithNullField_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => new ScaledDurationField(null, DurationFieldType.Minutes, 10));
        }

        [Test]
        public void Constructor_WithUnsupportedField_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentException>(() => new ScaledDurationField(UnsupportedDurationField.Milliseconds, DurationFieldType.Minutes, 10));
        }

        [Test]
        public void Constructor_WithInvalidFieldType_ThrowsArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ScaledDurationField(TicksDurationField.Instance, (DurationFieldType)(-1), 10));
        }

        [Test]
        public void Constructor_WithScaleOfZero_ThrowsArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ScaledDurationField(TicksDurationField.Instance, DurationFieldType.Minutes, 0));
        }

        [Test]
        public void Constructor_WithScaleOfOne_ThrowsArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ScaledDurationField(TicksDurationField.Instance, DurationFieldType.Minutes, 1));
        }

        [Test]
        public void SimpleProperties()
        {
            Assert.AreEqual(DurationFieldType.Minutes, sample.FieldType);
            Assert.IsTrue(sample.IsSupported);
            Assert.IsTrue(sample.IsPrecise);
        }

        [Test]
        public void UnitTicks()
        {
            Assert.AreEqual(90, sample.UnitTicks);
        }

        [Test]
        public void GetValue()
        {
            Assert.AreEqual(0, sample.GetValue(new Duration(0L)));
            Assert.AreEqual(12345678 / 90, sample.GetValue(new Duration(12345678L)));
            Assert.AreEqual(-1234 / 90, sample.GetValue(new Duration(-1234L)));
            Assert.AreEqual(int.MaxValue / 90, sample.GetValue(new Duration(int.MaxValue)));
        }

        public void GetValue_WithNonInt32Value_Overflows()
        {
            Assert.Throws<OverflowException>(() => sample.GetValue(new Duration(int.MaxValue + 1L)));
        }

        [Test]
        public void GetInt64Value()
        {
            Assert.AreEqual(0L, sample.GetInt64Value(new Duration(0L)));
            Assert.AreEqual(12345678L / 90, sample.GetInt64Value(new Duration(12345678L)));
            Assert.AreEqual(-1234L / 90, sample.GetInt64Value(new Duration(-1234L)));
            Assert.AreEqual(int.MaxValue / 90L, sample.GetInt64Value(new Duration(int.MaxValue)));
            Assert.AreEqual(int.MaxValue + 1L, sample.GetInt64Value(new Duration(int.MaxValue * 90L + 90L)));
        }

        public void GetValue_WithLocalInstant()
        {
            Assert.AreEqual(0, sample.GetValue(new Duration(0L), localInstant));
            Assert.AreEqual(12345678 / 90, sample.GetValue(new Duration(12345678L), localInstant));
            Assert.AreEqual(-1234 / 90, sample.GetValue(new Duration(-1234L), localInstant));
            Assert.AreEqual(int.MaxValue / 90, sample.GetValue(new Duration(int.MaxValue), localInstant));
        }

        public void GetValue_WithLocalInstantButNonInt32Value_Overflows()
        {
            Assert.Throws<OverflowException>(() => sample.GetValue(new Duration(int.MaxValue + 1L), localInstant));
        }

        [Test]
        public void GetInt64Value_WithLocalInstant()
        {
            Assert.AreEqual(0L, sample.GetInt64Value(new Duration(0L), localInstant));
            Assert.AreEqual(12345678L / 90, sample.GetInt64Value(new Duration(12345678L), localInstant));
            Assert.AreEqual(-1234L / 90, sample.GetInt64Value(new Duration(-1234L), localInstant));
            Assert.AreEqual(int.MaxValue / 90L, sample.GetInt64Value(new Duration(int.MaxValue), localInstant));
            Assert.AreEqual(int.MaxValue + 1L, sample.GetInt64Value(new Duration(int.MaxValue * 90L + 90L), localInstant));
        }

        [Test]
        public void GetDuration()
        {
            Assert.AreEqual(0L, sample.GetDuration(0).Ticks);
            Assert.AreEqual(1234 * 90L, sample.GetDuration(1234).Ticks);
            Assert.AreEqual(-1234 * 90L, sample.GetDuration(-1234).Ticks);
            Assert.AreEqual(int.MaxValue * 90L, sample.GetDuration(int.MaxValue).Ticks);
        }

        [Test]
        public void GetDuration_WithOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.GetDuration(long.MaxValue));
        }

        [Test]
        public void GetDuration_WithLocalInstant()
        {
            Assert.AreEqual(0L, sample.GetDuration(0, localInstant).Ticks);
            Assert.AreEqual(1234 * 90L, sample.GetDuration(1234, localInstant).Ticks);
            Assert.AreEqual(-1234 * 90L, sample.GetDuration(-1234, localInstant).Ticks);
            Assert.AreEqual(int.MaxValue * 90L, sample.GetDuration(int.MaxValue, localInstant).Ticks);
        }

        [Test]
        public void GetDuration_WithLocalInstantCausingOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.GetDuration(long.MaxValue, localInstant));
        }

        [Test]
        public void Add_WithInt32()
        {
            Assert.AreEqual(567L, sample.Add(localInstant, 0).Ticks);
            Assert.AreEqual(567L + 1234L * 90L, sample.Add(localInstant, 1234).Ticks);
            Assert.AreEqual(567L - 1234L * 90L, sample.Add(localInstant, -1234).Ticks);
        }

        [Test]
        public void Add_WithInt32CausingOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.Add(new LocalInstant(long.MaxValue), 1));
        }

        [Test]
        public void Add_WithInt64()
        {
            Assert.AreEqual(567L, sample.Add(localInstant, 0L).Ticks);
            Assert.AreEqual(567L + 1234L * 90L, sample.Add(localInstant, 1234L).Ticks);
            Assert.AreEqual(567L - 1234L * 90L, sample.Add(localInstant, -1234L).Ticks);
        }

        [Test]
        public void Add_WithInt64CausingOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.Add(new LocalInstant(long.MaxValue), 1L));
        }

        [Test]
        public void GetDifference()
        {
            Assert.AreEqual(0, sample.GetDifference(new LocalInstant(1L), new LocalInstant(0L)));
            Assert.AreEqual(567, sample.GetDifference(new LocalInstant(567 * 90L), new LocalInstant(0L)));
            Assert.AreEqual(567 - 1234, sample.GetDifference(new LocalInstant(567 * 90L), new LocalInstant(1234 * 90L)));
            Assert.AreEqual(567 + 1234, sample.GetDifference(new LocalInstant(567 * 90L), new LocalInstant(-1234 * 90L)));
        }

        [Test]
        public void GetDifference_WithOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.GetDifference(new LocalInstant(long.MaxValue), new LocalInstant(-1L)));
        }

        [Test]
        public void GetInt64Difference()
        {
            Assert.AreEqual(0L, sample.GetInt64Difference(new LocalInstant(1L), new LocalInstant(0L)));
            Assert.AreEqual(567L, sample.GetInt64Difference(new LocalInstant(567 * 90L), new LocalInstant(0L)));
            Assert.AreEqual(567L - 1234L, sample.GetInt64Difference(new LocalInstant(567 * 90L), new LocalInstant(1234 * 90L)));
            Assert.AreEqual(567L + 1234L, sample.GetInt64Difference(new LocalInstant(567 * 90L), new LocalInstant(-1234 * 90L)));
        }

        [Test]
        public void GetInt64Difference_WithOverflow()
        {
            Assert.Throws<OverflowException>(() => sample.GetInt64Difference(new LocalInstant(long.MaxValue), new LocalInstant(-1L)));
        }
    }
}


text:
// Decompiled with JetBrains decompiler
// Type: LinqToWiki.Generated.Entities.protectedtitlesOrderBy
// Assembly: LinqToWiki.Generated, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: A4304DCD-2C3F-4D9F-B552-69913FDA3067
// Assembly location: D:\work\my\AsoiafWikiDb\AsoiafWikiDb\bin\LinqToWiki.Generated.dll

namespace LinqToWiki.Generated.Entities
{
  public sealed class protectedtitlesOrderBy
  {
    private protectedtitlesOrderBy()
    {
    }
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
F. W. H. A. von Humboldt et al. , Nov. gen. sp. 5:287[folio]; 5:369[quarto]. 1823; t. 492. 1822

#### Original name
null

### Remarks
null


text:
"""
.. _tut-sensors-time-freq:

============================================
Frequency and time-frequency sensor analysis
============================================

The objective is to show you how to explore the spectral content
of your data (frequency and time-frequency). Here we'll work on Epochs.

We will use this dataset: :ref:`somato-dataset`. It contains so-called event
related synchronizations (ERS) / desynchronizations (ERD) in the beta band.
"""  # noqa: E501
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#          Richard Höchenberger <richard.hoechenberger@gmail.com>
#
# License: BSD (3-clause)
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet, psd_multitaper, psd_welch
from mne.datasets import somato

###############################################################################
# Set parameters
data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')

# picks MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False)

# Construct Epochs
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6),
                    preload=True)

epochs.resample(200., npad='auto')  # resample to reduce computation time

###############################################################################
# Frequency analysis
# ------------------
#
# We start by exploring the frequence content of our epochs.

###############################################################################
# Let's first check out all channel types by averaging across epochs.
epochs.plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False)

###############################################################################
# Now let's take a look at the spatial distributions of the PSD.
epochs.plot_psd_topomap(ch_type='grad', normalize=True)

###############################################################################
# Alternatively, you can also create PSDs from Epochs objects with functions
# that start with ``psd_`` such as
# :func:`mne.time_frequency.psd_multitaper` and
# :func:`mne.time_frequency.psd_welch`.

f, ax = plt.subplots()
psds, freqs = psd_multitaper(epochs, fmin=2, fmax=40, n_jobs=1)
psds = 10. * np.log10(psds)
psds_mean = psds.mean(0).mean(0)
psds_std = psds.mean(0).std(0)

ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
                color='k', alpha=.5)
ax.set(title='Multitaper PSD (gradiometers)', xlabel='Frequency (Hz)',
       ylabel='Power Spectral Density (dB)')
plt.show()

###############################################################################
# Notably, :func:`mne.time_frequency.psd_welch` supports the keyword argument
# ``average``, which specifies how to estimate the PSD based on the individual
# windowed segments. The default is ``average='mean'``, which simply calculates
# the arithmetic mean across segments. Specifying ``average='median'``, in
# contrast, returns the PSD based on the median of the segments (corrected for
# bias relative to the mean), which is a more robust measure.

# Estimate PSDs based on "mean" and "median" averaging for comparison.
kwargs = dict(fmin=2, fmax=40, n_jobs=1)
psds_welch_mean, freqs_mean = psd_welch(epochs, average='mean', **kwargs)
psds_welch_median, freqs_median = psd_welch(epochs, average='median', **kwargs)

# Convert power to dB scale.
psds_welch_mean = 10 * np.log10(psds_welch_mean)
psds_welch_median = 10 * np.log10(psds_welch_median)

# We will only plot the PSD for a single sensor in the first epoch.
ch_name = 'MEG 0122'
ch_idx = epochs.info['ch_names'].index(ch_name)
epo_idx = 0

_, ax = plt.subplots()
ax.plot(freqs_mean, psds_welch_mean[epo_idx, ch_idx, :], color='k',
        ls='-', label='mean of segments')
ax.plot(freqs_median, psds_welch_median[epo_idx, ch_idx, :], color='k',
        ls='--', label='median of segments')

ax.set(title='Welch PSD ({}, Epoch {})'.format(ch_name, epo_idx),
       xlabel='Frequency (Hz)', ylabel='Power Spectral Density (dB)')
ax.legend(loc='upper right')
plt.show()

###############################################################################
# Lastly, we can also retrieve the unaggregated segments by passing
# ``average=None`` to :func:`mne.time_frequency.psd_welch`. The dimensions of
# the returned array are ``(n_epochs, n_sensors, n_freqs, n_segments)``.

psds_welch_unagg, freqs_unagg = psd_welch(epochs, average=None, **kwargs)
print(psds_welch_unagg.shape)

###############################################################################
# .. _inter-trial-coherence:
#
# Time-frequency analysis: power and inter-trial coherence
# --------------------------------------------------------
#
# We now compute time-frequency representations (TFRs) from our Epochs.
# We'll look at power and inter-trial coherence (ITC).
#
# To this we'll use the function :func:`mne.time_frequency.tfr_morlet`
# but you can also use :func:`mne.time_frequency.tfr_multitaper`
# or :func:`mne.time_frequency.tfr_stockwell`.

# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2.  # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=3, n_jobs=1)

###############################################################################
# Inspect power
# -------------
#
# .. note::
#     The generated figures are interactive. In the topo you can click
#     on an image to visualize the data for one sensor.
#     You can also select a portion in the time-frequency plane to
#     obtain a topomap for a certain time-frequency region.
power.plot_topo(baseline=(-0.5, 0), mode='logratio', title='Average power')
power.plot([82], baseline=(-0.5, 0), mode='logratio', title=power.ch_names[82])

fig, axis = plt.subplots(1, 2, figsize=(7, 4))
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=8, fmax=12,
                   baseline=(-0.5, 0), mode='logratio', axes=axis[0],
                   title='Alpha', show=False)
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=13, fmax=25,
                   baseline=(-0.5, 0), mode='logratio', axes=axis[1],
                   title='Beta', show=False)
mne.viz.tight_layout()
plt.show()

###############################################################################
# Joint Plot
# ----------
# You can also create a joint plot showing both the aggregated TFR
# across channels and topomaps at specific times and frequencies to obtain
# a quick overview regarding oscillatory effects across time and space.

power.plot_joint(baseline=(-0.5, 0), mode='mean', tmin=-.5, tmax=2,
                 timefreqs=[(.5, 10), (1.3, 8)])

###############################################################################
# Inspect ITC
# -----------
itc.plot_topo(title='Inter-Trial coherence', vmin=0., vmax=1., cmap='Reds')

###############################################################################
# .. note::
#     Baseline correction can be applied to power or done in plots.
#     To illustrate the baseline correction in plots, the next line is
#     commented power.apply_baseline(baseline=(-0.5, 0), mode='logratio')
#
# Exercise
# --------
#
#    - Visualize the inter-trial coherence values as topomaps as done with
#      power.


text:
GitRepository
=============


text:
---
layout: default
---

			Posted on {{ page.date | date: "%B %-d, %Y" }}

			by {{ site.author }}

{{ page.title }}

	{% if page.image %}

	{% endif %}

		{{ content }}

	Tweet

			{% if page.next.url %}

				Next entry
				{{ page.next.title }}

			{% endif %}

			{% if page.previous.url %}

				Previous entry
				{{ page.previous.title }}

			{% endif %}

Please enable JavaScript to view the comments powered by Disqus.


text:
    Skill Description

      This is the name of the skill as visible to learners and other creators.

 0}">
      <input type="text" aria-label="Skill Description" class="form-control protractor-test-skill-description-field" ng-if="canEditSkillDescription()"
             ng-model="tmpSkillDescription" ng-change="resetErrorMsg()" ng-blur="saveSkillDescription(tmpSkillDescription)"
             maxlength="<[MAX_CHARS_IN_SKILL_DESCRIPTION]>" ng-trim="false">

          Skill description should be at most <[MAX_CHARS_IN_SKILL_DESCRIPTION]> characters.

          <[errorMsg]>

      <[tmpSkillDescription]>


text:
namespace blink {

class ChildNode {
public:
    static void before(Node& node, const HeapVector<NodeOrString>& nodes, ExceptionState& exceptionState)
    {
        return node.before(nodes, exceptionState);
    }

    static void after(Node& node, const HeapVector<NodeOrString>& nodes, ExceptionState& exceptionState)
    {
        return node.after(nodes, exceptionState);
    }

    static void replaceWith(Node& node, const HeapVector<NodeOrString>& nodes, ExceptionState& exceptionState)
    {
        return node.replaceWith(nodes, exceptionState);
    }

    static void remove(Node& node, ExceptionState& exceptionState)
    {
        return node.remove(exceptionState);
    }
};

} // namespace blink

#endif // ChildNode_h


text:
require 'uri'
require 'json'
require 'faraday'
require 'faraday_middleware'

class Tripletexer::APIClient
  ENDPOINT = 'https://tripletex.no/'

  attr_reader :session_token, :debug

  def initialize(object_class: Hash, proxy: nil, debug: false)
    @object_class = object_class
    @proxy = proxy
    @debug = debug
  end

  def connection
    return @connection if session_token && @connection
    @connection = init_connection
  end

  def reset_connection
    @session_token = @connection = nil
  end

  def session_token=(new_session_token)
    reset_connection
    @session_token = new_session_token
  end

  def get(path, *args, &block)
    call(:get, path, *args, &block)
  end

  def post(path, *args, &block)
    call(:post, path, *args, &block)
  end

  def put(path, *args, &block)
    call(:put, path, *args, &block)
  end

  def delete(path, *args, &block)
    call(:delete, path, *args, &block)
  end

  private

  attr_reader :object_class, :proxy

  def init_connection
    Faraday.new(url: ENDPOINT) do |faraday|
      faraday.response :logger if debug
      faraday.response :json, parser_options: { object_class: object_class }, content_type: %r[/json$]
      faraday.headers = {
        'Content-Type' => 'application/json'
      }
      faraday.adapter :net_http
      faraday.basic_auth(0, session_token) if session_token
      faraday.proxy = proxy if proxy # https://github.com/lostisland/faraday/issues/733
    end
  end

  def call(method, path, *args, &block)
    normalized_path = URI.escape(path)
    response = connection.public_send(method, normalized_path, *args, &block)
    handle_response(response)
  end

  def handle_response(response)
    body = response.body
    case response.status
    when 200, 201, 204
      body
    when 400, 422
      raise ::Tripletexer::Errors::BadRequest, body
    when 401
      raise ::Tripletexer::Errors::Unauthorized, body
    when 403
      raise ::Tripletexer::Errors::Forbidden, body
    when 404
      raise ::Tripletexer::Errors::NotFound, body
    when 409
      raise ::Tripletexer::Errors::Conflict, body
    when 500
      raise ::Tripletexer::Errors::InternalError, body
    else
      raise NotImplementedError, "don't know how to handle #{response.status} http status code"
    end
  end

end


text:
package org.datavaultplatform.broker.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.datavaultplatform.common.model.FileInfo;
import org.datavaultplatform.broker.services.FilesService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.datavaultplatform.broker.services.UsersService;
import org.datavaultplatform.common.model.FileStore;
import org.datavaultplatform.common.model.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;

/**
 * User: Robin Taylor
 * Date: 01/05/2015
 * Time: 13:21
 */

@RestController
public class FilesController {

    private FilesService filesService;
    private UsersService usersService;

    public void setFilesService(FilesService filesService) {
        this.filesService = filesService;
    }

    public void setUsersService(UsersService usersService) {
        this.usersService = usersService;
    }

    @RequestMapping("/files")
    public List<FileInfo> getStorageListing(@RequestHeader(value = "X-UserID", required = true) String userID,
                                            HttpServletRequest request) {

        User user = usersService.getUser(userID);

        ArrayList<FileInfo> files = new ArrayList<>();
        List<FileStore> userStores = user.getFileStores();
        for (FileStore userStore : userStores) {
            FileInfo info = new FileInfo(userStore.getID(),
                                         userStore.getID(),
                                         userStore.getLabel(),
                                         true);
            files.add(info);
        }

        // "GET /files/" will display a list of configured user storage systems.
        return files;
    }

    @RequestMapping("/files/{storageid}/**")
    public List<FileInfo> getFilesListing(@RequestHeader(value = "X-UserID", required = true) String userID,
                                          HttpServletRequest request,
                                          @PathVariable("storageid") String storageID) throws Exception {

        User user = usersService.getUser(userID);

        FileStore store = null;
        List<FileStore> userStores = user.getFileStores();
        for (FileStore userStore : userStores) {
            if (userStore.getID().equals(storageID)) {
                store = userStore;
            }
        }

        if (store == null) {
            throw new Exception("Storage device '" + storageID + "' not found!");
        }

        // "GET /files/storageid" will display files from the base directory.
        // "GET /files/storageid/abc" will display files from the "abc" directory under the base.

        // TODO: is there a cleaner way to extract the request path?
        String requestPath = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String filePath = requestPath.replaceFirst("^/files/" + storageID, "");

        List<FileInfo> files = filesService.getFilesListing(filePath, store);

        // Add the storage key to the start of the returned path/key
        for (FileInfo file : files) {
            String fullKey = file.getKey();

            if (!fullKey.startsWith("/")) {
                fullKey = "/" + fullKey;
            }

            fullKey = storageID + fullKey;
            file.setKey(fullKey);
        }

        return files;
    }

    @RequestMapping("/filesize/{storageid}/**")
    public String getFilesize(@RequestHeader(value = "X-UserID", required = true) String userID,
                                      HttpServletRequest request,
                                      @PathVariable("storageid") String storageID) throws Exception {

        User user = usersService.getUser(userID);

        FileStore store = null;
        List<FileStore> userStores = user.getFileStores();
        for (FileStore userStore : userStores) {
            if (userStore.getID().equals(storageID)) {
                store = userStore;
            }
        }

        if (store == null) {
            throw new Exception("Storage device '" + storageID + "' not found!");
        }

        // TODO: is there a cleaner way to extract the request path?
        String requestPath = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String filePath = requestPath.replaceFirst("^/filesize/" + storageID, "");

        Long size = filesService.getFilesize(filePath, store);

        if (size == null) {
            return "File information not available";
        } else {
            return FileUtils.byteCountToDisplaySize(size);
        }
    }
}


text:
namespace leveldb {

namespace {
static uint32_t BloomHash(const Slice& key) {
  return Hash(key.data(), key.size(), 0xbc9f1d34);
}

class BloomFilterPolicy : public FilterPolicy {
 private:
  size_t bits_per_key_;
  size_t k_;

 public:
  explicit BloomFilterPolicy(int bits_per_key)
      : bits_per_key_(bits_per_key) {
    // We intentionally round down to reduce probing cost a little bit
    k_ = static_cast<size_t>(bits_per_key * 0.69);  // 0.69 =~ ln(2)
    if (k_ < 1) k_ = 1;
    if (k_ > 30) k_ = 30;
  }

  virtual const char* Name() const {
    return "leveldb.BuiltinBloomFilter2";
  }

  virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const {
    // Compute bloom filter size (in both bits and bytes)
    size_t bits = n * bits_per_key_;

    // For small n, we can see a very high false positive rate.  Fix it
    // by enforcing a minimum bloom filter length.
    if (bits < 64) bits = 64;

    size_t bytes = (bits + 7) / 8;
    bits = bytes * 8;

    const size_t init_size = dst->size();
    dst->resize(init_size + bytes, 0);
    dst->push_back(static_cast<char>(k_));  // Remember # of probes in filter
    char* array = &(*dst)[init_size];
    for (int i = 0; i < n; i++) {
      // Use double-hashing to generate a sequence of hash values.
      // See analysis in [Kirsch,Mitzenmacher 2006].
      uint32_t h = BloomHash(keys[i]);
      const uint32_t delta = (h >> 17) | (h << 15);  // Rotate right 17 bits
      for (size_t j = 0; j < k_; j++) {
        const uint32_t bitpos = h % bits;
        array[bitpos/8] |= (1 << (bitpos % 8));
        h += delta;
      }
    }
  }

  virtual bool KeyMayMatch(const Slice& key, const Slice& bloom_filter) const {
    const size_t len = bloom_filter.size();
    if (len < 2) return false;

    const char* array = bloom_filter.data();
    const size_t bits = (len - 1) * 8;

    // Use the encoded k so that we can read filters generated by
    // bloom filters created using different parameters.
    const size_t k = array[len-1];
    if (k > 30) {
      // Reserved for potentially new encodings for short bloom filters.
      // Consider it a match.
      return true;
    }

    uint32_t h = BloomHash(key);
    const uint32_t delta = (h >> 17) | (h << 15);  // Rotate right 17 bits
    for (size_t j = 0; j < k; j++) {
      const uint32_t bitpos = h % bits;
      if ((array[bitpos/8] & (1 << (bitpos % 8))) == 0) return false;
      h += delta;
    }
    return true;
  }
};
}

const FilterPolicy* NewBloomFilterPolicy(int bits_per_key) {
  return new BloomFilterPolicy(bits_per_key);
}

}  // namespace leveldb


text:
/**
 * methods used to group similar keywords
 */
export type KeywordType =
    /**
     * keyword identifies a branch of instruction or specialized learning
     */
    'discipline' |
    /**
     * keyword identifies a location
     */
    'place' |
    /**
     * keyword identifies the layer(s) of any deposited substance
     */
    'stratum' |
    /**
     * keyword identifies a time period related to the dataset
     */
    'temporal' |
    /**
     * keyword identifies a particular subject or topic
     */
    'theme';


text:
from ggrc.models import Person
from tests.ggrc.converters import TestCase
from tests.ggrc.generator import ObjectGenerator

class TestBasicCsvImport(TestCase):

  def setUp(self):
    TestCase.setUp(self)
    self.generator = ObjectGenerator()
    self.client.get("/login")

  def test_people_import(self):
    filename = "people_basic_import.csv"
    self.import_file(filename)
    self.assertEquals(5, Person.query.count())

  def test_people_import_correct_order_dry_run(self):
    filename = "people_import_correct_order.csv"
    response = self.import_file(filename, dry_run=True)
    self.assertEquals(1, Person.query.count())
    self.assertEquals(response[1]["name"], "Org Group")
    self.assertEquals(set(), set(response[1]["row_warnings"]))
    self.assertEquals(set(), set(response[1]["row_errors"]))

  def test_people_import_wrong_order_dry_run(self):
    filename = "people_import_correct_order.csv"
    filename = "people_import_wrong_order.csv"
    response = self.import_file(filename, dry_run=True)
    self.assertEquals(1, Person.query.count())
    self.assertEquals(response[1]["name"], "Org Group")
    self.assertEquals(set(), set(response[1]["row_warnings"]))
    self.assertEquals(set(), set(response[1]["row_errors"]))

  def test_people_import_correct_order(self):
    filename = "people_import_correct_order.csv"
    response = self.import_file(filename)
    self.assertEquals(5, Person.query.count())
    self.assertEquals(response[1]["name"], "Org Group")
    self.assertEquals(set(), set(response[1]["row_warnings"]))
    self.assertEquals(set(), set(response[1]["row_errors"]))

  def test_people_import_wrong_order(self):
    filename = "people_import_correct_order.csv"
    filename = "people_import_wrong_order.csv"
    response = self.import_file(filename)
    self.assertEquals(5, Person.query.count())
    self.assertEquals(response[1]["name"], "Org Group")
    self.assertEquals(set(), set(response[1]["row_warnings"]))
    self.assertEquals(set(), set(response[1]["row_errors"]))


text:
//
// Copyright (c) 2006-2017 Benjamin Kaufmann
//
// This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
#ifndef BK_LIB_POD_VECTOR_H_INCLUDED
#define BK_LIB_POD_VECTOR_H_INCLUDED
#include "type_manip.h"
#include <iterator>
#include <memory>
#include <cstring>
#include <algorithm>
#include <cassert>
#include <stdexcept>

#if defined(__GNUC__)
#pragma GCC system_header
#endif

namespace bk_lib { namespace detail {
	template <class T>
	void fill(T* first, T* last, const T& x) {
		assert(first <= last);
		switch ((last - first) & 7u)
		{
		case 0:
				while (first != last)
				{
				new(first++) T(x);
		case 7: new(first++) T(x);
		case 6: new(first++) T(x);
		case 5: new(first++) T(x);
		case 4: new(first++) T(x);
		case 3: new(first++) T(x);
		case 2: new(first++) T(x);
		case 1: new(first++) T(x);
				assert(first <= last);
				}
		}
	}
	template <class Iter, class T>
	void copy(Iter first, Iter last, std::size_t s, T* out) {
		switch (s & 7u)
		{
		case 0:
				while (first != last)
				{
				new(out++) T(*first++);
		case 7: new(out++) T(*first++);
		case 6: new(out++) T(*first++);
		case 5: new(out++) T(*first++);
		case 4: new(out++) T(*first++);
		case 3: new(out++) T(*first++);
		case 2: new(out++) T(*first++);
		case 1: new(out++) T(*first++);
				}
		}
	}
	template <class T>
	struct Fill {
		Fill(const T& val) : val_(val) {}
		void operator()(T* first, std::size_t n) const { detail::fill(first, first + n, val_); }
		const T& val_;
	private: Fill& operator=(const Fill&);
	};
	template <class Iter>
	struct Copy {
		Copy(Iter first, Iter last) : first_(first), last_(last) {}
		template <class T>
		void operator()(T* out, std::size_t n) const { detail::copy(first_, last_, n, out); }
		Iter first_;
		Iter last_;
	};
	template <class T>
	struct Memcpy {
		Memcpy(const T* first) : first_(first) {}
		void operator()(T* out, std::size_t n) const {
			std::memcpy(out, first_, n*sizeof(T));
		}
		const T* first_;
	};
	typedef char yes_type;
	typedef char (&no_type)[2];
	template <class T>
	struct IterType {
		static yes_type isPtr(const volatile void*);
		static no_type isPtr(...);
		static yes_type isLong(long long);
		static no_type  isLong(...);
		static T& makeT();
		enum { ptr = sizeof(isPtr(makeT())) == sizeof(yes_type) };
		enum { num = sizeof(isLong(makeT())) == sizeof(yes_type) };
		enum { value = ptr ? 1 : num ? 2 : 0 };
	};

} // end namespace bk_lib::detail

//! A std::vector-replacement for POD-Types.
/*!
 * \pre T is a POD-Type
 * \see http://www.comeaucomputing.com/techtalk/#pod for a description of POD-Types.
 * \note Does not call any destructors and uses std::memcpy to copy/move elements
 * \note On LP64-machines size and capacity are represented as unsigned integers (instead of e.g. std::size_t)
 */
template <class T, class Allocator = std::allocator<T> >
class pod_vector {
public:
	// types:
	typedef          pod_vector<T,Allocator>          this_type;//not standard
	typedef          Allocator                        allocator_type;
	typedef typename Allocator::reference             reference;
	typedef typename Allocator::const_reference       const_reference;
	typedef typename Allocator::pointer               iterator;
	typedef typename Allocator::const_pointer         const_iterator;
	typedef typename Allocator::pointer               pointer;
	typedef typename Allocator::const_pointer         const_pointer;
	typedef std::reverse_iterator<iterator>           reverse_iterator;
	typedef std::reverse_iterator<const_iterator>     const_reverse_iterator;
	typedef          T                                value_type;
	typedef typename detail::if_then_else<
		sizeof(typename Allocator::size_type)<=sizeof(unsigned int),
		typename Allocator::size_type,
		unsigned int>::type                           size_type;
	typedef typename detail::if_then_else<
		sizeof(typename Allocator::difference_type)<=sizeof(int),
		typename Allocator::difference_type,
		int>::type                                    difference_type;
	// ctors
	//! constructs an empty pod_vector.
	/*!
	 * \post size() == capacity() == 0
	 */
	pod_vector() : ebo_(0, allocator_type()) { }

	//! constructs an empty pod_vector that uses a copy of a for memory allocations.
	/*!
	 * \post size() == capacity() == 0
	 */
	explicit pod_vector(const allocator_type& a) : ebo_(0, a) { }

	//! constructs a pod_vector containing n copies of value.
	/*!
	 * \post size() == n
	 */
	explicit pod_vector(size_type n, const T& value = T(), const allocator_type& a = allocator_type())
		: ebo_(n, a) {
		detail::fill(ebo_.buf, ebo_.buf + n, value);
		ebo_.size = n;
	}

	//! constructs a pod_vector equal to the range [first, last).
	/*!
	 * \post size() = distance between first and last.
	 */
	template <class Iter>
	pod_vector(Iter first, Iter last, const allocator_type& a = allocator_type(), typename detail::disable_if<detail::IterType<Iter>::num>::type* = 0)
		: ebo_(0, a) {
		insert_range(end(), first, last, typename std::iterator_traits<Iter>::iterator_category());
	}

	//! creates a copy of other
	/*!
	 * \post size() == other.size() && capacity() == other.size()
	 */
	pod_vector(const pod_vector& other) : ebo_(other.size(), other.get_allocator()) {
		std::memcpy(ebo_.buf, other.begin(), other.size()*sizeof(T));
		ebo_.size = other.size();
	}

	pod_vector& operator=(const pod_vector& other) {
		if (this != &other) {
			assign(other.begin(), other.end());
		}
		return *this;
	}

	//! frees all memory allocated by this pod_vector.
	/*!
	 * \note Won't call any destructors, because PODs don't have those.
	 */
	~pod_vector() { }

	/** @name inspectors
	 * inspector-functions
	 */
	//@{

	//! returns the number of elements currently stored in this pod_vector.
	size_type size()     const { return ebo_.size; }
	//! size of the largest possible pod_vector
	size_type max_size() const {
		typename allocator_type::size_type x = get_allocator().max_size();
		std::size_t                        y = size_type(-1)/sizeof(T);
		return static_cast<size_type>(std::min(std::size_t(x), y));
	}
	//! returns the total number of elements this pod_vector can hold without requiring reallocation.
	size_type capacity() const  { return ebo_.cap; }
	//! returns size() == 0
	bool empty() const { return ebo_.size == 0;  }

	const_iterator begin() const { return ebo_.buf; }
	const_iterator end()   const { return ebo_.buf+ebo_.size;}
	const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
	const_reverse_iterator rend()   const { return const_reverse_iterator(begin()); }

	iterator       begin()  { return ebo_.buf; }
	iterator       end()    { return ebo_.buf+ebo_.size; }
	reverse_iterator rbegin() { return reverse_iterator(end()); }
	reverse_iterator rend()   { return reverse_iterator(begin()); }

	//! returns a copy of the allocator used by this pod_vector
	allocator_type get_allocator() const { return ebo_; }

	//@}
	/** @name elemacc
	 * element access
	 */
	//@{

	//! returns a reference to the element at position n
	/*!
	 * \pre n < size()
	 */
	reference operator[](size_type n) {
		assert(n < size());
		return ebo_.buf[n];
	}

	//! returns a reference-to-const to the element at position n
	/*!
	 * \pre n < size()
	 */
	const_reference operator[](size_type n) const {
		assert(n < size());
		return ebo_.buf[n];
	}

	//! same as operator[] but throws std::out_of_range if pre-condition is not met.
	const_reference at(size_type n) const {
		if (n < size()) return ebo_.buf[n];
		throw std::out_of_range("pod_vector::at");
	}
	//! same as operator[] but throws std::out_of_range if pre-condition is not met.
	reference at(size_type n) {
		if (n < size()) return ebo_.buf[n];
		throw std::out_of_range("pod_vector::at");
	}

	//! equivalent to *begin()
	reference front() { assert(!empty()); return *ebo_.buf; }
	//! equivalent to *begin()
	const_reference front() const { assert(!empty()); return *ebo_.buf; }

	//! equivalent to *--end()
	reference back() { assert(!empty()); return ebo_.buf[ebo_.size-1]; }

	//! equivalent to *--end()
	const_reference back() const { assert(!empty()); return ebo_.buf[ebo_.size-1]; }

	//@}
	/** @name mutators
	 * mutator functions
	 */
	//@{

	//! erases all elements in the range [begin(), end)
	/*!
	 * \post size() == 0
	 */
	void clear() { ebo_.size = 0; }

	void assign(size_type n, const T& val) {
		clear();
		insert(end(), n, val);
	}

	template <class Iter>
	void assign(Iter first, Iter last) {
		clear();
		insert(end(), first, last);
	}

	//! erases the element pointed to by pos.
	/*!
	 * \pre pos != end() && !empty()
	 * \return an iterator pointing to the element following pos (before that element was erased)
	 * of end() if no such element exists.
	 *
	 * \note invalidates all iterators and references referring to elements after pos.
	 */
	iterator erase(iterator pos) {
		assert(!empty() && pos != end());
		erase(pos, pos + 1);
		return pos;
	}

	//! erases the elements in the range [first, last)
	/*!
	 * \pre [first, last) must be a valid range.
	 */
	iterator erase(iterator first, iterator last) {
		if (end() - last > 0) {
			std::memmove(first, last, (end() - last) * sizeof(T));
		}
		ebo_.size -= static_cast<size_type>(last - first);
		return first;
	}

	//! adjusts the size of this pod_vector to ns.
	/*!
	 * resize is equivalent to:
	 * if ns > size insert(end(), ns - size(), val)
	 * if ns < size erase(begin() + ns, end())
	 *
	 * \post size() == ns
	 */
	void resize(size_type ns, const T& val = T()) {
		if (ns > size()) {
			ns <= capacity() ? detail::fill(end(), end()+(ns-size()), val) : append_realloc(ns-size(), val);
		}
		ebo_.size = ns;
	}

	//! reallocates storage if necessary but never changes the size() of this pod_vector.
	/*!
	 * \note if n is <= capacity() reserve is a noop. Otherwise a reallocation takes place
	 * and capacity() >= n after reserve returned.
	 * \note reallocation invalidates all references, pointers and iterators referring to
	 * elements in this pod_vectror.
	 *
	 * \note when reallocation occurs elements are copied from the old storage using memcpy.
	 */
	void reserve(size_type n) {
		if (n > capacity()) {
			T* temp = ebo_.allocate(n);
			std::memcpy(temp, ebo_.buf, size()*sizeof(T));
			ebo_.release();
			ebo_.buf = temp;
			ebo_.cap = n;
		}
	}

	void swap(pod_vector& other) {
		std::swap(ebo_.buf, other.ebo_.buf);
		std::swap(ebo_.size, other.ebo_.size);
		std::swap(ebo_.cap, other.ebo_.cap);
	}

	//! equivalent to insert(end(), x);
	void push_back(const T& x) {
		if (size() < capacity()) {
			new ((ebo_.buf+ebo_.size++)) T(x);
		}
		else {
			append_realloc(1, x);
		}
	}

	//! equivalent to erase(--end());
	/*!
	 * \pre !empty()
	 */
	void pop_back() {
		assert(!empty());
		--ebo_.size;
	}

	//! inserts a copy of val before pos.
	/*!
	 * \pre pos is a valid iterator.
	 * \return an iterator pointing to the copy of val that was inserted.
	 * \note if size() + 1 > capacity() reallocation occurs. Otherwise iterators and
	 * references referring to elements before pos remain valid.
	 *
	 */
	iterator insert(iterator pos, const T& val) {
		return insert(pos, (size_type)1, val);
	}

	//! inserts n copies of val before pos.
	/*!
	 * \pre pos is a valid iterator.
	 */
	iterator insert(iterator pos, size_type n, const T& val) {
		size_type off = static_cast<size_type>(pos-begin());
		insert_impl(pos, n, detail::Fill<T>(val));
		return ebo_.buf + off;
	}

	//! inserts copies of elements in the range [first, last) before pos.
	/*!
	 * \pre first and last are not iterators into this pod_vector.
	 * \pre pos is a valid iterator.
	 * \note if first and last are pointers, memcpy is used to insert the elements
	 * in the range [first, last) into this container.
	 *
	 */
	template <class Iter>
	void insert(iterator pos, Iter first, Iter last, typename detail::disable_if<detail::IterType<Iter>::num>::type* = 0) {
		insert_range(pos, first, last, typename std::iterator_traits<Iter>::iterator_category());
	}

	/** @name nonstd
	 * Non-standard interface
	 */
	//@{

	//! adjusts the size of this pod_vector to ns.
	/*!
	 * In contrast to pod_vector::resize this function does not
	 * initializes new elements in case ns > size().
	 * This reflects the behaviour of built-in arrays of pod-types.
	 * \note
	 *  Any access to an unitialized element is illegal unless it is accessed
	 *  in order to assign a new value.
	 */
	void resize_no_init(size_type ns) {
		reserve(ns);
		ebo_.size = ns;
	}
	//@}
private:
	size_type grow_size(size_type n) {
		size_type new_cap = size() + n;
		assert(new_cap > size() && "pod_vector: max size exceeded!");
		assert(new_cap > capacity());
		if (new_cap < 4) new_cap = 1 << (new_cap+1);
		size_type x = (capacity()*3)>>1;
		if (new_cap < x) new_cap = x;
		return new_cap;
	}
	void append_realloc(size_type n, const T& x) {
		size_type new_cap = grow_size(n);
		pointer temp      = ebo_.allocate(new_cap);
		std::memcpy(temp, ebo_.buf, size()*sizeof(T));
		detail::fill(temp+size(), temp+size()+n, x);
		ebo_.release();
		ebo_.buf  = temp;
		ebo_.cap  = new_cap;
		ebo_.size+= n;
	}
	void move_right(iterator pos, size_type n) {
		assert( (pos || n == 0) && (ebo_.eos() - pos) >= (int)n);
		std::memmove(pos + n, pos, (end() - pos) * sizeof(T));
	}
	template <class It>
	void insert_range(iterator pos, It first, It last,  std::random_access_iterator_tag,
		typename detail::disable_if<detail::same_type<pointer, It>::value == 0 && detail::same_type<const_pointer, It>::value == 0>::type* = 0) {
		assert( (first < begin() || first >= end()) && "pod_vec::insert(): Precondition violated!");
		typename allocator_type::difference_type diff = std::distance(first, last);
		assert(diff == 0 || (static_cast<size_type>(size()+diff) > size() && "pod_vector: max size exceeded!"));
		insert_impl(pos, static_cast<size_type>(diff), detail::Memcpy<T>(first));
	}
	template <class It>
	void insert_range(iterator pos, It first, It last,  std::forward_iterator_tag) {
		typename allocator_type::difference_type diff = std::distance(first, last);
		assert(diff == 0 || (static_cast<size_type>(size()+diff) > size() && "pod_vector: max size exceeded!"));
		insert_impl(pos, static_cast<size_type>(diff), detail::Copy<It>(first, last));
	}
	template <class Iter>
	void insert_range(iterator pos, Iter first, Iter last, std::input_iterator_tag) {
		pod_vector<T> temp;
		while (first != last) temp.push_back(*first++);
		insert(pos, temp.begin(), temp.end());
	}

	// NOTE: template parameter ST should always equal size_type
	// and is only needed to workaround an internal compiler error
	// in gcc 3.4.3
	template <class ST, class P>
	void insert_impl(iterator pos, ST n, const P& pred) {
		assert(n == 0 || (size()+n) > size() );
		if (size()+n <= capacity()) {
			move_right(pos, n);
			pred(pos, n);
			ebo_.size += n;
		}
		else {
			size_type new_cap = grow_size(n);
			pointer temp      = ebo_.allocate(new_cap);
			size_type prefix  = static_cast<size_type>(pos-begin());
			// copy prefix
			std::memcpy(temp, begin(), prefix*sizeof(T));
			// insert new stuff
			pred(temp+prefix, n);
			// copy suffix
			std::memcpy(temp+prefix+n, pos, (end()-pos)*sizeof(T));
			ebo_.release();
			ebo_.buf  = temp;
			ebo_.size+= n;
			ebo_.cap  = new_cap;
		}
	}
	struct ebo : public Allocator { // empty-base-optimization
		typedef typename this_type::size_type size_type;
		typedef typename this_type::allocator_type A;
		pointer    buf;  // pointer to array
		size_type  size; // current size (used elements)
		size_type  cap;  // max size before regrow
		ebo(size_type n, const Allocator& a) : Allocator(a), buf(0), size(0), cap(n) {
			if (n > 0) {  buf = A::allocate(n); }
		}
		~ebo()            { release(); }
		void release()    { if (buf) A::deallocate(buf, cap); }
		T*   eos() const  { return buf + cap; }
	}      ebo_;
};

template <class T, class A>
inline bool operator==(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return lhs.size() == rhs.size()
		&& std::equal(lhs.begin(), lhs.end(), rhs.begin());
}

template <class T, class A>
inline bool operator!=(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return ! (lhs == rhs);
}

template <class T, class A>
inline bool operator<(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}

template <class T, class A>
inline bool operator>(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return rhs < lhs;
}

template <class T, class A>
inline bool operator<=(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return !(rhs < lhs);
}

template <class T, class A>
inline bool operator>=(const pod_vector<T, A>& lhs, const pod_vector<T, A>& rhs) {
	return !(lhs < rhs);
}

template <class T, class A>
inline void swap(pod_vector<T, A>& lhs, pod_vector<T, A>& rhs) {
	lhs.swap(rhs);
}

}

#endif


text:
import path from 'path';

const env = process.env.NODE_ENV || 'development';
const config = require(`./${env}`);

// load environment variables

const defaults = {
  root: path.join(__dirname, '/..')
};

export default Object.assign(defaults, config);


text:
package org.apache.camel.scala.dsl

import org.junit.Test
import builder.RouteBuilder
import org.apache.camel.Exchange
import org.junit.Assert._

class RouteErrorHandlerTest extends ScalaTestSupport {

  @Test
  def testRouteHandlerActive {
    "mock:deadLetter" expect {
      _.expectedMessageCount(1)
    }

    test {
      "direct:hasHandler" ! "hello world"
    }

  }

  @Test
  def testContextHandlerStillActive {
    try {
      test {
        "direct:noHandler" ! "hello world"
        fail("Default error handler not used.")
      }
    } catch {
      case _:Exception => {} // pass
    }
  }

  val builder = new RouteBuilder {
    "direct:noHandler" process (causeError _) to "mock:noHandler"

    "direct:hasHandler" errorHandler (deadLetterChannel("mock:deadLetter")) process (causeError _) to "mock:hasHandler"
  }

  def causeError(exch: Exchange) = throw new Exception("Error in route.")
}


text:
// Copyright 2018 Google LLC
//
// 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.google.api.ads.adwords.jaxws.v201809.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Returns a list of {@link CriterionBidLandscape}s for the criteria that match the query. In the
 *             result, the returned {@link LandscapePoint}s are grouped into {@link CriterionBidLandscape}s
 *             by their criteria, and numberResults of paging limits the total number of
 *             {@link LandscapePoint}s instead of number of {@link CriterionBidLandscape}s.
 *
 *             @param query The SQL-like AWQL query string.
 *             @return A list of bid landscapes.
 *             @throws ApiException if problems occur while parsing the query or fetching bid landscapes.
 *
 *
 *
Java class for queryCriterionBidLandscape element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="queryCriterionBidLandscape">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="query" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "query"
})
@XmlRootElement(name = "queryCriterionBidLandscape")
public class DataServiceInterfacequeryCriterionBidLandscape {

    protected String query;

    /**
     * Gets the value of the query property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getQuery() {
        return query;
    }

    /**
     * Sets the value of the query property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setQuery(String value) {
        this.query = value;
    }

}


text:
from bofhexcuse import bofh_excuse

def test_single():
    """make sure it generates a single excuse by default"""
    assert(len(bofh_excuse()) == 1)

def test_ten():
    """make sure it generates 10 excuses if asked"""
    assert(len(bofh_excuse(how_many=10)) == 10)


text:
import React, { PureComponent } from 'react';
import Clear from 'react-material-design-icons/icons/Clear';
import { Direction, NumberPlain, NumberColored, OpenCloseNotice } from 'binary-components';
import { actions } from '../_store';
import WatchlistSparkline from './WatchlistSparkline';

export default class WatchlistItem extends PureComponent {

	props: {
		item: any,
	};

	onRemove = () => {
		const { item } = this.props;
		actions.watchlistToggleAsset(item.get('symbol'), false);
	}

	render() {
		const { item } = this.props;

		return (

					{item.get('assetName')}
					<NumberPlain value={item.get('quote')} digits={item.get('digits')} />

						<Direction diff={item.get('diff')} />

						<NumberColored value={item.get('diff')} digits={item.get('digits')} />

					<Clear className="close-btn" onClick={this.onRemove} />

				{item.get('isOpen') ?
					<WatchlistSparkline history={item.get('history')} /> :
					<OpenCloseNotice isOpen={false} />
				}

		);
	}
}


text:
#include "si.common.h"
#include "si.std.h"
#include "si.window.popup.h"
#include "si.nwcontrol.sbutton.h"
#include "si.window.popupmenu.h"

iPopupMenu::~iPopupMenu()
{
	DestroyPopupMenuContent();
}

void iPopupMenu::InsertMenuItem(const iDib &dib, const iStringT &txt, bool enb)
{
	check((dib.GetSize()==m_ElementSize));

	iNWSimpleButton *btn = new iNWSimpleButton();
	btn->CreateNWSimpleButton(this,m_ElementSize,dib);
	RegisterElement(btn);

	iMenuItem *mitem = new iMenuItem(btn,txt,enb);
	m_Items.Add(mitem);
}

bool iPopupMenu::OnNWMessage( iNWMessage& msg )
{
	if (msg.m_Message == NWMSG_BUTTON_CLICK)
	{
		for (uint32 xx=0; xx<m_Items.GetSize(); ++xx)
		{
			if (msg.m_Element == m_Items[xx]->m_Button)
			{
				m_PopupNotifySubscriber->OnPopupNotify(PWNM_STATUSCHANGED,xx);
				break;
			}
		}
	}
	return true;
}

void iPopupMenu::MsgActivate(bool fActive, bool fMinimized)
{
	iPopupWindow::MsgActivate(fActive,fMinimized);
	if (!fActive)
	{
		m_PopupNotifySubscriber->OnPopupNotify(PWNM_DEACTIVATED,0);
	}
}

void iPopupMenu::HidePopupMenu()
{
	ShowWindow(SW_HIDE);
}

void iPopupMenu::ShowPopupMenu(const iPoint &pos, iAlignment algn)
{
	if (m_Items.GetSize() == 0) return;

	iRect nrect(0,0,0,0);

	for (uint32 xx=0; xx< m_Items.GetSize(); ++xx)
	{
		m_Items[xx]->m_Button->SetElementPos(iPoint(nrect.w,0));
		nrect.w += m_Items[xx]->m_Button->GetElementRect().w;
		nrect.h = iMAX(nrect.h,m_Items[xx]->m_Button->GetElementRect().h);
	}

	nrect.y = pos.y-nrect.h;
	nrect.x = pos.x - nrect.w/2;

	iSize ssize = iWindowManager::GetScreenSize();

	if (nrect.x<0) nrect.x=0;
	else if (nrect.x2() > (sint32)ssize.w) nrect.x = ssize.w - nrect.w;

	if (nrect.y<0) nrect.y=0;
	else if (nrect.y2() > (sint32)ssize.h) nrect.y = ssize.h - nrect.h;

	SetWndRect(nrect);

	ShowWindow(SW_SHOW);
	SetActiveWindow();
}

void iPopupMenu::DrawBackground(iDib &odib, const iRect &rect)
{
	// Erase rect
	odib.Fill(iColor(0,0,0,0),BLEND_SRCCOPY);
}

bool iPopupMenu::InitPopupMenu(iPopupNotifySubscriber *pwns, const iStringT &capt, const iSize &elsiz)
{
	m_Caption = capt;
	m_ElementSize = elsiz;

	if (!CreatePopupWindow(pwns,iRect(0,0,elsiz.w,elsiz.h))) return false;
	AddMessageSubscriber(this);

	return true;
}

const iMenuItem* iPopupMenu::GetItem(uint32 item) const
{
	return m_Items[item];
}


text:
using System;
using System.Globalization;
using System.Windows.Data;

namespace MvvX.Plugins.OAuthClient
{
    /// <summary>
    /// Source code : https://github.com/MrMitch/WPF-Loaders.git
    /// Applies a linear function to the value passed as a parameter.
    /// f(x) = a*x + b
    /// </summary>
    internal class LinearConverter : IValueConverter
    {
        public double A { get; set; } = 1;
        public double B { get; set; } = 0;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => A * System.Convert.ToInt32(value) + B;

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => (System.Convert.ToInt32(value) - B) / A;
    }
}


text:
<?php

/**
 * Добавляет блок(в сайдбар, тулбар и т.п.)
 *
 * @param   $params
 * @param   $smarty
 */
function smarty_function_add_block($params, &$smarty) {

    if (!array_key_exists('group', $params)) {
        trigger_error("add_block: missing 'group' parameter", E_USER_WARNING);
        return;
    }

    if (!array_key_exists('name', $params)) {
        trigger_error("add_block: missing 'name' parameter", E_USER_WARNING);
        return;
    }

    $aBlockParams = (isset($params['params']) && is_array($params['params'])) ? $params['params'] : array();
    $iPriority = isset($params['priority']) ? $params['priority'] : 5;

    foreach ($params as $k => $v) {
        if (!in_array($k, array('group', 'name', 'params', 'priority'))) {
            $aBlockParams[$k] = $v;
        }
    }

    Engine::getInstance()->Viewer_AddWidget($params['group'], $params['name'], $aBlockParams, $iPriority);
}

// EOF


text:
<?php

require __DIR__.'/../vendor/autoload.php';

$converter = new Locurro\Converter\IpAddress(
    new Locurro\Converter\Country(
        new Locurro\Converter\Locale(
            new Locurro\Converter\Currency(
                new Swap\Swap(
                    new Swap\Provider\YahooFinanceProvider(
                        new Ivory\HttpAdapter\FileGetContentsHttpAdapter()
                    ),
                    new Swap\Cache\DoctrineCache(new Doctrine\Common\Cache\FilesystemCache(__DIR__.'/../cache'), 60)
                )
            )
        )
    ),
    new Geocoder\Provider\GeoIP2(
        new Geocoder\Adapter\GeoIP2Adapter(
            new GeoIp2\Database\Reader(__DIR__.'/../data/GeoLite2-Country.mmdb'),
            Geocoder\Adapter\GeoIP2Adapter::GEOIP2_MODEL_COUNTRY
        )
    )
);

$money = $converter->convert(
    new Money\Money(100, new Money\Currency('EUR')),
    '109.92.115.78'
);

var_dump($money);


text:
use bytemuck::{Pod, Zeroable};
use cgmath::Vector3;
use std::sync::Arc;
use vulkano::{
    buffer::{BufferUsage, CpuAccessibleBuffer, TypedBufferAccess},
    command_buffer::{
        allocator::StandardCommandBufferAllocator, AutoCommandBufferBuilder,
        CommandBufferInheritanceInfo, CommandBufferUsage, SecondaryAutoCommandBuffer,
    },
    descriptor_set::{
        allocator::StandardDescriptorSetAllocator, PersistentDescriptorSet, WriteDescriptorSet,
    },
    device::Queue,
    image::ImageViewAbstract,
    impl_vertex,
    memory::allocator::MemoryAllocator,
    pipeline::{
        graphics::{
            color_blend::{AttachmentBlend, BlendFactor, BlendOp, ColorBlendState},
            input_assembly::InputAssemblyState,
            vertex_input::BuffersDefinition,
            viewport::{Viewport, ViewportState},
        },
        GraphicsPipeline, Pipeline, PipelineBindPoint,
    },
    render_pass::Subpass,
};

/// Allows applying a directional light source to a scene.
pub struct DirectionalLightingSystem {
    gfx_queue: Arc<Queue>,
    vertex_buffer: Arc<CpuAccessibleBuffer<[Vertex]>>,
    subpass: Subpass,
    pipeline: Arc<GraphicsPipeline>,
    command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
    descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
}

impl DirectionalLightingSystem {
    /// Initializes the directional lighting system.
    pub fn new(
        gfx_queue: Arc<Queue>,
        subpass: Subpass,
        memory_allocator: &impl MemoryAllocator,
        command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
        descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
    ) -> DirectionalLightingSystem {
        // TODO: vulkano doesn't allow us to draw without a vertex buffer, otherwise we could
        //       hard-code these values in the shader
        let vertices = [
            Vertex {
                position: [-1.0, -1.0],
            },
            Vertex {
                position: [-1.0, 3.0],
            },
            Vertex {
                position: [3.0, -1.0],
            },
        ];
        let vertex_buffer = {
            CpuAccessibleBuffer::from_iter(
                memory_allocator,
                BufferUsage::VERTEX_BUFFER,
                false,
                vertices,
            )
            .expect("failed to create buffer")
        };

        let pipeline = {
            let vs = vs::load(gfx_queue.device().clone()).expect("failed to create shader module");
            let fs = fs::load(gfx_queue.device().clone()).expect("failed to create shader module");

            GraphicsPipeline::start()
                .vertex_input_state(BuffersDefinition::new().vertex::<Vertex>())
                .vertex_shader(vs.entry_point("main").unwrap(), ())
                .input_assembly_state(InputAssemblyState::new())
                .viewport_state(ViewportState::viewport_dynamic_scissor_irrelevant())
                .fragment_shader(fs.entry_point("main").unwrap(), ())
                .color_blend_state(ColorBlendState::new(subpass.num_color_attachments()).blend(
                    AttachmentBlend {
                        color_op: BlendOp::Add,
                        color_source: BlendFactor::One,
                        color_destination: BlendFactor::One,
                        alpha_op: BlendOp::Max,
                        alpha_source: BlendFactor::One,
                        alpha_destination: BlendFactor::One,
                    },
                ))
                .render_pass(subpass.clone())
                .build(gfx_queue.device().clone())
                .unwrap()
        };

        DirectionalLightingSystem {
            gfx_queue,
            vertex_buffer,
            subpass,
            pipeline,
            command_buffer_allocator,
            descriptor_set_allocator,
        }
    }

    /// Builds a secondary command buffer that applies directional lighting.
    ///
    /// This secondary command buffer will read `color_input` and `normals_input`, and multiply the
    /// color with `color` and the dot product of the `direction` with the normal.
    /// It then writes the output to the current framebuffer with additive blending (in other words
    /// the value will be added to the existing value in the framebuffer, and not replace the
    /// existing value).
    ///
    /// Since `normals_input` contains normals in world coordinates, `direction` should also be in
    /// world coordinates.
    ///
    /// - `viewport_dimensions` contains the dimensions of the current framebuffer.
    /// - `color_input` is an image containing the albedo of each object of the scene. It is the
    ///   result of the deferred pass.
    /// - `normals_input` is an image containing the normals of each object of the scene. It is the
    ///   result of the deferred pass.
    /// - `direction` is the direction of the light in world coordinates.
    /// - `color` is the color to apply.
    ///
    pub fn draw(
        &self,
        viewport_dimensions: [u32; 2],
        color_input: Arc<dyn ImageViewAbstract + 'static>,
        normals_input: Arc<dyn ImageViewAbstract + 'static>,
        direction: Vector3<f32>,
        color: [f32; 3],
    ) -> SecondaryAutoCommandBuffer {
        let push_constants = fs::ty::PushConstants {
            color: [color[0], color[1], color[2], 1.0],
            direction: direction.extend(0.0).into(),
        };

        let layout = self.pipeline.layout().set_layouts().get(0).unwrap();
        let descriptor_set = PersistentDescriptorSet::new(
            &self.descriptor_set_allocator,
            layout.clone(),
            [
                WriteDescriptorSet::image_view(0, color_input),
                WriteDescriptorSet::image_view(1, normals_input),
            ],
        )
        .unwrap();

        let viewport = Viewport {
            origin: [0.0, 0.0],
            dimensions: [viewport_dimensions[0] as f32, viewport_dimensions[1] as f32],
            depth_range: 0.0..1.0,
        };

        let mut builder = AutoCommandBufferBuilder::secondary(
            &self.command_buffer_allocator,
            self.gfx_queue.queue_family_index(),
            CommandBufferUsage::MultipleSubmit,
            CommandBufferInheritanceInfo {
                render_pass: Some(self.subpass.clone().into()),
                ..Default::default()
            },
        )
        .unwrap();
        builder
            .set_viewport(0, [viewport])
            .bind_pipeline_graphics(self.pipeline.clone())
            .bind_descriptor_sets(
                PipelineBindPoint::Graphics,
                self.pipeline.layout().clone(),
                0,
                descriptor_set,
            )
            .push_constants(self.pipeline.layout().clone(), 0, push_constants)
            .bind_vertex_buffers(0, self.vertex_buffer.clone())
            .draw(self.vertex_buffer.len() as u32, 1, 0, 0)
            .unwrap();
        builder.build().unwrap()
    }
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Zeroable, Pod)]
struct Vertex {
    position: [f32; 2],
}
impl_vertex!(Vertex, position);

mod vs {
    vulkano_shaders::shader! {
        ty: "vertex",
        src: "
#version 450

layout(location = 0) in vec2 position;

void main() {
    gl_Position = vec4(position, 0.0, 1.0);
}"
    }
}

mod fs {
    vulkano_shaders::shader! {
        ty: "fragment",
        src: "
#version 450

// The `color_input` parameter of the `draw` method.
layout(input_attachment_index = 0, set = 0, binding = 0) uniform subpassInput u_diffuse;
// The `normals_input` parameter of the `draw` method.
layout(input_attachment_index = 1, set = 0, binding = 1) uniform subpassInput u_normals;

layout(push_constant) uniform PushConstants {
    // The `color` parameter of the `draw` method.
    vec4 color;
    // The `direction` parameter of the `draw` method.
    vec4 direction;
} push_constants;

layout(location = 0) out vec4 f_color;

void main() {
    vec3 in_normal = normalize(subpassLoad(u_normals).rgb);
    // If the normal is perpendicular to the direction of the lighting, then `light_percent` will
    // be 0. If the normal is parallel to the direction of the lightin, then `light_percent` will
    // be 1. Any other angle will yield an intermediate value.
    float light_percent = -dot(push_constants.direction.xyz, in_normal);
    // `light_percent` must not go below 0.0. There's no such thing as negative lighting.
    light_percent = max(light_percent, 0.0);

    vec3 in_diffuse = subpassLoad(u_diffuse).rgb;
    f_color.rgb = light_percent * push_constants.color.rgb * in_diffuse;
    f_color.a = 1.0;
}",
        types_meta: {
            use bytemuck::{Pod, Zeroable};

            #[derive(Clone, Copy, Zeroable, Pod)]
        },
    }
}


text:
namespace RA.Extensions
{
    public static class StringExtensions
    {
        public static bool IsEmpty(this string source)
        {
            return string.IsNullOrEmpty(source);
        }

        public static bool IsNotEmpty(this string source)
        {
            return !string.IsNullOrEmpty(source);
        }

        public static string Quote(this string source)
        {
            return "\"" + source + "\"";
        }
    }
}