text:
/* jshint indent: 2 */

import DataTypes from 'sequelize';
import Model from '../sequelize';

const merchandise = Model.define('merchandise', {
  id: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: DataTypes.STRING(30),
    allowNull: false,
  },
  type: {
    type: DataTypes.STRING(30),
    allowNull: true,
  },
  cost: {
    type: DataTypes.INTEGER(11),
    allowNull: true,
  },
}, {
  tableName: 'merchandise',
});

export default merchandise;

redpajama_set_name: RedPajamaGithub


text:
import axios from 'axios';
import Papa from 'papaparse';

import { DEBUG_FETCH } from '@/constants/api';

interface GithubFileApiResponse {
  size: number;
  download_url: string;
}

export const fetchJson = async <T>({ url }: { url: string }): Promise<T> => {
  try {
    const response = await fetch(url);
    if (response.status >= 200 && response.status < 300) {
      const data = (await response.json()) as T;
      await new Promise((res) => setTimeout(res, 2000));
      return data;
    }
    throw Error(`HTTP Status ${response.status}`);
  } catch (error) {
    console.error(error);
    return Promise.reject(error);
  }
};

export const fetchCsvWithProgress = async <T>({
  path,
  setProgress,
}: {
  path: string;
  setProgress: (progress: number) => void;
}): Promise<T[]> => {
  setProgress(0);

  // Github API
  // https://api.github.com/repos/grumd/osu-pps/contents/data/maps/osu/diffs.csv?ref=data
  const apiResponse = DEBUG_FETCH
    ? { data: { size: 1, download_url: `/${path}` } }
    : await axios.get<GithubFileApiResponse>(
        `https://api.github.com/repos/grumd/osu-pps/contents/${path}?ref=data`
      );
  const contentSize = apiResponse.data.size;
  const downloadUrl = apiResponse.data.download_url;

  setProgress(0.1);

  const response = await axios.get<string>(downloadUrl, {
    responseType: 'text',
    onDownloadProgress: (progressEvent: { loaded: number }) => {
      // Math.min for the sanity check, just in case downloaded content is bigger than contentSize
      setProgress(Math.min(0.9, (progressEvent.loaded / contentSize) * 0.8 + 0.1));
    },
  });

  setProgress(0.9);

  const parsed = await new Promise<T[]>((resolve) => {
    Papa.parse<T>(response.data, {
      header: true,
      dynamicTyping: true,
      worker: true,
      complete: (result) => {
        resolve(result.data);
      },
    });
  });

  setProgress(1);

  return parsed;
};

export const fetchCsv = async <T>({ url }: { url: string }): Promise<T[]> => {
  try {
    const response = await fetch(url);
    if (response.status >= 200 && response.status < 300) {
      const text = await response.text();
      const parsePromise = new Promise<T[]>((resolve) => {
        Papa.parse<T>(text, {
          header: true,
          dynamicTyping: true,
          worker: true,
          complete: (result) => {
            resolve(result.data);
          },
        });
      });

      return await parsePromise;
    }
    throw Error(`HTTP Status ${response.status}`);
  } catch (error) {
    console.error(error);
    return Promise.reject(error);
  }
};


text:
@implementation PopupViewController1
{
    UILabel *_label;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.title = @"Apple";
        self.contentSizeInPopup = CGSizeMake(300, 400);
        self.landscapeContentSizeInPopup = CGSizeMake(400, 200);
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStylePlain target:self action:@selector(nextBtnDidTap)];

    _label = [UILabel new];
    _label.numberOfLines = 0;
    _label.text = @"Apple Inc. (commonly known as Apple) is an American multinational technology company headquartered in Cupertino, California, that designs, develops, and sells consumer electronics, computer software, and online services. Its best-known hardware products are the Mac personal computers, the iPod portable media player, the iPhone smartphone, the iPad tablet computer, and the Apple Watch smartwatch. Apple's consumer software includes the OS X and iOS operating systems, the iTunes media player, the Safari web browser, and the iLife and iWork creativity and productivity suites. Its online services include the iTunes Store, the iOS App Store and Mac App Store, and iCloud.";
    [self.view addSubview:_label];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    _label.frame = CGRectMake(20, 10, self.view.frame.size.width - 40, self.view.frame.size.height - 20);
}

- (void)nextBtnDidTap
{
    [self.popupController pushViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PopupViewController2"] animated:YES];
}

@end


text:
<?php

namespace App;

/**
 * Theme customizer
 */
add_action('customize_register', function (\WP_Customize_Manager $wp_customize) {
    // Add postMessage support
    $wp_customize->get_setting('blogname')->transport = 'postMessage';
    $wp_customize->get_setting('blogdescription')->transport = 'postMessage';
    $wp_customize->selective_refresh->add_partial('blogname', [
        'selector' => '.brand-name',
        'render_callback' => function () {
            bloginfo('name');
        }
    ]);
    $wp_customize->selective_refresh->add_partial('blogdescription', [
        'selector' => '.brand-description',
        'render_callback' => function () {
            bloginfo('description');
        }
    ]);
});

/**
 * Customizer JS
 */
add_action('customize_preview_init', function () {
    wp_enqueue_script('sage/customizer.js', asset_path('scripts/customizer.js'), ['customize-preview'], null, true);
});


text:
package nonimmutables;

import org.immutables.value.Value;

@Value.Immutable
public interface HasUmlauts {
  int getZahlungsempfänger();
}


text:
#include "ir/intrinsics.h"
#include "wasm-builder.h"

namespace wasm {

static Name BinaryenIntrinsicsModule("binaryen-intrinsics"),
  CallWithoutEffects("call.without.effects");

bool Intrinsics::isCallWithoutEffects(Function* func) {
  if (func->module != BinaryenIntrinsicsModule) {
    return false;
  }
  if (func->base == CallWithoutEffects) {
    return true;
  }
  Fatal() << "Unrecognized intrinsic";
}

Call* Intrinsics::isCallWithoutEffects(Expression* curr) {
  if (auto* call = curr->dynCast<Call>()) {
    // The target function may not exist if the module is still being
    // constructed.
    if (auto* func = module.getFunctionOrNull(call->target)) {
      if (isCallWithoutEffects(func)) {
        return call;
      }
    }
  }
  return nullptr;
}

} // namespace wasm


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"/>

    <link type="text/css" href="$context/css/simplepage-theme/jquery-ui-1.11.1.smoothness.css" rel="stylesheet" />
    <link rsf:id="scr=portal-matter" href="/library/skin/tool_base.css" type="text/css" rel="stylesheet" media="all" />
    <link rsf:id="scr=portal-matter" href="/library/skin/default/tool.css" type="text/css" rel="stylesheet" media="all" />
    <link rel="stylesheet" rsf:id="scr=rewrite-url" href="../css/Simplepagetool.css" type="text/css"/>
    <link rel="stylesheet" rsf:id="scr=rewrite-url" href="../css/checklist.css" type="text/css"/>
    <link rel="stylesheet" rsf:id="customCSS" type="text/css" />

    <title rsf:id="msg=simplepage.checklist"></title>

 junk

    <form rsf:id="page_form" class="checklistForm">
        <input type="hidden" rsf:id="csrf"/>
	<input type="hidden" rsf:id="add-before" id="add-before" />

Enter your page content below

                *

                <input rsf:id="name" id="name" />

                <input type="checkbox" rsf:id="isNameHidden" id="isNameHidden" class="hideNameCheckbox"/>

                <textarea rsf:id="description" id="description"></textarea>

            <input type="hidden" rsf:id="attributeString" id="attributeString"/>

            <fieldset>
                <legend class="no-border">

</legend>

                        <input type="hidden" rsf:id="checklist-item-complete" />
                        <input type="hidden" rsf:id="checklist-item-id" class="checklist-item-id" />

                        <input type="text" rsf:id="checklist-item-name" name="checklist-item-name" class="checklist-item-name" />

                <button onclick="checklist.addChecklistItem(); return false;" rsf:id="msg=simplepage.addChecklistItem" id="addChecklistItemButton"/>
            </fieldset>

                    <select rsf:id="indent-level" name="indent-level" id="indent-level"/>

                    <input rsf:id="customCssClass" type="text" id="customCssClass" length="30" maxlength="99" class="edit-form-input"/>

                    <input type="checkbox" rsf:id="select-group" /><input type="checkbox" rsf:id="select-group-checked" checked="checked" />

            <input accesskey ="s" rsf:id="save" value="Save" type="submit" class="active" onclick="return checklist.validateChecklistForm();" />
            <input accesskey ="x" rsf:id="cancel" value="Cancel" type="submit"/>
            <input type="submit" rsf:id="delete" class="deleteButton" />

    </form>


text:
package package_creator_by_reader

import (
	"testing"

	. "github.com/bborbe/assert"
)

func TestImplementsDebianPackageCreator(t *testing.T) {
	b := New(nil, nil, nil)
	var i *Creator
	err := AssertThat(b, Implements(i).Message("check type"))
	if err != nil {
		t.Fatal(err)
	}
}

func TestJoinDirsOne(t *testing.T) {
	if err := AssertThat(joinDirs("/tmp"), Is("/tmp")); err != nil {
		t.Fatal(err)
	}
}

func TestJoinDirsTwo(t *testing.T) {
	if err := AssertThat(joinDirs("/tmp", "sub"), Is("/tmp/sub")); err != nil {
		t.Fatal(err)
	}
}

func TestJoinDirsOneEmpty(t *testing.T) {
	if err := AssertThat(joinDirs("/tmp", ""), Is("/tmp")); err != nil {
		t.Fatal(err)
	}
}


text:
#include "Python.h"
#include "pyobjc-api.h"
#include <stdarg.h>

#import <Foundation/Foundation.h>

struct ArrayStruct {
	int first;
	int second;
};

typedef int int_array_t[4];
typedef struct ArrayStruct struct_array_t[4];

@interface OC_ArrayTest : NSObject
{
}
#if 0
	/* It seems to be impossible to return C arrays */
+(int_array_t)arrayOf4Integers;
+(struct_array_t)arrayOf4Structs;
#endif

-(NSObject*)arrayOf4Ints:(int_array_t)array;
-(NSObject*)arrayOf4IntsIn:(in int_array_t)array;
-(NSObject*)arrayOf4IntsInOut:(inout int_array_t)array;
-(void)arrayOf4IntsOut:(out int_array_t)array;

-(NSObject*)arrayOf4Structs:(struct_array_t)array;
-(NSObject*)arrayOf4StructsIn:(in struct_array_t)array;
-(NSObject*)arrayOf4StructsInOut:(inout struct_array_t)array;
-(void)arrayOf4StructsOut:(out struct_array_t)array;

+(NSObject*)callArrayOf4Ints:(OC_ArrayTest*)object;
+(NSObject*)callArrayOf4IntsOut:(OC_ArrayTest*)object;
+(NSObject*)callArrayOf4Structs:(OC_ArrayTest*)object;
+(NSObject*)callArrayOf4StructsOut:(OC_ArrayTest*)object;
@end

@implementation OC_ArrayTest

#if 0
	/* These don't compile for some reason */
+(int_array_t)arrayOf4Integers;
{
static int_array_t gValue = { 4, 5, 6, 7 };
	return gValue;
}
+(struct_array_t)arrayOf4Structs
{
static struct_array_t gValue = {
		{ 9, 10 },
		{ 12, 13 },
		{ 21, 24 },
		{ -1, -2 },
	};
	return gValue;
}
#endif

-(NSObject*)arrayOf4Ints:(int_array_t)array
{
	return [NSArray arrayWithObjects:
		[NSNumber numberWithInt:array[0]],
		[NSNumber numberWithInt:array[1]],
		[NSNumber numberWithInt:array[2]],
		[NSNumber numberWithInt:array[3]],
		nil];
}
-(NSObject*)arrayOf4IntsIn:(in int_array_t)array
{
	return [NSArray arrayWithObjects:
		[NSNumber numberWithInt:array[0]],
		[NSNumber numberWithInt:array[1]],
		[NSNumber numberWithInt:array[2]],
		[NSNumber numberWithInt:array[3]],
		nil];
}
-(NSObject*)arrayOf4IntsInOut:(inout int_array_t)array
{
	NSObject* result = [NSArray arrayWithObjects:
		[NSNumber numberWithInt:array[0]],
		[NSNumber numberWithInt:array[1]],
		[NSNumber numberWithInt:array[2]],
		[NSNumber numberWithInt:array[3]],
		nil];

	array[0] += 42;
	array[1] += 42;
	array[2] += 42;
	array[3] += 42;

	return result;
}
-(void)arrayOf4IntsOut:(out int_array_t)array
{
	array[0] = 99;
	array[1] = 100;
	array[2] = 102;
	array[3] = 110;
}

-(NSObject*)arrayOf4Structs:(struct_array_t)array
{
	return [NSArray arrayWithObjects:
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[0].first],
				[NSNumber numberWithInt:array[0].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[1].first],
				[NSNumber numberWithInt:array[1].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[2].first],
				[NSNumber numberWithInt:array[2].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[3].first],
				[NSNumber numberWithInt:array[3].second],
				nil],
			nil
		];
}
-(NSObject*)arrayOf4StructsIn:(in struct_array_t)array
{
	return [NSArray arrayWithObjects:
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[0].first],
				[NSNumber numberWithInt:array[0].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[1].first],
				[NSNumber numberWithInt:array[1].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[2].first],
				[NSNumber numberWithInt:array[2].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[3].first],
				[NSNumber numberWithInt:array[3].second],
				nil],
			nil
		];
}
-(NSObject*)arrayOf4StructsInOut:(inout struct_array_t)array
{
	NSObject* result = [NSArray arrayWithObjects:
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[0].first],
				[NSNumber numberWithInt:array[0].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[1].first],
				[NSNumber numberWithInt:array[1].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[2].first],
				[NSNumber numberWithInt:array[2].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[3].first],
				[NSNumber numberWithInt:array[3].second],
				nil],
			nil
		];

	int i;
	for (i = 0; i < 4; i++) {
		array[i].first += 42;
		array[i].second -= 42;
	}

	return result;
}
-(void)arrayOf4StructsOut:(out struct_array_t)array
{
	int i;
	for (i = 0; i < 4; i++) {
		array[i].first = 1 + i * i;
		array[i].second = -4 - i * i * i;
	}
}

+(NSObject*)callArrayOf4Ints:(OC_ArrayTest*)object
{
	int_array_t array = { 1, 2, 3, 4 };
	return [object arrayOf4Ints:array];
}

+(NSObject*)callArrayOf4IntsOut:(OC_ArrayTest*)object
{
	int_array_t array;
	[object arrayOf4IntsOut:array];
	return [NSArray arrayWithObjects:
			[NSNumber numberWithInt: array[0]],
			[NSNumber numberWithInt: array[1]],
			[NSNumber numberWithInt: array[2]],
			[NSNumber numberWithInt: array[3]],
			nil];
}

+(NSObject*)callArrayOf4Structs:(OC_ArrayTest*)object
{
	struct_array_t array = {
		{ 1, 2 },
		{ 3, 4 },
		{ 5, 6 },
		{ 7, 8 }
	};
	return [object arrayOf4Structs:array];
}

+(NSObject*)callArrayOf4StructsOut:(OC_ArrayTest*)object
{
	struct_array_t array;
	[object arrayOf4StructsOut:array];

	return [NSArray arrayWithObjects:
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[0].first],
				[NSNumber numberWithInt:array[0].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[1].first],
				[NSNumber numberWithInt:array[1].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[2].first],
				[NSNumber numberWithInt:array[2].second],
				nil],
			[NSArray arrayWithObjects:
				[NSNumber numberWithInt:array[3].first],
				[NSNumber numberWithInt:array[3].second],
				nil],
			nil
		];
}
@end

static PyMethodDef mod_methods[] = {
	        { 0, 0, 0, 0 }
};

#if PY_VERSION_HEX >= 0x03000000

static struct PyModuleDef mod_module = {
	PyModuleDef_HEAD_INIT,
	"arrays",
	NULL,
	0,
	mod_methods,
	NULL,
	NULL,
	NULL,
	NULL
};

#define INITERROR() return NULL
#define INITDONE() return m

PyObject* PyInit_arrays(void);

PyObject*
PyInit_arrays(void)

#else

#define INITERROR() return
#define INITDONE() return

void initarrays(void);

void
initarrays(void)
#endif
{
	PyObject* m;

#if PY_VERSION_HEX >= 0x03000000
	m = PyModule_Create(&mod_module);
#else
	m = Py_InitModule4("arrays", mod_methods,
		NULL, NULL, PYTHON_API_VERSION);
#endif
	if (!m) {
		INITERROR();
	}

	PyObjC_ImportAPI(m);

	if (PyModule_AddObject(m, "OC_ArrayTest",
		PyObjCClass_New([OC_ArrayTest class])) < 0) {
		INITERROR();
	}

	INITDONE();
}


text:
require 'test_helper'

describe Hanami::Routes do
  before do
    @scheme   = 'https'
    @host     = 'hanamirb.org'
    @port     = 443
    @original = Hanami::Router.new(scheme: @scheme, host: @host, port: @port) do
      get '/', as: :root
    end

    @routes = Hanami::Routes.new(@original)
  end

  describe '#path' do
    it 'returns a path for the given name' do
      @routes.path(:root).must_equal '/'
    end

    it 'raises an error when the path cannot be found' do
      -> { @routes.path(:unknown) }.must_raise Hanami::Routing::InvalidRouteException
    end

    it 'returns safe string' do
      @routes.path(:root).must_be_kind_of Hanami::Utils::Escape::SafeString
    end
  end

  describe '#url' do
    it 'returns a url for the given name' do
      @routes.url(:root).must_equal "#{ @scheme }://#{ @host }/"
    end

    it 'raises an error when the url cannot be found' do
      -> { @routes.url(:unknown) }.must_raise Hanami::Routing::InvalidRouteException
    end

    it 'returns safe string' do
      @routes.url(:root).must_be_kind_of Hanami::Utils::Escape::SafeString
    end
  end

  describe '#recognize' do
    it 'recognizes a route from a Rack env' do
      env   = Rack::MockRequest.env_for('/')
      route = @routes.recognize(env)

      route.must_be :routable?

      route.path.must_equal '/'
      route.verb.must_equal 'GET'
      route.params.must_equal({})
    end

    it 'does not recognizes a route from wrong Rack env' do
      env   = Rack::MockRequest.env_for('/foo')
      route = @routes.recognize(env)

      route.wont_be :routable?
    end
  end

  describe 'dynamic finders' do
    describe 'for relative URLs' do
      it 'recognizes named route' do
        @routes.root_path.must_equal '/'
      end

      it "raises an error if an unknown path is invoked" do
        -> { @routes.unknown_path }.must_raise Hanami::Routing::InvalidRouteException
      end
    end

    describe 'for absolute URLs' do
      it 'recognizes named route' do
        @routes.root_url.must_equal "#{ @scheme }://#{ @host }/"
      end

      it "raises an error if an unknown url is invoked" do
        -> { @routes.unknown_url }.must_raise Hanami::Routing::InvalidRouteException
      end
    end

    it 'raises an error for unknown methods' do
      -> { @routes.foo }.must_raise NoMethodError
    end
  end
end


text:
id: 5690307fddb111c6084545d7
title: Logical Order in If Else Statements
challengeType: 1
videoUrl: https://scrimba.com/c/cwNvMUV
forumTopicId: 18228
localeTitle: Логический порядок в остальных случаях
---

## Description

Порядок важен в if , else if . Функция выполняется сверху вниз, поэтому вы хотите быть осторожным с тем, что должно быть сделано первым. Возьмем эти две функции в качестве примера. Вот первый:
 функция foo (x) {
 если (x <1) {
 return «Меньше одного»;
 } else if (x <2) {
 return «Меньше двух»;
 } else {
 return «Больше или равно двум»;
 }
 }
 А второй просто переключает порядок утверждений:
 функциональная панель (x) {
 если (x <2) {
 return «Меньше двух»;
 } else if (x <1) {
 return «Меньше одного»;
 } else {
 return «Больше или равно двум»;
 }
 }
 Хотя эти две функции выглядят почти одинаковыми, если мы передаем число для обоих, мы получаем разные выходы.
 foo (0) // «Меньше одного»
 bar (0) // «Менее двух»

## Instructions

Измените порядок логики в функции так, чтобы она вернула правильные утверждения во всех случаях.

## Tests

```yml
tests:
  - text: <code>orderMyLogic(4)</code> should return "Less than 5"
    testString: assert(orderMyLogic(4) === "Less than 5");
  - text: <code>orderMyLogic(6)</code> should return "Less than 10"
    testString: assert(orderMyLogic(6) === "Less than 10");
  - text: <code>orderMyLogic(11)</code> should return "Greater than or equal to 10"
    testString: assert(orderMyLogic(11) === "Greater than or equal to 10");

```

## Challenge Seed

```js
function orderMyLogic(val) {
  if (val < 10) {
    return "Less than 10";
  } else if (val < 5) {
    return "Less than 5";
  } else {
    return "Greater than or equal to 10";
  }
}

// Change this value to test
orderMyLogic(7);

```

## Solution

```js
function orderMyLogic(val) {
  if(val < 5) {
    return "Less than 5";
  } else if (val < 10) {
    return "Less than 10";
  } else {
    return "Greater than or equal to 10";
  }
}
```


text:
package fi.csc.chipster.comp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import fi.csc.chipster.comp.ToolDescription.OutputDescription;

/**
 * Provides functionality for transferring input files from file broker to job
 * work directory and output files from job work directory to file broker.
 *
 */
public abstract class OnDiskCompJobBase extends CompJob {

	private static Logger logger = LogManager.getLogger();

	private static final String JOB_DATA_DIR_NAME = "data";
	private static final String JOB_TOOLBOX_DIR_NAME = "toolbox";

	protected File jobDir;
	protected File jobDataDir;
	protected File jobToolboxDir;

	@Override
	public void construct(GenericJobMessage inputMessage, ToolDescription toolDescription, ResultCallback resultHandler,
			int jobTimeout) {
		super.construct(inputMessage, toolDescription, resultHandler, jobTimeout);
		this.jobDir = new File(resultHandler.getWorkDir(), getId());
		this.jobDataDir = new File(this.jobDir, JOB_DATA_DIR_NAME);
		this.jobToolboxDir = new File(this.jobDir, JOB_TOOLBOX_DIR_NAME);
	}

	/**
	 * Copy input files from file broker to job work directory.
	 *
	 * @throws JobCancelledException
	 *
	 */
	@Override
	protected void preExecute() throws JobCancelledException {
		cancelCheck();
		super.preExecute();

		updateState(JobState.RUNNING, "transferring input data");

		// create directories for the job
		if (!this.jobDir.mkdir()) {
			this.setErrorMessage("Creating job working directory failed.");
			updateState(JobState.ERROR);
			return;
		}

		// get input files and toolbox
		try {
			// input files
			getInputFiles();

			// toolbox
			if (!this.jobToolboxDir.mkdir()) {
				throw new IOException("Creating job toolbox dir failed.");
			}
			resultHandler.getToolboxClient().getToolboxModules(this.jobToolboxDir);

		} catch (Exception e) {
			this.setErrorMessage("Transferring input data and tools to computing service failed.");
			this.setOutputText(Exceptions.getStackTrace(e));
			logger.error("transferring input data and tools failed", e);
			updateState(JobState.ERROR);
			return;
		}
	}

	/**
	 * Copy output files from job work dir to file broker.
	 *
	 */
	@Override
	protected void postExecute() throws JobCancelledException {
		// update job state on the client side
		updateState(JobState.RUNNING, "transferring output data");
		cancelCheck();

		// get phenodata file // FIXME add support for multiple phenodata outputs
		File phenodataFile = null;
		for (OutputDescription outputDescription : toolDescription.getOutputFiles()) {
			if (outputDescription.isMeta()) {
				phenodataFile = new File(jobDataDir, outputDescription.getFileName().getID());
			}
		}

		// pass output files to result message
		List<OutputDescription> outputFiles = toolDescription.getOutputFiles();
		for (OutputDescription fileDescription : outputFiles) {
			cancelCheck();

			// single file description can also describe several files
			File[] describedFiles;

			if (fileDescription.getFileName().isSpliced()) {
				// it is a set of files
				String prefix = fileDescription.getFileName().getPrefix();
				String postfix = fileDescription.getFileName().getPostfix();
				String regex = prefix + ".*" + postfix;
				describedFiles = OnDiskCompJobBase.findFiles(jobDataDir, regex);

				// if output is required there should be at least one
				if (!fileDescription.isOptional() && describedFiles.length == 0) {
					logger.error("required output file set not found");
					this.setErrorMessage(
							"Required output file set " + fileDescription.getFileName().getID() + " is missing.");
					updateState(JobState.ERROR);
					return;
				}
			} else {
				// it is a single file
				String outputName = fileDescription.getFileName().getID();
				describedFiles = new File[] { new File(jobDataDir, outputName) };
			}

			// parse a file containing file names for the client
			String outputsFilename = "chipster-outputs.tsv";
			LinkedHashMap<String, String> nameMap = new LinkedHashMap<>();
			try {
				nameMap = ToolUtils.parseOutputDescription(new File(jobDataDir, outputsFilename));
			} catch (IOException | CompException e) {
				logger.warn("couldn't parse " + outputsFilename);
				this.setErrorMessage("could not parse " + outputsFilename);
				this.setOutputText(Exceptions.getStackTrace(e));
				updateState(JobState.ERROR);
			}

			// add all described files to the result message
			for (File outputFile : describedFiles) {
				// copy file to file broker
				try {
					File phenodataFileForThisOutput =
							outputFile.getName().endsWith(".tsv") ||
							outputFile.getName().endsWith(".shared") ||
							outputFile.getName().endsWith(".Rda") ? phenodataFile : null;

					String nameInClient = nameMap.get(outputFile.getName());
					String nameInSessionDb = nameInClient != null ? nameInClient : outputFile.getName();
					String dataId = resultHandler.getFileBrokerClient().addFile(
							UUID.fromString(inputMessage.getJobId()), inputMessage.getSessionId(), outputFile, nameInSessionDb, fileDescription.isMeta(), phenodataFileForThisOutput);
					// put dataId to result message
					this.addOutputDataset(outputFile.getName(), dataId, nameInClient);
					logger.debug("transferred output file: " + fileDescription.getFileName());

				} catch (FileNotFoundException e) {
					// required output file not found
					if (!fileDescription.isOptional()) {
						logger.error("required output file not found", e);
						this.setErrorMessage("Required output file is missing.");
						this.appendOutputText(Exceptions.getStackTrace(e));
						updateState(JobState.ERROR);
						return;
					}

				} catch (NotEnoughDiskSpaceException nedse) {
					logger.warn("not enough disk space for result file in filebroker");
					this.setErrorMessage(
							"There was not enough disk space for the result file in the Chipster server. Please try again later.");
					updateState(JobState.FAILED_USER_ERROR, "not enough disk space for results");
				}

				catch (Exception e) {
					// TODO continue or return? also note the super.postExecute()
					logger.error("could not put file to file broker", e);
					this.setErrorMessage("Could not send output file.");
					this.setOutputText(Exceptions.getStackTrace(e));
					updateState(JobState.ERROR);
					return;
				}
			}
		}
		super.postExecute();
	}

	/**
	 * Clear job working directory.
	 *
	 */
	@Override
	protected void cleanUp() {
		try {
			// sweep job working directory
			if (resultHandler.shouldSweepWorkDir()) {
				OnDiskCompJobBase.delTree(jobDir);
			}
		} catch (Exception e) {
			logger.error("Error when cleaning up job work dir.", e);
		} finally {
			super.cleanUp();
		}
	}

	private void getInputFiles()
			throws Exception, JobCancelledException, IOException, FileBrokerException {
		LinkedHashMap<String, String> nameMap = new LinkedHashMap<>();

		if (!this.jobDataDir.mkdir()) {
			throw new IOException("Creating job data dir failed.");
		}

		for (String fileName : inputMessage.getKeys()) {
			cancelCheck();

			// get url and output file
			String dataId = inputMessage.getId(fileName);
			File localFile = new File(jobDataDir, fileName);

			// make local file available, by downloading, copying or symlinking
			resultHandler.getFileBrokerClient().getFile(inputMessage.getSessionId(), dataId,
					new File(jobDataDir, fileName));
			logger.debug("made available local file: " + localFile.getName() + " " + localFile.length());

			nameMap.put(fileName, inputMessage.getName(fileName));
		}

		ToolUtils.writeInputDescription(new File(jobDataDir, "chipster-inputs.tsv"), nameMap);

		inputMessage.preExecute(jobDataDir);
	}

	/**
	 * Deletes a file or a directory recursively. Deletes directory links, does not go
	 * into them recursively.
	 *
	 * @param dir directory or file to be deleted
	 * @return true if deleting was successful, false file does not exist or deleting it failed
	 * @throws IOException
	 */
	public static boolean delTree(File dir) throws IOException {

		// Just try to delete the file first
		// Will work for normal files, empty dirs and links (dir or file)
		// Avoids need for dealing with links later on
		if (dir.delete()) {
			return true;
		}

		// Directory
		else if (dir.isDirectory()) {
			for (File file : dir.listFiles()) {
				delTree(file);
			}

			// Dir should be empty now
			return dir.delete();
		}

		// Could not delete, not a directory, no can do
		else {
			return false;
		}
	}

	/**
	 * Find files in a given directory whose filenames match given regex.
	 */
	public static File[] findFiles(File dir, String regex) {

	    class RegexFileFilter implements FilenameFilter {
	        private String regex;

	        public RegexFileFilter(String regex) {
                this.regex = regex;
            }

            @Override
            public boolean accept(File dir, String name) {
                return name.matches(regex);
            }

	    }

	    return dir.listFiles(new RegexFileFilter(regex));
	}

	public File getJobDataDir() {
		return this.jobDataDir;
	}
}


text:
<?php

namespace MediaMonks\Doctrine\Transformable\Transformer;

interface TransformerInterface
{
    /**
     * @param mixed $value
     * @return mixed
     */
    public function transform($value);

    /**
     * @param mixed $value
     * @return mixed
     */
    public function reverseTransform($value);
}


text:
package pub.zilla.validzilla.model;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created by zilla on 10/12/17.
 */

public class MethodModel {
    private Method method;
    private Annotation annotation;

    public MethodModel() {

    }

    public MethodModel(Method method, Annotation annotation) {
        this.method = method;
        this.annotation = annotation;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Annotation getAnnotation() {
        return annotation;
    }

    public void setAnnotation(Annotation annotation) {
        this.annotation = annotation;
    }

    @Override
    public String toString() {
        return "MethodModel{" +
                "method=" + method +
                ", annotation=" + annotation +
                '}';
    }
}


text:
layout: doc
title: Kartierung mit einem GPS-Gerät
permalink: /de/beginner/using-gps/
lang: de
category: beginner
---

Kartierung mit einem GPS-Gerät
====================

In diesem Kapitel werden wir herausfinden was ein GPS-Gerät ist und wie es funktioniert. Du wirst lernen wie man ein GPS-Gerät benutzt und wie du mit dessen Hilfe Karten erstellen kannst. Das in diesem Kapitel vorgestellte und verwendete GPS-Gerät ist das Garmin eTrex HCx, welches weit verbreitet ist und zum Kartieren eingesetzt wird. Es gibt noch viele andere Hersteller und Modelle, welche alle den gleichen Zweck verfolgen. Falls du also ein anderes GPS-Gerät verwendest, keine Sorge - die grundsätzlichen Funktionen sind die gleichen.

Was ist ein GPS-Gerät?
--------------

Ein GPS-Gerät ähnelt einem Mobiltelefon, allerdings empfängt es keine Signale aus dem Mobilfunktnetz. Vielmehr kann ein GPS-Gerät Signale von Satelliten empfangen welche um die Erde kreisen. Dadurch ist es in der Lage deine exakte Position auf der Erde zu bestimmen. Die Position wird in Koordinaten erfasst, welche aus zwei langen zahlen bestehen. Die erste Zahl beschreibt, wie weit westlich oder östlich du dich (vom Nullmeridian) aufhälst - man nennt das Längengrad - und die zweite Zahl gibt an wie weit nördlich oder südlich (vom Äquator) du bist - dies nennt man Breitengrad. Jeder Ort auf der Erde verfügt über einzigartige geografische Koordinaten.
Zum Beispiel: -8.639298 (südliche) Breite, 116.311607 (östliche) Länge ist ein Ort in Lombok, Indonesien.

![Google Earth, Anzeige der Koordinaten von Lombok, Indonesia][]

![Garmin eTrex Vista HCx][]

Das GPS-Gerät in Betrieb nehmen
---------------

Bevor du dein GPS-Gerät in Betrieb nimmst, gehe nach draußen an einen Ort wo du unter freiem Himmel stehst. Da das GPS-Signal mithilfe von Satelliten bestimmt wird, funktioniert es nicht innerhalb von Gebäuden.

Auf der rechten Seite des Geräts ist der Einschaltknopf, drücke und halte ihn. Das Gerät startet und wird als erstes die Ansicht der Satelliten laden. Es sollte in etwa so aussehen wie auf dem Screenshot unten. Das GPS-Gerät sucht nach einem verfügbaren Satelliten-Signal und sobald es sich mit drei oder mehr Satelliten verbunden hat, kann die Position bestimmt werden.

![GPS Positionsbestimmung][]

Sobald deine Position bestimmt wurde, wird die Satelliten-Ansicht geschlossen und das Hauptmenü geöffnet.

![GPS Hauptmenü][]

Mit dem GPS-Gerät navigieren
----------------

-   Das GPS-Gerät verfügt über verschiedene Ansichten, welche verschiedene Funktionen beherbergen. Um zwischen den einzelnen Anischten zu wechseln, drücke auf den Knopf "X", welcher sich direkt über dem Einschaltknopf an der rechten Seite des Geräts befindet. Dieser Knopf ist auch gleichzeitig ein "Zurück"-Knopf, falls du aus Versehen auf irgendetwas gedrückt hast und die Aktion abbrechen möchtest, drück auf den "X"-Knopf.
-   Mit Hilfe des "X"-Knpofes kannst du durch die einzelnen Ansichten wechseln, was ungefähr so aussieht:

    ![GPS alle][]

-   Wenn du zur Satelliten-Ansicht zurückkehrst, kannst du sehen, dass das Gerät mit mindestens drei Satelliten verbunden ist. In der oberen linken Ecke sind deine Koordinaten zu sehen, in Breiten- und Längengraden.

> Um OSM zu deinem GPS-Gerät hinzuzufügen, lade die neuesten Daten von [http://labs.geofabrik.de/haiti/latest.garmin-gmapsupp.zip](http://labs.geofabrik.de/haiti/latest.garmin-gmapsupp.zip) herunter.
> Entpacke "latest.garmin-gmapsupp.zip" und speichere die Datei "gmapsupp.img" vorübergehend in einen Ordner. Nachdem du dein GPS-Gerät eingeschaltet und mit dem Computer verbunden hast, sollte das Gerät als USB-Laufwerk sichtbar sein. Erstelle einen neuen Ordner mit dem Namen "Garmin" im Hauptverzeichnis des USB-Laufwerks.
> Kopiere die Datei "gmapsupp.img" in den neu erstellten "Garmin"-Ordner.
> Als letztes starte das GPS-Gerät neu. Die extrahierte OSM-Karte sollte zu deinem Gerät hinzugefügt werden.

- Wechsle zur Kartenansicht und du kannst eine Karte mit deiner aktuellen Position sehen. Wenn du die OSM-Karte hinzugefügt hast, wirst du wahrscheinlich auch Straßen und Orte sehen. Wenn nicht, könnte die Karte ziemlich leer aussehen. Mit den "Hoch"- und "Runter"-Knöpfen an der linken Seite des Gerätes kannst du die Karte vergrößern und verkleinern.

Spuren und Wegpunkte
--------------------

Dein GPS-Gerät nimmt zwei Arten von Informationen auf, welche nützlich sind zum Speichern von Koordinaten und Erstellen von Karten. Zum einen kann die aktuelle Position in den Speicher des Geräts geschrieben werden. Wenn du eine Position speicherst werden die Koordinaten mit einem Namen versehen. der erste punkt wird beispielswesie 001 genannt, der zweite 002, und so weiter.

> Falls dein GPS-Gerät nicht mit 001 anfängt und du die vorherigen Punkte löschen möchtest, wähle das "Finden"-Icon im Hauptmenü aus. Wähle "Wegpunkte" und dann den Knopf für das Untermenü auf der rechten Seite um das Wegpunkte-Untermenü anzuzeigen. Wähle unten "Löschen", dann "Alle Symbole" und drücke zum Bestätigen "Ja".

Wenn du eine Position speicherst, kannst du dir die Nummer auf einem Stück Papier notieren, zusammen mit einer Notiz was dort zu finden ist und allen möglichen Attributen und Hinweisen die du wissen möchtest. Gespeicherte Positionen auf deinem GPS-Gerät werden Wegpunkte genannt.

Außerdem kann dein GPS-Gerät sogenannte Spuren aufzeichnen. Während ein Wegpunkt nur eine bestimmt Position speichert, kann eine GPS-Spur eine ganze Reihe an Positionen, an denen du dich aufhälst, aufzeichnen. Zum Beispiel kann das Gerät jede Sekunde eine Position aufnehmen, oder jeden Meter den du dich bewegst. Das Resultat ist eine Reihe von Punkten, die eine Spur darstellen, wo du gewesen bist. So eine Spur ist nützlich um Objekte zu erfassen, welche durch Linen oder Formen dargestellt werden, beispielsweise Straßen oder Spielfelder.

![GPS Spur][]

Deine Position speichern
-----------------------------------

-   Um deine aktuelle Position als einen Wegpunkt zu speichern, drücke den "X"-Knopf solange, bis du in das Hauptmenü gelangst. Mit Hilfe des Joysticks kannst du den Menüpunkt "Mark" auswählen und anschließend den Joystick-Knopf runterdrücken um die "Wegpunkt speichern"-Ansicht aufzurufen.

    ![Position 1 speichern][]
    ![Position 2 speichern][]

> Falls du mehrere GPS-Geräte verwendest, ist es wichtig sicherzustellen, dass alle Geräte auf das selbe Positionsformat eingestellt sind. Um dies zu überprüfen, wähle das Hauptmenü aus und finde den Unterpunkt "Set up Menu". Klicke auf "Einheiten" und stelle sicher, dass Folgendes eingestellt ist: Positionsformat auf Dezimalgrad (hddd.ddddd°), das Kartendatum auf WGS84 und die Distanzgeschwindigkeit, Erhebung und Tiefe auf Meter.

-   Du kannst in dieser Ansicht gewisse Informationen über den Wegpunkt sehen, den du speicherst. Zunächst den Namen, falls dies dein erster Wegpunkt ist, steht dort vermutlich "001". Dies ist die Zahl die du dir zusammen mit Zusatzinformationen auf Papier notieren solltest. Als nächstes wird das Datum und die Uhrzeit angezeigt an dem der Wegpunkt aufgenommen wurde. Darunter stehen die geografischen Koordinaten und die Höhe über dem Meeresspiegel.
-   Nutze den Joystick um den "OK"-Knopf unten in der Ansicht auszuwählen. Drücke den Joystick runter um diesen Wegpunkt zu speichern. Stelle sicher, dass du dir die Nummer des Punktes aufgeschrieben hast, zusammen mit Zusatzinformationen über den Wegpunkt.
-   Drücke den "X"-Knopf, um wieder zur Kartenansicht zu gelangen. Dein Wegpunkt sollte nun auf der Karte sichtbar sein.

Aktivieren des Spurenprotokolls
---------------------

-   Nun, da wir wissen, wie man Wegpunkte speichert, ist es sinnvoll zu lernen, wie man das Spurenprotokoll aktiviert. Wenn das Spurenprotokoll aktiviert ist, zeichnet das GPS-Gerät automatisch deinen zurück gelegten Weg auf. Es ist üblich das Protokoll zu aktivieren, wenn du mit der Kartierung anfängst und es zu deaktivieren wenn du fertig bist. So kannst du anschliessend deine GPS-Spur am Computer anschauen. Wenn du den Verlauf einer Straße kartierst, ist eine gute Idee, zu Beginn und Ende jeweils einen Wegpunkt zu speichern. So kannst du den Namen und andere nützliche Informationen über die Straße in deinem Notizbuch aufschreiben.
-   Um das Spurenprotokoll zu aktivieren, drücke den "X"-Knopf solange, bis du zur Ansicht "Track Log" kommst.

    ![Protokoll aktivieren][]

-   Wenn du das Spurenprotokoll löschen möchtest um frühere Aufzeichnungen zu entfernen, nutze den Joystick um "Clear" auszuwählen und drücke den Joystick-Knopf. Die obere Leiste sollte "0%" anzeigen.
-   Um das Protokoll zu aktivieren, wähle mit dem Joystick "On" aus und drücke den Joystick-Knopf. Jetzt zichnet das GPS-Gerät deinen Weg auf.
-   In der Option "Set up" kannst du außerdem auch Zeit- oder Distanzintervalle einstellen. Zeitintervalle sagen dem GPS-Gerät, dass es die aktuelle Position in einem bestimmten Intervall aufzeichnen soll. Wenn du eine Speicherkarte in deinem Gerät verwendest, macht es Sinn das Zeitintervall auf 1 Sekunde zu stellen. So wird jede Sekunde die aktuelle Position erfasst und du erhälst eine sehr detaillierte GPS-Spur.
-   Drücke den "X"-Knopf um zur Kartenansicht zurück zu kehren. Wenn du dich bewegst wirst du deine aufgezeichnete Spur als eine Reihe von Punkten angezeigt bekommen.

Wegpunkte und GPS-Spuren auf den Computer kopieren
-----------------------------------------

### GPS-Gerät mit dem Computer verbinden

-   Ween du mit dem Kartieren fertig bist, möchtest du sicher die Wegpunkte und GPS-Spuren auf deinen Computer kopieren damit du sie in JOSM öffnen kannst. Als erstes solltest du das Spurenprotokoll auf deinem GPS-Gerät wie oben beschrieben deaktivieren, sofern du es noch nicht getan hast.
-   Verbinde das GPS-Gerät mit dem Computer. Ein Ende des Kabels wird in den USB-Anschluss deines Computers gesteckt, das andere kommt an die Rückseite des GPS-Geräts, unter die obere Gummiabdeckung. Das GPS-Gerät muss eingeschaltet sein, um die Wegpunkte und Spuren zu kopieren.

### GPS-Treiber installieren

-   Es kann sein, dass du zunächst noch GPS-Treiber auf deinem Computer installieren musst, damit das GPS-Gerät erkannt wird.
-   Die entsprechende Datei mit dem Namen "USBDrivers\_23.exe" kannst du unter [http://www8.garmin.com/support/download\_details.jsp?id=591](http://www8.garmin.com/support/download_details.jsp?id=591) herunterladen. Öffne die URL in deinem Internetbrowser und drücke auf "Download". Öffne die Datei um die Treiber zu installieren.

### Hole dir das GPSBabel Setup-Programm
-   GPSBabel ist ein Programm, welches und ermöglicht Daten vom GPS-Gerät zu kopieren. Falls du eine Kopie von GPSBabel auf CD oder auf einem USB-Stick hast, mache direkt mit dem nächsten Abschnitt weiter.
-   Wenn du GPSBabel noch nicht besitzt, öffne [www.gpsbabel.org](www.gpsbabel.org) in deinem Web-Browser und klicke auf "Downloads" oben auf der Seite.
-   Scrolle nach unten um verschiedene Downloads für die unterschiedlichen Betriebssysteme zu finden. Der oberste Download ist für Computer die unter Windows laufen, der mittlere für Apple-Computer mit Mac OSX und der unterste für Linux-Rechner. Klicke auf den jeweligen Button um die passende Datei herunter zu laden.

### GPSBabel installieren
-   Öffne die gerade heruntergeladene Datei mit einem Doppelklick.
-   Klicke auf "Next".
-   Klicke auf "I accept" und "Next".
-   Drücke weiter auf "Next" bis das Programm anfängt zu installieren.
-   Wenn das Programm fertig installiert ist, klicker auf "Finish" um GPSBabel zu starten.

    ![GPSBabel Programmoberfläche][]

### Spuren und Wegpunkte kopieren

-   Klicke auf den Kreis neben dem Wort "Device" am oberen Fensterrand.
-   In dem Auswahlmenü "Format" wählst du "Garmin serial/USB
    protocol" aus.
-   In dem Auswahlmenü in der Mitte des Fensters (unter "Output"), wähle "GPX XML" aus.

    ![GPX XML auswählen][]

-   Wähle "File Name" und tippe einen Namen für die zu speichernde datei ein. Der Name sollte aus etwas sinnvollem bestehen, etwas was die GPS-daten beschreibt, wie das Datum und der Ort. Beispielsweise: _jakarta-07-07-2011_
-   Stelle sicher, dass das GPS-Gerät mit dem Computer verbunden und eingeschaltet ist.
-   Klicke auf "Apply" in der unteren rechten Ecke in GPSBabel.
-   Wenn alles richtig läuft, siehst du eine Fortschrittsleiste, welche anzeigt, dass Daten von GPS-Gerät übertragen werden. Wenn die Übertragung abgeschlossen ist, sind deine Wegpunkte und Spuren in der Datei gespeichert, die du angegeben hast.

### Daten in JOSM öffnen

-   Als nächstes öffne JOSM. In dem oberen Menü, wähle "File" und klicke auf "Open..."
-   Wähle die Datei aus, die du mit GPSBabel erzeugt hast und klicke auf "Open".
-   Du solltest jetzt deine Wegpunkte und Spuren in JOSM sehen.

    ![GPS Dateien in JOSM geöffnet][]

Zusammenfassung
-------

Glückwunsch! Du solltest jetzt ein gutes Verständnis davon haben, wie man ein GPS-Gerät benutzt. Falls du es nicht schon längst getan hast, probiere mal aus ein paar Wegpunkte von wichtigen Orten in deiner Umgebung zu speichern. In diesem Kapitel hast du gelernt wie man Wegpunkte und GPS-Spuren in JOSM öffnet. In Kapitel 6 werden wir diese Informationen nutzen um neue Informationen zu OpenStreetMap hinzuzufügen. Im nächsten Kapitel lernen wir Walking Papers kennen, welche ein weiterer Weg sind, Informationen für OpenStreetMap zu sammeln. Mit Hilfe von Walking Papers ist es möglich, nur mit Hilfe von Stift und Papier die Koordinaten von Orten aufzuzeichnen, so wie mit einem GPS-Gerät.

[Google Earth, Anzeige der Koordinaten von Lombok, Indonesia]: {{site.baseurl}}/images/gps_lombok_map_en.png
[Garmin eTrex Vista HCx]: {{site.baseurl}} /images/en/beginner/05_gps/en_beg_05_gps_image01_garmin-etrex.png
[GPS Positionsbestimmung]: {{site.baseurl}}/images/en/beginner/05_gps/en_beg_05_gps_image02_aquiring-satellites.png
[GPS hauptmenü]: {{site.baseurl}}/images/gps_main_en.png
[GPS alle]: {{site.baseurl}}/images/en/beginner/05_gps/en_beg_05_gps_image04_all.png
[GPS Spur]: {{site.baseurl}}/images/gps_google_earth_en.png
[Position 1 speichern]: {{site.baseurl}}/images/gps_save_location1_en.png
[Position 2 speichern]: {{site.baseurl}}/images/gps_save_location2_en.png
[Protokoll aktivieren]: {{site.baseurl}}/images/gps_turn_on_track_en.png
[GPSBabel Programmoberfläche]: {{site.baseurl}}/images/gps_babel_en.png
[GPX XML auswählen]: {{site.baseurl}}/images/gps_xml_en.png
[GPS Dateien in JOSM geöffnet]: {{site.baseurl}}/images/gps_open_josm_en.png


text:
using System;
using System.Linq;

////### Problem 05. Sort by string length
////*You are given an array of strings. Write a method that sorts the array by the length of its elements (the number of characters composing them).
class SortByStringLength
{
    static void Main()
    {
        // WARNING! To better understand this code you can watch the last hour of Matrix and Multidim arrays
        // lecture by Niki from 2013/2014 C# Part 2 archive on TelerikAcademy`s website

        // YOUR INPUT HERE!!!!!!!!!!!!!!!!
        string[] arrStr =
        {
            "Asen", "Petko", "Mincho", "Martin", "Dancho", "Lyubo", "Lyudmil"
        };

        // using lambda expression we create anonymous function for comparing two values in arrStr
        Array.Sort(arrStr, (x, y) =>
            {
                // we need to make sure that the function returns either -1, 0 or 1
                // if x > y (first value bigger than second) return 1
                if (x.Length > y.Length)
                {
                    return 1;
                }

                // if first value is smaller, return -1
                else if (x.Length < y.Length)
                {
                    return -1;
                }

                // if strings are equal in length sort them lexicographically
                else
                {
                    if (x.CompareTo(y) > 0)
                    {
                        return 1;
                    }
                    if (x.CompareTo(y) < 0)
                    {
                        return -1;
                    }
                    if (x.CompareTo(y) == 0)
                    {
                        return 0;
                    }
                }

                // we need this final statement to fulfil compilers condition to return -1,0 or 1
                // although it will never be reached
                return 0;
            }
            );

        foreach (var item in arrStr)
        {
            Console.WriteLine(item);
        }
    }
}


text:
/*
 * Contains all the configurables for the designcheck
 **/

var options = {

    /*
     * int associationMargin , the number of pixels to the left or right an
     * element can be to be associated with the base element
     **/
    associationMargin   : 3 ,

    /*
     * The minimum value offsetLeft should have in order to be eligable for checking
     **/
    minOffsetLeft       : 0 ,

    /*
     * The minimum dimensions an element should have to be eligable for tracking
     * This gives the option to exclude i.e. tracking pixels
     **/
    minDimentions       : {
        width   : 0 ,
        height  : 0
    } ,

    /*
     * dimentionTrigger is used together with the minDimentions configuration.
     * This value is either "and" of "or"
     * "and" setting enables u to check the elements that meet both minimum height and width requirements
     * "or" setting enables u to check the elements that meet either the height or width requirement
     */

    dimentionTrigger : "and" ,

    /*Elements that should be removed from the site before the check starts */
    removeableIds : Array("cookie") ,

    /*
     * Toggle for diplaying only errors or displaying all checks
     */

    errorsOnly : true ,

    /*
     * Setter for minOffsetLeft
     **/
    setLeft : function()
    {
        this.minOffsetLeft = 0;
    }

}


text:
package org.teavm.classlib.java.util.stream.impl;

import java.util.function.Predicate;

public class TAnyMatchConsumer<T> implements Predicate<T> {
    public boolean matched;
    private Predicate<? super T> predicate;

    public TAnyMatchConsumer(Predicate<? super T> predicate) {
        this.predicate = predicate;
    }

    @Override
    public boolean test(T t) {
        matched = predicate.test(t);
        return !matched;
    }
}


text:
import asyncio

from twisted.internet import asyncioreactor
asyncioreactor.install(asyncio.get_event_loop())

import scrapy
from scrapy.crawler import CrawlerProcess

class NoRequestsSpider(scrapy.Spider):
    name = 'no_request'

    def start_requests(self):
        return []

process = CrawlerProcess(settings={
    "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
})
process.crawl(NoRequestsSpider)
process.start()


text:
package org.sparkcommerce.common.exception;

/**
 * @author adasari
 */
public class SiteNotFoundException extends RuntimeException {

    public SiteNotFoundException() {
        //do nothing
    }

    public SiteNotFoundException(Throwable cause) {
        super(cause);
    }

    public SiteNotFoundException(String message) {
        super(message);
    }

    public SiteNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
import { EventsKey } from '../events';
import Event from '../events/Event';
import { Extent } from '../extent';
import LayerType from '../LayerType';
import { ObjectEvent } from '../Object';
import PluggableMap from '../PluggableMap';
import RenderEvent from '../render/Event';
import Source from '../source/Source';
import TileSource from '../source/Tile';
import Layer from './Layer';

export interface Options {
    opacity?: number;
    visible?: boolean;
    extent?: Extent;
    zIndex?: number;
    minResolution?: number;
    maxResolution?: number;
    preload?: number;
    source?: TileSource;
    map?: PluggableMap;
    useInterimTilesOnError?: boolean;
}
export default class TileLayer extends Layer {
    constructor(opt_options?: Options);
    protected type: LayerType;
    getPreload(): number;
    getSource(): TileSource;
    getUseInterimTilesOnError(): boolean;
    setPreload(preload: number): void;
    setUseInterimTilesOnError(useInterimTilesOnError: boolean): void;
    on(type: string | string[], listener: (p0: any) => void): EventsKey | EventsKey[];
    once(type: string | string[], listener: (p0: any) => void): EventsKey | EventsKey[];
    un(type: string | string[], listener: (p0: any) => void): void;
    on(type: 'change', listener: (evt: Event) => void): EventsKey;
    once(type: 'change', listener: (evt: Event) => void): EventsKey;
    un(type: 'change', listener: (evt: Event) => void): void;
    on(type: 'change:extent', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:extent', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:extent', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:maxResolution', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:maxResolution', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:maxResolution', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:minResolution', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:minResolution', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:minResolution', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:opacity', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:opacity', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:opacity', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:preload', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:preload', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:preload', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:source', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:source', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:source', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:useInterimTilesOnError', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:useInterimTilesOnError', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:useInterimTilesOnError', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:visible', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:visible', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:visible', listener: (evt: ObjectEvent) => void): void;
    on(type: 'change:zIndex', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'change:zIndex', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'change:zIndex', listener: (evt: ObjectEvent) => void): void;
    on(type: 'postcompose', listener: (evt: RenderEvent) => void): EventsKey;
    once(type: 'postcompose', listener: (evt: RenderEvent) => void): EventsKey;
    un(type: 'postcompose', listener: (evt: RenderEvent) => void): void;
    on(type: 'precompose', listener: (evt: RenderEvent) => void): EventsKey;
    once(type: 'precompose', listener: (evt: RenderEvent) => void): EventsKey;
    un(type: 'precompose', listener: (evt: RenderEvent) => void): void;
    on(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    once(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
    un(type: 'propertychange', listener: (evt: ObjectEvent) => void): void;
    on(type: 'render', listener: (evt: RenderEvent) => void): EventsKey;
    once(type: 'render', listener: (evt: RenderEvent) => void): EventsKey;
    un(type: 'render', listener: (evt: RenderEvent) => void): void;
    on(type: 'rendercomplete', listener: (evt: RenderEvent) => void): EventsKey;
    once(type: 'rendercomplete', listener: (evt: RenderEvent) => void): EventsKey;
    un(type: 'rendercomplete', listener: (evt: RenderEvent) => void): void;
}


text:
{% load comments i18n %}
{% load url from future %}

  {% block entry-header %}

    {% block entry-title %}

      {{ object.title }}

    {% endblock %}
    {% block entry-info %}

      {% with authors=object.authors.all %}
      {% if authors|length %}
      {% trans "Written by" %}
      {% for author in authors %}

        {{ author }}{% if not forloop.last %}, {% endif %}
      {% endfor %}
      {% trans "on" %}
      {% else %}
      {% trans "Written on" %}
      {% endif %}
      {% endwith %}
      <time datetime="{{ object.creation_date|date:"c" }}" pubdate="pubdate">{{ object.creation_date|date:"DATE_FORMAT" }}</time>
      {% with categories=object.categories.all %}
      {% if categories|length %}
      {% trans "in" %}
      {% for category in categories %}
      {{ category }}{% if not forloop.last %}, {% endif %}{% endfor %}{% endif %}.{% endwith %}

    {% endblock %}

  {% endblock %}

  {% block entry-body %}

    {% block entry-image %}
    {% if object.image %}

        {% if continue_reading %}

          {% endif %}

          {% if continue_reading %}

        {% endif %}

    {% endif %}
    {% endblock %}
    {% block entry-content %}

      {{ object_content }}

    {% endblock %}

  {% endblock %}

  {% block entry-footer %}

    {% block continue-reading %}
    {% if continue_reading %}

      {% trans "Continue reading" %}

    {% endif %}
    {% endblock %}
    {% block entry-tags %}

       {% trans "Tags" %} :
      {% for tag in object.tags_list %}
      {{ tag }}
      {% empty %}
      {% trans "No tags" %}
      {% endfor %}

    {% endblock %}
    {% block entry-shorturl %}

       {% trans "Short url" %} :

        {{ object.short_url }}

    {% endblock %}
    {% block entry-comments %}

       {% trans "Discussions" %} :
      {% with comment_count=object.comment_count %}
      {% if comment_count %}

        {% blocktrans count comment_count=comment_count %}{{ comment_count }} comment{% plural %}{{ comment_count }} comments{% endblocktrans %}

      {% else %}
      {% if object.comments_are_open %}
      {% trans "No comments yet." %}

        {% trans "Be first to comment!" %}

      {% else %}
      {% trans "Comments are closed." %}
      {% endif %}
      {% endif %}
      {% endwith %}
      {% with pingback_count=object.pingback_count %}
      {% if pingback_count %}
      ,
        {% blocktrans count pingback_count=pingback_count %}{{ pingback_count }} pingback{% plural %}{{ pingback_count }} pingbacks{% endblocktrans %}

      {% endif %}
      {% endwith %}
      {% with trackback_count=object.trackback_count %}
      {% if trackback_count %}
      ,
        {% blocktrans count trackback_count=trackback_count %}{{ trackback_count }} trackback{% plural %}{{ trackback_count }} trackbacks{% endblocktrans %}

      {% endif %}
      {% endwith %}

    {% endblock %}

  {% endblock %}


text:
<?php

namespace CodeIgniter\Commands;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Filters\CITestStreamFilter;

/**
 * @internal
 *
 * @group Others
 */
final class ClearDebugbarTest extends CIUnitTestCase
{
    private $streamFilter;
    private $time;

    protected function setUp(): void
    {
        parent::setUp();

        CITestStreamFilter::$buffer = '';
        $this->streamFilter         = stream_filter_append(STDOUT, 'CITestStreamFilter');
        $this->streamFilter         = stream_filter_append(STDERR, 'CITestStreamFilter');
        $this->time                 = time();
    }

    protected function tearDown(): void
    {
        stream_filter_remove($this->streamFilter);
    }

    protected function createDummyDebugbarJson()
    {
        $time = $this->time;
        $path = WRITEPATH . 'debugbar' . DIRECTORY_SEPARATOR . "debugbar_{$time}.json";

        // create 10 dummy debugbar json files
        for ($i = 0; $i < 10; $i++) {
            $path = str_replace($time, $time - $i, $path);
            file_put_contents($path, "{}\n");

            $time -= $i;
        }
    }

    public function testClearDebugbarWorks()
    {
        // test clean debugbar dir
        $this->assertFileDoesNotExist(WRITEPATH . 'debugbar' . DIRECTORY_SEPARATOR . "debugbar_{$this->time}.json");

        // test dir is now populated with json
        $this->createDummyDebugbarJson();
        $this->assertFileExists(WRITEPATH . 'debugbar' . DIRECTORY_SEPARATOR . "debugbar_{$this->time}.json");

        command('debugbar:clear');
        $result = CITestStreamFilter::$buffer;

        $this->assertFileDoesNotExist(WRITEPATH . 'debugbar' . DIRECTORY_SEPARATOR . "debugbar_{$this->time}.json");
        $this->assertFileExists(WRITEPATH . 'debugbar' . DIRECTORY_SEPARATOR . '.gitkeep');
        $this->assertStringContainsString('Debugbar cleared.', $result);
    }
}


text:
set -euE

check_row_count() {
    run_sql "select count(*) from test.$1;"
    check_contains "count(*): $2"
}

for BACKEND in local tidb; do
    if [ "$BACKEND" = 'local' ]; then
        check_cluster_version 4 0 0 'local backend' || continue
    fi
    run_sql 'DROP DATABASE IF EXISTS test'
    run_sql 'CREATE DATABASE test'
    run_sql "source tests/$TEST_NAME/db.sql;" -D test

    run_lightning --backend $BACKEND

    check_row_count customer 20
    check_row_count district 10
    check_row_count history 100
    check_row_count item 100
    check_row_count new_order 100
    check_row_count order_line 100
    check_row_count orders 100
    check_row_count stock 50
    check_row_count warehouse 1

    run_sql 'select sum(c_id) from test.customer;'
    check_contains "sum(c_id): 210"

    run_sql 'select w_name from test.warehouse;'
    check_contains "w_name: eLNEDIW"
    run_sql 'select w_bool from test.warehouse;'
    check_contains "w_bool: 1"

    run_sql 'select c_since, c_discount from test.customer where c_id = 20;'
    check_contains "c_since: 2020-09-10 20:17:16"
    check_contains "c_discount: 0.0585"
done


text:
title: "areacodes.online"
layout: post
description: pretty area code listing
category: parked
img: img/areacodes.online.png
redirect: http://areacodes.online
---


text:
package git

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"strconv"
	"strings"
)

// DiffLineType is the line type in diff.
type DiffLineType uint8

// A list of different line types.
const (
	DiffLinePlain DiffLineType = iota + 1
	DiffLineAdd
	DiffLineDelete
	DiffLineSection
)

// DiffFileType is the file status in diff.
type DiffFileType uint8

// A list of different file statuses.
const (
	DiffFileAdd DiffFileType = iota + 1
	DiffFileChange
	DiffFileDelete
	DiffFileRename
)

// DiffLine represents a line in diff.
type DiffLine struct {
	Type      DiffLineType // The type of the line
	Content   string       // The content of the line
	LeftLine  int          // The left line number
	RightLine int          // The right line number
}

// DiffSection represents a section in diff.
type DiffSection struct {
	Lines []*DiffLine // lines in the section

	numAdditions int
	numDeletions int
}

// NumLines returns the number of lines in the section.
func (s *DiffSection) NumLines() int {
	return len(s.Lines)
}

// Line returns a specific line by given type and line number in a section.
func (s *DiffSection) Line(typ DiffLineType, line int) *DiffLine {
	var (
		difference      = 0
		addCount        = 0
		delCount        = 0
		matchedDiffLine *DiffLine
	)

loop:
	for _, diffLine := range s.Lines {
		switch diffLine.Type {
		case DiffLineAdd:
			addCount++
		case DiffLineDelete:
			delCount++
		default:
			if matchedDiffLine != nil {
				break loop
			}
			difference = diffLine.RightLine - diffLine.LeftLine
			addCount = 0
			delCount = 0
		}

		switch typ {
		case DiffLineDelete:
			if diffLine.RightLine == 0 && diffLine.LeftLine == line-difference {
				matchedDiffLine = diffLine
			}
		case DiffLineAdd:
			if diffLine.LeftLine == 0 && diffLine.RightLine == line+difference {
				matchedDiffLine = diffLine
			}
		}
	}

	if addCount == delCount {
		return matchedDiffLine
	}
	return nil
}

// DiffFile represents a file in diff.
type DiffFile struct {
	// The name of the file.
	Name string
	// The type of the file.
	Type DiffFileType
	// The index (SHA1 hash) of the file. For a changed/new file, it is the new SHA,
	// and for a deleted file it is the old SHA.
	Index string
	// The sections in the file.
	Sections []*DiffSection

	numAdditions int
	numDeletions int

	oldName string

	isBinary     bool
	isSubmodule  bool
	isIncomplete bool
}

// NumSections returns the number of sections in the file.
func (f *DiffFile) NumSections() int {
	return len(f.Sections)
}

// NumAdditions returns the number of additions in the file.
func (f *DiffFile) NumAdditions() int {
	return f.numAdditions
}

// NumDeletions returns the number of deletions in the file.
func (f *DiffFile) NumDeletions() int {
	return f.numDeletions
}

// IsCreated returns true if the file is newly created.
func (f *DiffFile) IsCreated() bool {
	return f.Type == DiffFileAdd
}

// IsDeleted returns true if the file has been deleted.
func (f *DiffFile) IsDeleted() bool {
	return f.Type == DiffFileDelete
}

// IsRenamed returns true if the file has been renamed.
func (f *DiffFile) IsRenamed() bool {
	return f.Type == DiffFileRename
}

// OldName returns previous name before renaming.
func (f *DiffFile) OldName() string {
	return f.oldName
}

// IsBinary returns true if the file is in binary format.
func (f *DiffFile) IsBinary() bool {
	return f.isBinary
}

// IsSubmodule returns true if the file contains information of a submodule.
func (f *DiffFile) IsSubmodule() bool {
	return f.isSubmodule
}

// IsIncomplete returns true if the file is incomplete to the file diff.
func (f *DiffFile) IsIncomplete() bool {
	return f.isIncomplete
}

// Diff represents a Git diff.
type Diff struct {
	Files []*DiffFile // The files in the diff

	totalAdditions int
	totalDeletions int

	isIncomplete bool
}

// NumFiles returns the number of files in the diff.
func (d *Diff) NumFiles() int {
	return len(d.Files)
}

// TotalAdditions returns the total additions in the diff.
func (d *Diff) TotalAdditions() int {
	return d.totalAdditions
}

// TotalDeletions returns the total deletions in the diff.
func (d *Diff) TotalDeletions() int {
	return d.totalDeletions
}

// IsIncomplete returns true if the file is incomplete to the entire diff.
func (d *Diff) IsIncomplete() bool {
	return d.isIncomplete
}

// SteamParseDiffResult contains results of streaming parsing a diff.
type SteamParseDiffResult struct {
	Diff *Diff
	Err  error
}

type diffParser struct {
	*bufio.Reader
	maxFiles     int
	maxFileLines int
	maxLineChars int

	// The next line that hasn't been processed. It is used to determine what kind of process should go in.
	buffer []byte
	isEOF  bool
}

func (p *diffParser) readLine() error {
	if p.buffer != nil {
		return nil
	}

	var err error
	p.buffer, err = p.ReadBytes('\n')
	if err != nil {
		if err != io.EOF {
			return fmt.Errorf("read string: %v", err)
		}

		p.isEOF = true
	}

	// Remove line break
	if len(p.buffer) > 0 && p.buffer[len(p.buffer)-1] == '\n' {
		p.buffer = p.buffer[:len(p.buffer)-1]
	}
	return nil
}

var diffHead = []byte("diff --git ")

func (p *diffParser) parseFileHeader() (*DiffFile, error) {
	line := string(p.buffer)
	p.buffer = nil

	// Note: In case file name is surrounded by double quotes (it happens only in git-shell).
	// e.g. diff --git "a/xxx" "b/xxx"
	var middle int
	hasQuote := line[len(diffHead)] == '"'
	if hasQuote {
		middle = strings.Index(line, ` "b/`)
	} else {
		middle = strings.Index(line, ` b/`)
	}

	beg := len(diffHead)
	a := line[beg+2 : middle]
	b := line[middle+3:]
	if hasQuote {
		a = string(UnescapeChars([]byte(a[1 : len(a)-1])))
		b = string(UnescapeChars([]byte(b[1 : len(b)-1])))
	}

	file := &DiffFile{
		Name: a,
		Type: DiffFileChange,
	}

	// Check file diff type and submodule
	var err error
checkType:
	for !p.isEOF {
		if err = p.readLine(); err != nil {
			return nil, err
		}

		line := string(p.buffer)
		p.buffer = nil

		if len(line) == 0 {
			continue
		}

		switch {
		case strings.HasPrefix(line, "new file"):
			file.Type = DiffFileAdd
			file.isSubmodule = strings.HasSuffix(line, " 160000")
		case strings.HasPrefix(line, "deleted"):
			file.Type = DiffFileDelete
			file.isSubmodule = strings.HasSuffix(line, " 160000")
		case strings.HasPrefix(line, "index"): // e.g. index ee791be..9997571 100644
			fields := strings.Fields(line[6:])
			shas := strings.Split(fields[0], "..")
			if len(shas) != 2 {
				return nil, errors.New("malformed index: expect two SHAs in the form of <old>..<new>")
			}

			if file.IsDeleted() {
				file.Index = shas[0]
			} else {
				file.Index = shas[1]
			}
			break checkType
		case strings.HasPrefix(line, "similarity index "):
			file.Type = DiffFileRename
			file.oldName = a
			file.Name = b

			// No need to look for index if it's a pure rename
			if strings.HasSuffix(line, "100%") {
				break checkType
			}
		case strings.HasPrefix(line, "old mode"):
			break checkType
		}
	}

	return file, nil
}

func (p *diffParser) parseSection() (_ *DiffSection, isIncomplete bool, _ error) {
	line := string(p.buffer)
	p.buffer = nil

	section := &DiffSection{
		Lines: []*DiffLine{
			{
				Type:    DiffLineSection,
				Content: line,
			},
		},
	}

	// Parse line number, e.g. @@ -0,0 +1,3 @@
	var leftLine, rightLine int
	ss := strings.Split(line, "@@")
	ranges := strings.Split(ss[1][1:], " ")
	leftLine, _ = strconv.Atoi(strings.Split(ranges[0], ",")[0][1:])
	if len(ranges) > 1 {
		rightLine, _ = strconv.Atoi(strings.Split(ranges[1], ",")[0])
	} else {
		rightLine = leftLine
	}

	var err error
	for !p.isEOF {
		if err = p.readLine(); err != nil {
			return nil, false, err
		}

		if len(p.buffer) == 0 {
			p.buffer = nil
			continue
		}

		// Make sure we're still in the section. If not, we're done with this section.
		if p.buffer[0] != ' ' &&
			p.buffer[0] != '+' &&
			p.buffer[0] != '-' {

			// No new line indicator
			if p.buffer[0] == '\\' &&
				bytes.HasPrefix(p.buffer, []byte(`\ No newline at end of file`)) {
				p.buffer = nil
				continue
			}
			return section, false, nil
		}

		line := string(p.buffer)
		p.buffer = nil

		// Too many characters in a single diff line
		if p.maxLineChars > 0 && len(line) > p.maxLineChars {
			return section, true, nil
		}

		switch line[0] {
		case ' ':
			section.Lines = append(section.Lines, &DiffLine{
				Type:      DiffLinePlain,
				Content:   line,
				LeftLine:  leftLine,
				RightLine: rightLine,
			})
			leftLine++
			rightLine++
		case '+':
			section.Lines = append(section.Lines, &DiffLine{
				Type:      DiffLineAdd,
				Content:   line,
				RightLine: rightLine,
			})
			section.numAdditions++
			rightLine++
		case '-':
			section.Lines = append(section.Lines, &DiffLine{
				Type:     DiffLineDelete,
				Content:  line,
				LeftLine: leftLine,
			})
			section.numDeletions++
			if leftLine > 0 {
				leftLine++
			}
		}
	}

	return section, false, nil
}

func (p *diffParser) parse() (*Diff, error) {
	diff := new(Diff)
	file := new(DiffFile)
	currentFileLines := 0

	var err error
	for !p.isEOF {
		if err = p.readLine(); err != nil {
			return nil, err
		}

		if len(p.buffer) == 0 ||
			bytes.HasPrefix(p.buffer, []byte("+++ ")) ||
			bytes.HasPrefix(p.buffer, []byte("--- ")) {
			p.buffer = nil
			continue
		}

		// Found new file
		if bytes.HasPrefix(p.buffer, diffHead) {
			// Check if reached maximum number of files
			if p.maxFiles > 0 && len(diff.Files) >= p.maxFiles {
				diff.isIncomplete = true
				_, _ = io.Copy(ioutil.Discard, p)
				break
			}

			file, err = p.parseFileHeader()
			if err != nil {
				return nil, err
			}
			diff.Files = append(diff.Files, file)

			currentFileLines = 0
			continue
		}

		if file == nil || file.isIncomplete {
			p.buffer = nil
			continue
		}

		if bytes.HasPrefix(p.buffer, []byte("Binary")) {
			p.buffer = nil
			file.isBinary = true
			continue
		}

		// Loop until we found section header
		if p.buffer[0] != '@' {
			p.buffer = nil
			continue
		}

		// Too many diff lines for the file
		if p.maxFileLines > 0 && currentFileLines > p.maxFileLines {
			file.isIncomplete = true
			diff.isIncomplete = true
			continue
		}

		section, isIncomplete, err := p.parseSection()
		if err != nil {
			return nil, err
		}
		file.Sections = append(file.Sections, section)
		file.numAdditions += section.numAdditions
		file.numDeletions += section.numDeletions
		diff.totalAdditions += section.numAdditions
		diff.totalDeletions += section.numDeletions
		currentFileLines += section.NumLines()
		if isIncomplete {
			file.isIncomplete = true
			diff.isIncomplete = true
		}
	}

	return diff, nil
}

// StreamParseDiff parses the diff read from the given io.Reader. It does parse-on-read to minimize
// the time spent on huge diffs. It accepts a channel to notify and send error (if any) to the caller
// when the process is done. Therefore, this method should be called in a goroutine asynchronously.
func StreamParseDiff(r io.Reader, done chan<- SteamParseDiffResult, maxFiles, maxFileLines, maxLineChars int) {
	p := &diffParser{
		Reader:       bufio.NewReader(r),
		maxFiles:     maxFiles,
		maxFileLines: maxFileLines,
		maxLineChars: maxLineChars,
	}
	diff, err := p.parse()
	done <- SteamParseDiffResult{
		Diff: diff,
		Err:  err,
	}
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    <%=formalEntityName%> = mongoose.model('<%=formalEntityName%>'),
    _ = require('lodash');

/**
 * Find <%=entityName%> by id
 */
exports.<%=entityName%> = function(req, res, next, id) {
    <%=formalEntityName%>.load(id, function(err, <%=entityName%>) {
        if (err) return next(err);
        if (!<%=entityName%>) return next(new Error('Failed to load <%=entityName%> ' + id));
        req.<%=entityName%> = <%=entityName%>;
        next();
    });
};

/**
 * Create an <%=entityName%>
 */
exports.create = function(req, res) {
    var <%=entityName%> = new <%=formalEntityName%>(req.body);
                <%=entityName%>.user = req.user;

                <%=entityName%>.save(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                <%=entityName%>: <%=entityName%>
            });
        } else {
            res.jsonp(<%=entityName%>);
        }
    });
};

/**
 * Update an <%=entityName%>
 */
exports.update = function(req, res) {
    var <%=entityName%> = req.<%=entityName%>;

    <%=entityName%> = _.extend(<%=entityName%>, req.body);

    <%=entityName%>.save(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                <%=entityName%>: <%=entityName%>
            });
        } else {
            res.jsonp(<%=entityName%>);
        }
    });
};

/**
 * Delete an <%=entityName%>
 */
exports.destroy = function(req, res) {
    var <%=entityName%> = req.<%=entityName%>;

    <%=entityName%>.remove(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                <%=entityName%>: <%=entityName%>
            });
        } else {
            res.jsonp(<%=entityName%>);
        }
    });
};

/**
 * Show an <%=entityName%>
 */
exports.show = function(req, res) {
    res.jsonp(req.<%=entityName%>);
};

/**
 * List of <%=formalEntityName%>s
 */
exports.all = function(req, res) {
    <%=formalEntityName%>.find().sort('-created').populate('user', 'name username').exec(function(err, <%=entityName%>s) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(<%=entityName%>s);
        }
    });
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

Morphers for primitive types.


text:
package org.tinymediamanager.scraper.mediaprovider;

import java.util.List;

import org.tinymediamanager.scraper.entities.MediaType;

/**
 * just a dedicated interface, for JSPF to find all "special" Kodi impls.<br>
 *
 * @author Myron Boyle
 *
 */
public interface IKodiMetadataProvider extends IMediaProvider {
  /**
   * get all Kodi scraper-plugins for the desired type
   *
   * @param type
   *          the desired media type
   * @return all found plugins
   */
  public List<IMediaProvider> getPluginsForType(MediaType type);
}


text:
using System;
using System.Reflection;
using CSF.Entities;
using NHibernate.Mapping.ByCode;
using Agiil.Data.MappingProviders;

namespace Agiil.Data.ConventionMappings
{
  public class PropertyMapping : IConventionMapping
  {
    readonly IDbNameFormatter formatter;
    readonly IGetsWhetherPropertyShouldBeMapped ignoredPropertiesProvider;

    public void ApplyMapping(ConventionModelMapper mapper)
    {
      mapper.IsPersistentProperty((member, declared) => {
        var property = member as PropertyInfo;

        if(property == null || !property.CanRead)
          return false;

        if(IsIdentityProperty(property))
          return false;

        if(property.ReflectedType.GetProperty(property.Name, BindingFlags.Instance | BindingFlags.Public) == null)
          return false;

        if(!ignoredPropertiesProvider.ShouldMapProperty(property))
          return false;

        return true;
      });

      mapper.BeforeMapProperty += (modelInspector, member, propertyCustomizer) => {
        propertyCustomizer.Column(formatter.GetColumnName(member.LocalMember));
      };
    }

    bool IsIdentityProperty(PropertyInfo property)
    {
      return (property.Name == IdentityMapping.IdentityPropertyName
              && property.PropertyType == typeof(long)
              && property.DeclaringType == typeof(Entity<long>));
    }

    public PropertyMapping(IDbNameFormatter formatter,
                           IGetsWhetherPropertyShouldBeMapped ignoredPropertiesProvider)
    {
      this.formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
      this.ignoredPropertiesProvider = ignoredPropertiesProvider ?? throw new ArgumentNullException(nameof(ignoredPropertiesProvider));
    }
  }
}


text:
package main

import (
	"github.com/go-kit/kit/log"
	httptransport "github.com/go-kit/kit/transport/http"

	"github.com/micromdm/micromdm/dep/depsync"
	"github.com/micromdm/micromdm/platform/appstore"
	"github.com/micromdm/micromdm/platform/blueprint"
	"github.com/micromdm/micromdm/platform/config"
	"github.com/micromdm/micromdm/platform/dep"
	"github.com/micromdm/micromdm/platform/device"
	"github.com/micromdm/micromdm/platform/profile"
	"github.com/micromdm/micromdm/platform/remove"
	"github.com/micromdm/micromdm/platform/user"
)

type remoteServices struct {
	profilesvc   profile.Service
	blueprintsvc blueprint.Service
	blocksvc     remove.Service
	usersvc      user.Service
	devicesvc    device.Service
	configsvc    config.Service
	appsvc       appstore.Service
	depsvc       dep.Service
	depsyncsvc   depsync.Service
}

func setupClient(logger log.Logger) (*remoteServices, error) {
	cfg, err := LoadServerConfig()
	if err != nil {
		return nil, err
	}

	profilesvc, err := profile.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	blueprintsvc, err := blueprint.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	blocksvc, err := remove.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	usersvc, err := user.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	devicesvc, err := device.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	configsvc, err := config.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	appsvc, err := appstore.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	depsvc, err := dep.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	depsyncsvc, err := depsync.NewHTTPClient(
		cfg.ServerURL, cfg.APIToken, logger,
		httptransport.SetClient(skipVerifyHTTPClient(cfg.SkipVerify)))
	if err != nil {
		return nil, err
	}

	return &remoteServices{
		profilesvc:   profilesvc,
		blueprintsvc: blueprintsvc,
		blocksvc:     blocksvc,
		usersvc:      usersvc,
		devicesvc:    devicesvc,
		configsvc:    configsvc,
		appsvc:       appsvc,
		depsvc:       depsvc,
		depsyncsvc:   depsyncsvc,
	}, nil
}


text:
package com.bumptech.glide.request.target;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.RemoteViews;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowNotificationManager;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 18, shadows = NotificationTargetTest
    .UpdateShadowNotificationManager.class)
public class NotificationTargetTest {
  private UpdateShadowNotificationManager shadowManager;
  private RemoteViews remoteViews;
  private int viewId;
  private Notification notification;
  private int notificationId;
  private String notificationTag;
  private NotificationTarget target;

  @Before
  public void setUp() {
    NotificationManager notificationManager =
        (NotificationManager)
            RuntimeEnvironment.application.getSystemService(Context.NOTIFICATION_SERVICE);
    shadowManager = Shadow.extract(notificationManager);

    remoteViews = mock(RemoteViews.class);
    viewId = 123;
    notification = mock(Notification.class);
    notificationId = 456;
    notificationTag = "tag";

    target =
        new NotificationTarget(RuntimeEnvironment.application, 100 /*width*/, 100 /*height*/,
            viewId, remoteViews, notification, notificationId, notificationTag);
  }

  @Test
  public void testSetsBitmapOnRemoteViewsWithGivenImageIdOnResourceReady() {
    Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    target.onResourceReady(bitmap, null /*glideAnimation*/);
    verify(remoteViews).setImageViewBitmap(eq(viewId), eq(bitmap));
  }

  @Test
  public void updatesNotificationManagerWithNotificationIdAndNotificationOnResourceReady() {
    target.onResourceReady(Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888), null
    /*glideAnimation*/);

    assertEquals(notificationId, shadowManager.updatedNotificationId);
    assertEquals(notificationTag, shadowManager.updatedNotificationTag);
    assertEquals(notification, shadowManager.updatedNotification);
  }

  @Test(expected = NullPointerException.class)
  public void testThrowsIfContextIsNull() {
    new NotificationTarget(null /*context*/, 100 /*width*/, 100 /*height*/,
        123 /*viewId*/, mock(RemoteViews.class), mock(Notification.class), 456 /*notificationId*/,
        "tag" /*notificationTag*/);
  }

  @Test(expected = NullPointerException.class)
  public void testThrowsIfNotificationIsNull() {
    new NotificationTarget(RuntimeEnvironment.application, 100 /*width*/, 100 /*height*/,
        123 /*viewId*/, mock(RemoteViews.class), null /*notification*/, 456 /*notificationId*/,
        "tag" /*notificationTag*/);
  }

  @Test(expected = NullPointerException.class)
  public void testThrowsIfRemoteViewsIsNull() {
    new NotificationTarget(RuntimeEnvironment.application, 100 /*width*/, 100 /*height*/,
        123 /*viewId*/, null /*remoteViews*/, mock(Notification.class), 456 /*notificationId*/,
        "tag" /*notificationTag*/);
  }

  @Implements(NotificationManager.class)
  public static class UpdateShadowNotificationManager extends ShadowNotificationManager {
    int updatedNotificationId;
    String updatedNotificationTag;
    Notification updatedNotification;

    @Implementation
    public void notify(String notificationTag, int notificationId, Notification notification) {
      updatedNotificationTag = notificationTag;
      updatedNotificationId = notificationId;
      updatedNotification = notification;
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<analysisEngineDescription xmlns="http://uima.apache.org/resourceSpecifier">
  <frameworkImplementation>org.apache.uima.java</frameworkImplementation>
  <primitive>true</primitive>
  <annotatorImplementationName>fr.univnantes.lina.uima.nlp.ConcordancerAE</annotatorImplementationName>
  <analysisEngineMetaData>
    <name>(Simple) Concordancer</name>
    <description/>
    <version/>
    <vendor/>
    <configurationParameters>
      <configurationParameter>
        <name>Patterns</name>
        <type>String</type>
        <multiValued>true</multiValued>
        <mandatory>true</mandatory>
      </configurationParameter>
      <configurationParameter>
        <name>WindowSize</name>
        <type>Integer</type>
        <multiValued>false</multiValued>
        <mandatory>true</mandatory>
      </configurationParameter>
    </configurationParameters>
    <configurationParameterSettings>
      <nameValuePair>
        <name>Patterns</name>
        <value>
          <array>
            <string>fr.univnantes.lina.uima.types.Person</string>
            <string>fr.univnantes.lina.uima.types.Profession</string>
          </array>
        </value>
      </nameValuePair>
    </configurationParameterSettings>
    <typeSystemDescription/>
    <typePriorities/>
    <fsIndexCollection/>
    <capabilities>
      <capability>
        <inputs/>
        <outputs/>
        <languagesSupported/>
      </capability>
    </capabilities>
    <operationalProperties>
      <modifiesCas>true</modifiesCas>
      <multipleDeploymentAllowed>true</multipleDeploymentAllowed>
      <outputsNewCASes>false</outputsNewCASes>
    </operationalProperties>
  </analysisEngineMetaData>
  <resourceManagerConfiguration/>
</analysisEngineDescription>


text:
@interface GRMessagesInputToolbarButtonFactroy : NSObject
+ (UIButton *)defaultAccessoryButtonItem;

+ (UIButton *)defaultVoiceButtonItem;

+ (UIButton *)defaultSecondAccessoryButtonItem;

@end


text:
/* // It returns false if n is composite and returns true if n
// is probably prime.  k is an input parameter that determines
// accuracy level. Higher value of k indicates more accuracy.
bool isPrime(int n, int k)
1) Handle base cases for n < 3
2) If n is even, return false.
3) Find an odd number d such that n-1 can be written as d*2r.
   Note that since n is odd, (n-1) must be even and r must be
   greater than 0.
4) Do following k times
     if (millerTest(n, d) == false)
          return false
5) Return true.

// This function is called for all k trials. It returns
// false if n is composite and returns false if n is probably
// prime.
// d is an odd number such that  d*2r = n-1 for some r >= 1
bool millerTest(int n, int d)
1) Pick a random number 'a' in range [2, n-2]
2) Compute: x = pow(a, d) % n
3) If x == 1 or x == n-1, return true.

// Below loop mainly runs 'r-1' times.
4) Do following while d doesn't become n-1.
     a) x = (x*x) % n.
     b) If (x == 1) return false.
     c) If (x == n-1) return true.  */

// C++ program Miller-Rabin primality test
#include <bits/stdc++.h>
using namespace std;

// Utility function to do modular exponentiation.
// It returns (x^y) % p
int power(int x, unsigned int y, int p)
{
    int res = 1;      // Initialize result
    x = x % p;  // Update x if it is more than or
                // equal to p
    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res*x) % p;

        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

// This function is called for all k trials. It returns
// false if n is composite and returns false if n is
// probably prime.
// d is an odd number such that  d*2r = n-1
// for some r >= 1
bool miillerTest(int d, int n)
{
    // Pick a random number in [2..n-2]
    // Corner cases make sure that n > 4
    int a = 2 + rand() % (n - 4);

    // Compute a^d % n
    int x = power(a, d, n);

    if (x == 1  || x == n-1)
       return true;

    // Keep squaring x while one of the following doesn't
    // happen
    // (i)   d does not reach n-1
    // (ii)  (x^2) % n is not 1
    // (iii) (x^2) % n is not n-1
    while (d != n-1)
    {
        x = (x * x) % n;
        d *= 2;

        if (x == 1)      return false;
        if (x == n-1)    return true;
    }

    // Return composite
    return false;
}

// It returns false if n is composite and returns true if n
// is probably prime.  k is an input parameter that determines
// accuracy level. Higher value of k indicates more accuracy.
bool isPrime(int n, int k)
{
    // Corner cases
    if (n <= 1 || n == 4)  return false;
    if (n <= 3) return true;

    // Find r such that n = 2^d * r + 1 for some r >= 1
    int d = n - 1;
    while (d % 2 == 0)
        d /= 2;

    // Iterate given nber of 'k' times
    for (int i = 0; i < k; i++)
         if (miillerTest(d, n) == false)
              return false;

    return true;
}


text:
// This file is auto gererated by build/build-entry.js

import VeCheckbox from './ve-checkbox';
import VeCheckboxGroup from './ve-checkbox-group';
import VeContextmenu from './ve-contextmenu';
import VeDropdown from './ve-dropdown';
import VeIcon from './ve-icon';
import VeLoading from './ve-loading';
import VeLocale from './ve-locale';
import VePagination from './ve-pagination';
import VeRadio from './ve-radio';
import VeSelect from './ve-select';
import VeTable from './ve-table';

const version = '2.13.1';
const components = [
  VeCheckbox,
  VeCheckboxGroup,
  VeContextmenu,
  VeDropdown,
  VeIcon,
  VeLoading,
  VeLocale,
  VePagination,
  VeRadio,
  VeSelect,
  VeTable
];

const install = Vue => {
  components.forEach(Component => {
    Vue.use(Component);
  });

  Vue.prototype.$veLoading = VeLoading;
  Vue.prototype.$veLocale = VeLocale;
};

/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}

export {
  install,
  version,
  VeCheckbox,
  VeCheckboxGroup,
  VeContextmenu,
  VeDropdown,
  VeIcon,
  VeLoading,
  VeLocale,
  VePagination,
  VeRadio,
  VeSelect,
  VeTable
};

export default {
  install,
  version,
  VeCheckbox,
  VeCheckboxGroup,
  VeContextmenu,
  VeDropdown,
  VeIcon,
  VeLoading,
  VeLocale,
  VePagination,
  VeRadio,
  VeSelect,
  VeTable
};


text:
> Stringify any JavaScript value.

- Supports [all built-in JavaScript types](#type-support)
- [Blazingly fast](https://gist.github.com/thejameskyle/2b04ffe4941aafa8f970de077843a8fd) (similar performance to v8's `JSON.stringify` and significantly faster than Node's `util.format`)
- Plugin system for extending with custom types (i.e. [`ReactTestComponent`](#reacttestcomponent-plugin))

## Installation

```sh
$ npm install pretty-format
```

## Usage

```js
var prettyFormat = require('pretty-format');

var obj = { property: {} };
obj.circularReference = obj;
obj[Symbol('foo')] = 'foo';
obj.map = new Map();
obj.map.set('prop', 'value');
obj.array = [1, NaN, Infinity];

console.log(prettyFormat(obj));
```

**Result:**

```js
Object {
  "property": Object {},
  "circularReference": [Circular],
  "map": Map {
    "prop" => "value"
  },
  "array": Array [
    1,
    NaN,
    Infinity
  ],
  Symbol(foo): "foo"
}
```

#### Type Support

`Object`, `Array`, `ArrayBuffer`, `DataView`, `Float32Array`, `Float64Array`, `Int8Array`, `Int16Array`, `Int32Array`, `Uint8Array`, `Uint8ClampedArray`, `Uint16Array`, `Uint32Array`, `arguments`, `Boolean`, `Date`, `Error`, `Function`, `Infinity`, `Map`, `NaN`, `null`, `Number`, `RegExp`, `Set`, `String`, `Symbol`, `undefined`, `WeakMap`, `WeakSet`

### Plugins

Pretty format also supports adding plugins:

```js
var fooPlugin = {
  test: function(val) {
    return val && val.hasOwnProperty('foo');
  },
  print: function(val, print, indent) {
    return 'Foo: ' + print(val.foo);
  }
};

var obj = { foo: { bar: {} } };

prettyFormat(obj, {
  plugins: [fooPlugin]
});
// Foo: Object {
//   "bar": Object {}
// }
```

#### `ReactTestComponent` plugin

```js
var prettyFormat = require('pretty-format');
var reactPlugin = require('pretty-format/plugins/ReactTestComponent');

var React = require('react');
var renderer = require('react/lib/ReactTestRenderer');

var jsx = React.createElement('h1', null, 'Hello World');

prettyFormat(renderer.create(jsx).toJSON(), {
  plugins: [reactPlugin]
});
// <h1>
//   Hello World
// </h1>
```


text:
package org.gearvrf.accessibility;

import org.gearvrf.GVRContext;
import org.gearvrf.GVRShader;
import org.gearvrf.GVRShaderTemplate;
import org.gearvrf.R;
import org.gearvrf.utility.TextFile;

/**
 * Shader to invert colors by post processing rendered image from cameras.
 */
public class GVRAccessibilityPostEffectShader  extends GVRShaderTemplate {
    static String fragmentSource;
    static String vertexSource;

    public GVRAccessibilityPostEffectShader(GVRContext context) {
        super("", "sampler2D u_texture", "float3 a_position float2 a_texcoord", GVRShader.GLSLESVersion.VULKAN);
        if (vertexSource == null)
        {
            vertexSource = TextFile.readTextFile(context.getContext(), R.raw.inverted_colors_vertex);
        }
        if (fragmentSource == null)
        {
            fragmentSource = TextFile.readTextFile(context.getContext(), R.raw.inverted_colors_fragment);
        }
        setSegment("VertexTemplate", vertexSource);
        setSegment("FragmentTemplate", fragmentSource);
    }
}