text:
/**
 * This package contains advanced versions of the predicate functional interfaces defined in the JDK package
 * {@link java.util.function}. The advanced versions include e.g. more boolean combinators for predicate results.
 * @author Max Bureck
 */
package de.boereck.matcher.function.predicate;

redpajama_set_name: RedPajamaGithub


text:
define(function()
{
    "use strict";
    var Action = {};

    Action.ADD_CELL_CANDIDATE = "addCellCandidate";
    Action.BATCH_REMOVE_CANDIDATES = "batchRemoveCandidates";
    Action.REMOVE_CELL_CANDIDATE = "removeCellCandidate";
    Action.SET_CELL_VALUE = "setCellValue";
    Action.SET_PUZZLE = "setPuzzle";
    Action.SET_SELECTED_INDEX = "setSelectedIndex";
    Action.SET_SOLVER = "setSolver";

    Action.addCellCandidate = function(index, candidate)
    {
        InputValidator.validateIsNumber("index", index);
        InputValidator.validateIsNumber("candidate", candidate);

        return (
        {
            type: Action.ADD_CELL_CANDIDATE,
            index: index,
            candidate: candidate,
        });
    };

    Action.batchRemoveCandidates = function(indices, candidates)
    {
        InputValidator.validateNotNull("indices", indices);
        InputValidator.validateNotNull("candidates", candidates);

        return (
        {
            type: Action.BATCH_REMOVE_CANDIDATES,
            indices: indices,
            candidates: candidates,
        });
    };

    Action.removeCellCandidate = function(index, candidate)
    {
        InputValidator.validateIsNumber("index", index);
        InputValidator.validateIsNumber("candidate", candidate);

        return (
        {
            type: Action.REMOVE_CELL_CANDIDATE,
            index: index,
            candidate: candidate,
        });
    };

    Action.setCellValue = function(index, value)
    {
        InputValidator.validateIsNumber("index", index);
        InputValidator.validateIsNumber("value", value);

        return (
        {
            type: Action.SET_CELL_VALUE,
            index: index,
            value: value,
        });
    };

    Action.setPuzzle = function(puzzle)
    {
        InputValidator.validateNotNull("puzzle", puzzle);

        return (
        {
            type: Action.SET_PUZZLE,
            puzzle: puzzle,
        });
    };

    Action.setSelectedIndex = function(index)
    {
        InputValidator.validateIsNumber("index", index);

        return (
        {
            type: Action.SET_SELECTED_INDEX,
            index: index,
        });
    };

    Action.setSolver = function(solver)
    {
        InputValidator.validateNotNull("solver", solver);

        return (
        {
            type: Action.SET_SOLVER,
            solver: solver,
        });
    };

    if (Object.freeze)
    {
        Object.freeze(Action);
    }

    return Action;
});


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Graphics;
using osu.Game.Overlays.Dialog;

namespace osu.Game.Screens.Select
{
    public class BeatmapDeleteDialog : PopupDialog
    {
        private BeatmapDatabase database;

        [BackgroundDependencyLoader]
        private void load(BeatmapDatabase beatmapDatabase)
        {
            database = beatmapDatabase;
        }

        public BeatmapDeleteDialog(WorkingBeatmap beatmap)
        {
            Icon = FontAwesome.fa_trash_o;
            HeaderText = @"Confirm deletion of";
            BodyText = $@"{beatmap?.Beatmap?.Metadata?.Artist} - {beatmap?.Beatmap?.Metadata?.Title}";
            Buttons = new PopupDialogButton[]
            {
                new PopupDialogOkButton
                {
                    Text = @"Yes. Totally. Delete it.",
                    Action = () =>
                    {
                        beatmap.Dispose();
                        database.Delete(beatmap.BeatmapSetInfo);
                    },
                },
                new PopupDialogCancelButton
                {
                    Text = @"Firetruck, I didn't mean to!",
                },
            };
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace SiteAnalyzerBundle\Page;

use SiteAnalyzerBundle\Resource\HtmlPage;
use Symfony\Component\DomCrawler\Crawler as SymfonyDomCrawler;

/**
 * Analyze html page.
 * TODO:...
 */
class PageAnalyzer
{
    protected $htmlPage;

    public function __construct()
    {
    }

}


text:
@implementation ASTextLine {
  CGFloat _firstGlyphPos; // first glyph position for baseline, typically 0.
}

+ (instancetype)lineWithCTLine:(CTLineRef)CTLine position:(CGPoint)position vertical:(BOOL)isVertical NS_RETURNS_RETAINED {
  if (!CTLine) return nil;
  ASTextLine *line = [self new];
  line->_position = position;
  line->_vertical = isVertical;
  [line setCTLine:CTLine];
  return line;
}

- (void)dealloc {
  if (_CTLine) CFRelease(_CTLine);
}

- (void)setCTLine:(_Nonnull CTLineRef)CTLine {
  if (_CTLine != CTLine) {
    if (CTLine) CFRetain(CTLine);
    if (_CTLine) CFRelease(_CTLine);
    _CTLine = CTLine;
    if (_CTLine) {
      _lineWidth = CTLineGetTypographicBounds(_CTLine, &_ascent, &_descent, &_leading);
      CFRange range = CTLineGetStringRange(_CTLine);
      _range = NSMakeRange(range.location, range.length);
      if (CTLineGetGlyphCount(_CTLine) > 0) {
        CFArrayRef runs = CTLineGetGlyphRuns(_CTLine);
        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, 0);
        CGPoint pos;
        CTRunGetPositions(run, CFRangeMake(0, 1), &pos);
        _firstGlyphPos = pos.x;
      } else {
        _firstGlyphPos = 0;
      }
      _trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(_CTLine);
    } else {
      _lineWidth = _ascent = _descent = _leading = _firstGlyphPos = _trailingWhitespaceWidth = 0;
      _range = NSMakeRange(0, 0);
    }
    [self reloadBounds];
  }
}

- (void)setPosition:(CGPoint)position {
  _position = position;
  [self reloadBounds];
}

- (void)reloadBounds {
  if (_vertical) {
    _bounds = CGRectMake(_position.x - _descent, _position.y, _ascent + _descent, _lineWidth);
    _bounds.origin.y += _firstGlyphPos;
  } else {
    _bounds = CGRectMake(_position.x, _position.y - _ascent, _lineWidth, _ascent + _descent);
    _bounds.origin.x += _firstGlyphPos;
  }

  _attachments = nil;
  _attachmentRanges = nil;
  _attachmentRects = nil;
  if (!_CTLine) return;
  CFArrayRef runs = CTLineGetGlyphRuns(_CTLine);
  NSUInteger runCount = CFArrayGetCount(runs);
  if (runCount == 0) return;

  NSMutableArray *attachments = [NSMutableArray new];
  NSMutableArray *attachmentRanges = [NSMutableArray new];
  NSMutableArray *attachmentRects = [NSMutableArray new];
  for (NSUInteger r = 0; r < runCount; r++) {
    CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, r);
    CFIndex glyphCount = CTRunGetGlyphCount(run);
    if (glyphCount == 0) continue;
    NSDictionary *attrs = (id)CTRunGetAttributes(run);
    ASTextAttachment *attachment = attrs[ASTextAttachmentAttributeName];
    if (attachment) {
      CGPoint runPosition = CGPointZero;
      CTRunGetPositions(run, CFRangeMake(0, 1), &runPosition);

      CGFloat ascent, descent, leading, runWidth;
      CGRect runTypoBounds;
      runWidth = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, &leading);

      if (_vertical) {
        ASTEXT_SWAP(runPosition.x, runPosition.y);
        runPosition.y = _position.y + runPosition.y;
        runTypoBounds = CGRectMake(_position.x + runPosition.x - descent, runPosition.y , ascent + descent, runWidth);
      } else {
        runPosition.x += _position.x;
        runPosition.y = _position.y - runPosition.y;
        runTypoBounds = CGRectMake(runPosition.x, runPosition.y - ascent, runWidth, ascent + descent);
      }

      NSRange runRange = ASTextNSRangeFromCFRange(CTRunGetStringRange(run));
      [attachments addObject:attachment];
      [attachmentRanges addObject:[NSValue valueWithRange:runRange]];
      [attachmentRects addObject:[NSValue valueWithCGRect:runTypoBounds]];
    }
  }
  _attachments = attachments.count ? attachments : nil;
  _attachmentRanges = attachmentRanges.count ? attachmentRanges : nil;
  _attachmentRects = attachmentRects.count ? attachmentRects : nil;
}

- (CGSize)size {
  return _bounds.size;
}

- (CGFloat)width {
  return CGRectGetWidth(_bounds);
}

- (CGFloat)height {
  return CGRectGetHeight(_bounds);
}

- (CGFloat)top {
  return CGRectGetMinY(_bounds);
}

- (CGFloat)bottom {
  return CGRectGetMaxY(_bounds);
}

- (CGFloat)left {
  return CGRectGetMinX(_bounds);
}

- (CGFloat)right {
  return CGRectGetMaxX(_bounds);
}

- (NSString *)description {
  NSMutableString *desc = @"".mutableCopy;
  NSRange range = self.range;
  [desc appendFormat:@"<ASTextLine: %p> row:%zd range:%tu,%tu",self, self.row, range.location, range.length];
  [desc appendFormat:@" position:%@",NSStringFromCGPoint(self.position)];
  [desc appendFormat:@" bounds:%@",NSStringFromCGRect(self.bounds)];
  return desc;
}

@end

@implementation ASTextRunGlyphRange
+ (instancetype)rangeWithRange:(NSRange)range drawMode:(ASTextRunGlyphDrawMode)mode NS_RETURNS_RETAINED {
  ASTextRunGlyphRange *one = [self new];
  one.glyphRangeInRun = range;
  one.drawMode = mode;
  return one;
}
@end


text:
require 'spec_helper'
require 'omniauth-delicious-oauth2'

describe OmniAuth::Strategies::DeliciousOauth2 do
  let(:request) { double('Request', :params => {}, :cookies => {}, :env => {}) }
  let(:app) {
    lambda do
      [200, {}, ["Hello."]]
    end
  }

  subject do
    OmniAuth::Strategies::DeliciousOauth2.new(app, 'appid', 'secret', @options || {}).tap do |strategy|
      allow(strategy).to receive(:request) {
        request
      }
    end
  end

  before do
    OmniAuth.config.test_mode = true
  end

  after do
    OmniAuth.config.test_mode = false
  end

  describe '#client_options' do
    it 'has correct site' do
      expect(subject.client.site).to eq('https://accounts.delicious.com')
    end

    it 'has correct authorize_url' do
      expect(subject.client.options[:authorize_url]).to eq('/o/oauth2/auth')
    end
  end
end


text:
export * from './alerts';
export * from './icons';
export * from './input';
export * from './loaders';
export * from './overlays';
export * from './panels';
export * from './react-bootstrap';
export * from './table';
export * from './utils';


text:
<!DOCTYPE html>

    <title>ArcGIS Developers 開発リソース集</title>

      <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="revised" content="2022-11-10T15:09:42 JST">
<title>Android :: ArcGIS Developers 開発リソース集</title>
<link rel="shortcut icon" href="/arcgis-dev-resources/images/favicon.png" type="image/x-icon" />
<link href="/arcgis-dev-resources/css/nucleus.css" rel="stylesheet">
<link href="/arcgis-dev-resources/css/font-awesome.min.css" rel="stylesheet">
<link href="/arcgis-dev-resources/css/hybrid.css" rel="stylesheet">
<link href="/arcgis-dev-resources/css/featherlight.min.css" rel="stylesheet">
<link href="/arcgis-dev-resources/css/auto-complete.css" rel="stylesheet">
<link href="/arcgis-dev-resources/theme-original/style.css" rel="stylesheet">

<link rel="stylesheet" href="/arcgis-dev-resources/css/bootstrap.min.css">

<meta name="description" content="ArcGIS Runtime SDK for Android を用いたモバイル地図アプリの作成方法を紹介します。">

    ArcGIS Developers 開発リソース集

		    <input data-search-input id="search-by" type="text" placeholder="検索...">

      スタートアップ ガイド

            開発者アカウントの作成

            API キーの取得

      ロケーションサービスの利用

            フィーチャサービスの作成

            Web マップの作成

      アプリ開発

            ArcGIS API for JavaScript

            Esri Leaflet

            MapLibre GL JS

            OpenLayers

            Android

            iOS

            .NET

            セキュリティと認証

            デプロイ

      もっと学ぶ

            Esri Japan GitHub

            ArcGIS 開発者コミュニティ

      技術 Tips 集

      ArcGIS API for JavaScript

            インストールおよびセットアップ方法

            インストール ガイド

            バージョン 4.x と 3.x の選択

            バージョン 3.x から 4.x への移行

            ウィジェット開発

            Arcade

            カスタム フォント

      ArcGIS Experience Builder (Developer Edition)

      コア コンセプト

            ページ(Page)

            ウィンドウ(Window)

            セクションとビュー(Section and view)

            画面グループ(Screen groups)

            レイアウト(Layout)

            テーマ(Theme)

            ウィジェット(Widget)

            Jimu

            データ ソース(Data source)

            データアクション(Data action)

            メッセージ と アクション(Message and action)

            マップ/シーン ビュー(Map/Scene View)

            拡張ポイント(Extension points)

            インストール ガイド

      カスタム ウィジェット開発ガイド

            ウィジェット開発のスタート

            ウィジェット manifest

            ウィジェットの実装

            ウィジェット UI の作成

            ウィジェットでデータソースを使用

            ウィジェット間の通信

            ウィジェット開発のデバック

            サードパーティ製のライブラリ使用

            単体テスト

            assets の使用

            コードリンティング

            デプロイ パターン

            デプロイ

            チュートリアル

      ArcGIS Web AppBuilder (Developer Edition)

            インストール ガイド

            カスタム ウィジェット開発ガイド

            デプロイ パターン

            Web アプリケーションのデプロイ

      ウィジェット一覧表

            ウィジェット一覧表 (ArcGIS Online)

            ウィジェット一覧表 (ArcGIS Enterprise)

            ウィジェット一覧表 (Developer Edition)

      ArcGIS Runtime SDK for .NET

            インストール ガイド

            アプリケーション配布ガイド

            バージョン 10.2.x から 100.x への移行

      ArcGIS Runtime SDK for Android

            インストール ガイド

            アプリケーション配布ガイド

            バージョン 10.2.x から 100.x への移行

      ArcGIS Runtime SDK for iOS

            インストール ガイド

            アプリケーション配布ガイド

            バージョン 10.2.x から 100.x への移行

      ArcGIS API for Python

            ArcGIS API for Python のコンセプト

            ArcGIS API for Python のための基礎環境:conda入門

            インストール ガイド

            Jupyter Notebook を使ってみよう

            Jupyter Lab を使ってみよう

            スクリプト実行の自動化

            matplotlib での日本語利用について

      ArcGIS Pro SDK

      ArcGIS AppStudio

      Calcite Design System

            はじめに

            Web コンセプト

            アクセシビリティ

            ローカライゼーション

            フレームワークの統合

            チュートリアル

      その他

      データ ビジュアライゼーション

            データ可視化のワークフロー

            データ可視化の手順

            地図上に賢くデータを可視化するための 6 つの方法

      サンプル集

            ミートアップ

 Github

© Esri Japan. All rights reserved.

 ArcGIS Developers 開発リソース集 > スタートアップ ガイド > アプリ開発 > Android

前提条件

ステップ

新しい Android Studio プロジェクトを作成します

インポートステートメントを追加する

マップビューの UI を追加する

マップを追加する

API キーを設定する

Android

マップを表示する

このチュートリアルでは ArcGIS Runtime SDK for Android を使用して、マップとベースマップ レイヤーを表示する方法を紹介します。

マップには、地理データのレイヤーが含まれています。マップには、ベースマップ レイヤーと、オプションで1つ以上のデータレイヤーを追加できます。マップビューを使用し、場所とズームレベルを設定することで、マップの特定の領域を表示できます。

このチュートリアルでは、地形ベースマップレイヤーを使用して、富士山付近を表示する地図を作成します。

前提条件

このチュートリアルを実施するには、以下が必要です。

API キーにアクセスするための ArcGIS 開発者アカウント。アカウントをお持ちでない場合は、サインアップ(無料)してください。アカウントの作成方法は「開発者アカウントの作成」をご覧ください。

開発環境がシステム要件を満たしていることを確認します。

Kotlin で Android 開発を行うための IDE。このチュートリアルでは Android Studio を使用していますが、記述されたコードは Kotlin をサポートする任意の Android の IDE で動作します。

ステップ

新しい Android Studio プロジェクトを作成します

Android Studio を使用してアプリを作成し、API を参照するように構成します。

Android Studio を開きます。

メニューバーで、[File] > [New] > [New Project….] をクリックします。

[Create New Project] ウィンドウで、[Phone and Tablet] タブが選択されていることを確認してから、[Empty Activity] を選択します。[Next] をクリックします。

Gradle は、Android Studio のデフォルトのビルドツールです。Gradle を使用できない場合は、API を手動で取得する を参照してください。

[Configure your project] ウィンドウで、次の構成オプションを設定します。

Name: Display a map

Package name: com.example.app に変更します。または、組織に合わせて変更してください。

Save location: 新しいフォルダに設定します

Language: Kotlin

Minimum SDK: API 23: Android 6.0 (Marshmallow)

プロジェクトのツールウィンドウで、現在のビューが Android であることを確認してください。チュートリアルの説明では、そのビューを参照しています。

ビュー名が Android 以外の名前(プロジェクトやパッケージなど)の場合は、プロジェクトツールウィンドウのタイトルバーの左端のコントロールをクリックし、リストから Android を選択します。

プロジェクト ツールウィンドウから、[Gradle Scripts] > [build.gradle (Project: Display_a_map)] を開きます。ファイルの内容を次のコードに置き換えます。

build.gradle (Project: Display_a_map)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

プロジェクト ツールウィンドウから、[Gradle Scripts] > [build.gradle (Module: Display_a_map.app)] を開きます。ファイルの内容を次のコードに置き換えます。

build.gradle (Module: Display_a_map.app)

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdkVersion 32

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 23
        targetSdkVersion 32
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

    buildFeatures {
        viewBinding true
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }

}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'com.google.android.material:material:1.6.1'

    implementation 'com.esri.arcgisruntime:arcgis-android:100.15.0'
}

注: 上記の build.gradle ファイルでは、ソースとターゲットの両方で Java 8 言語互換性を指定しています。Android Studio はこの互換性設定を利用して、必要に応じて「desugaring」と呼ばれるバイトコード変換を自動で行います。別の IDE を使用している場合は、自分で Java 8 互換性を設定する必要がある場合があります。詳しくは、Java 8 言語機能と API を使用する を参照してください。

プロジェクト ツールウィンドウから、[Gradle Scripts] > [settings.gradle] を開きます。ファイルの内容を次のコードに置き換えます。

settings.gradle

import org.gradle.api.initialization.resolve.RepositoriesMode

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()

        maven {
            url 'https://esri.jfrog.io/artifactory/arcgis'
        }
    }
}

rootProject.name = "Display a map"

include ':app'

Gradle の変更を同期します。[Sync now] プロンプトをクリックするか、ツールバーの更新アイコン(Sync Project with Gradle Files)をクリックします。同期に数分かかるかもしれません。

プロジェクトツールウィンドウから、[app] > [manifests] > [AndroidManifest.xml] を開きます。Android マニフェストを更新して、ネットワークアクセスを許可し、アプリが OpenGL2.0 以降を使用することを示します。

これらの新しい要素を manifest 要素内に挿入します。他のステートメントを変更または削除しないでください。追加する ArcGIS の機能によっては、マニフェストに追加のアクセス許可を追加する必要がある可能性があります。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app">

// 追加開始
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />
// 追加終了

インポートステートメントを追加する

[app] > [java] > [com.example.app] > [MainActivity.kt] を開き、ArcGIS Runtime SDK を参照するようにインポートステートメントを追加します。

MainActivity.kt

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

// 追加開始
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.MapView
import com.example.app.databinding.ActivityMainBinding
// 追加終了

マップビューの UI を追加する

マップビューは、マップを表示する UI コンポーネントです。また、タッチジェスチャによるナビゲートなど、ユーザーによるマップの操作も処理します。XML を使用してマップビューを UI に追加し、メインアクティビティのソースコードで使用できるようにします。

[app] > [res] > [layout] > [activity_main.xml] で、TextView 要素全体を MapView 要素に置き換えます。

XMLコードが表示されない場合は、[Code] タブを選択してデザインモードを切り替え、エディターに XML コードを表示します。
MapView 要素は、ArcGIS Runtime SDK for Android から MapView クラスのインスタンスを作成します。

メインアクティビティ ソースコードでは、android:id 属性の値で宣言されている暗黙的なプロパティを使用してその MapView インスタンスにアクセスできます。この場合、プロパティの名前は mapView になります。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    // 追加開始
    <com.esri.arcgisruntime.mapping.view.MapView
            android:id="@+id/mapView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    // 追加終了

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt で、生成された Android クラス ActivityMainBinding を参照する activityMainBinding という名前の読み取り専用ローカル変数を作成します。

MainActivity.kt

class MainActivity : AppCompatActivity() {

    // 追加開始
    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    // 追加終了

mapView という名前の読み取り専用変数を作成し、それを activity_main.xml で作成された mapView にバインドします。

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    // 追加開始
    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }
    // 追加終了

マップを追加する

マップビューを使用して、富士山を中心としたマップを表示します。マップには、地形ベースマップレイヤーが含まれます。

MainActivity.kt で、MainActivity クラスに新しい setupMap メソッドを追加し、ArcGISMap を作成します。ARCGIS_TOPOGRAPHIC という名前の特定のベースマップスタイルを使用して ArcGISMap を構成します。

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

// 追加開始
// ここでマップを設定します。このメソッドは onCreate() から呼び出します
private fun setupMap() {

    // BasemapStyle で地図を作成する
    val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)

}
// 追加終了

地形図(ARCGIS_TOPOGRAPHIC)以外にも、道路地図(ARCGIS_STREETS)、衛星画像(ARCGIS_IMAGERY)、オープンストリートマップ(OSM_STANDARD)など、様々なスタイルが用意されています。

mapView の map プロパティを新しい ArcGISMap に設定します。次に、ViewPoint を作成し、それを mapView に追加します。

MainActivity.kt

// ここでマップを設定します。このメソッドは onCreate() から呼び出します
private fun setupMap() {

    // BasemapStyle で地図を作成する
    val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)

    // 追加開始
    // レイアウトの MapView に表示されるマップを設定します
    mapView.map = map
    // 視点の Viewpoint(緯度、経度、スケール) を設定します
    mapView.setViewpoint(Viewpoint(35.360626, 138.727363, 200000.0))
    // 追加終了
}

onCreate() メソッドで、Android Studio のデフォルトの呼び出しであるsetContentView(R.layout.activity_main) を setContentView(activityMainBinding.root) に置き換えます。その後、setupMap() を呼び出します。

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // 変更前
    // setContentView(R.layout.activity_main)

    // 変更後
    setContentView(activityMainBinding.root)
    setupMap()
}

MainActivity クラスの onPause、onResume、onDestroy メソッドをオーバーライドします。

MapView はビューを適切に管理するために、アプリがバックグラウンドになったとき、またはバックグラウンドから復元されたときを知る必要があります。ビューが不要になった時、そのリソースは dispose の呼び出しで解放される必要があります。これらのメソッドは、MainActivity クラスの定義内のどこにでも置くことができます。

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(activityMainBinding.root)

    setupMap()

}

// 追加開始
override fun onPause() {
    mapView.pause()
    super.onPause()
}

override fun onResume() {
    super.onResume()
    mapView.resume()
}

override fun onDestroy() {
    mapView.dispose()
    super.onDestroy()
}
// 追加終了

API キーを設定する

ArcGIS Online でホストされているサービス、Web マップ、Web シーンにアクセスできるようにするには、API キーが必要です。
まだ作成していない場合は、ArcGIS Developers ダッシュボード に移動して、API キーを取得します。作成方法は「API キーの取得」をご覧ください。

setApiKeyForApp() メソッドを作成し、API キーを使用して ArcGISRuntimeEnvironment の apiKey プロパティを設定します。

MainActivity.kt

override fun onDestroy() {
    mapView.dispose()
    super.onDestroy()
}

// 追加開始
private fun setApiKeyForApp(){

    // API キーを設定します
    // 注:API キーをソースコードに保存することはベストプラクティスではありません。API キーが参照されます。
    //チュートリアルでは便宜上ソースコードに記載しています
    ArcGISRuntimeEnvironment.setApiKey("<API キー>")

}
// 追加終了

onCreate() ライフサイクル メソッド内で setApiKeyForApp() を呼び出す。

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(activityMainBinding.root)

    // 追加開始
    setApiKeyForApp()
    // 追加開始

    setupMap()

}

[Run] > [Run] > [app] をクリックして、アプリを実行します。アプリを実行するエミュレーターが表示されます。アプリがビルドされてもエミュレーターが表示されない場合は、エミュレーターを追加する必要があります。[Tools] > [AVD Manager] > [Create Virtual Device…] をクリックします。

富士山を中心とした地形ベースマップレイヤーのマップが表示されます。マップビューをピンチ、ドラッグ、およびダブルタップして、マップを操作します。

完成版のプロジェクトはこちらからダウンロードできます(マップの表示場所は本チュートリアルで設定した場所とは異なります)。

Web マップを表示する

「Web マップの作成」のガイドで Web マップを作成している場合は、作成した Web マップも基本的に同じステップで表示できます。

マップを表示するのステップで作成したプロジェクトの [app] > [java] > [com.example.app] > [MainActivity.kt] を開き、必要なインポートステートメントを追加します。

MainActivity.kt

import com.esri.arcgisruntime.portal.Portal
import com.esri.arcgisruntime.portal.PortalItem

setupMap メソッドを下記のように書き換えます。

MainActivity.kt

    val portal = Portal("https://www.arcgis.com", false)
    val itemId = "<Web マップの ID>"
    val portalItem = PortalItem(portal, itemId)
    val map = ArcGISMap(portalItem)
    mapView.map = map

アプリの動作が確認できたら ArcGIS の セキュリティと認証について学びましょう!

 OpenLayers
    iOS


text:
@interface WMFExploreSectionHeader ()

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *rightButtonWidthConstraint;
@property (assign, nonatomic) CGFloat rightButtonWidthConstraintConstant;

@property (strong, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) IBOutlet UIImageView *icon;
@property (strong, nonatomic) IBOutlet UIView *iconContainerView;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UILabel *subTitleLabel;

@end

@implementation WMFExploreSectionHeader

- (void)awakeFromNib {
    [super awakeFromNib];
    [self reset];
    self.titleLabel.isAccessibilityElement = NO;
    self.subTitleLabel.isAccessibilityElement = NO;
    self.containerView.isAccessibilityElement = YES;
    self.accessibilityTraits = UIAccessibilityTraitHeader;
    self.tintColor = [UIColor wmf_blueTintColor];
    self.rightButtonWidthConstraintConstant = self.rightButtonWidthConstraint.constant;
    self.rightButton.hidden = YES;
    self.rightButton.tintColor = [UIColor wmf_blueTintColor];
    self.rightButton.isAccessibilityElement = YES;
    self.rightButton.accessibilityTraits = UIAccessibilityTraitButton;
    @weakify(self);
    [self bk_whenTapped:^{
        @strongify(self);
        if (self.whenTapped) {
            self.whenTapped();
        }
    }];
}

- (void)setImage:(UIImage *)image {
    self.icon.image = image;
}

- (void)setImageTintColor:(UIColor *)imageTintColor {
    self.icon.tintColor = imageTintColor;
}

- (void)setImageBackgroundColor:(UIColor *)imageBackgroundColor {
    self.iconContainerView.backgroundColor = imageBackgroundColor;
}

- (void)setTitle:(NSAttributedString *)title {
    self.titleLabel.attributedText = title;
    [self updateAccessibilityLabel];
}

- (void)setSubTitle:(NSAttributedString *)subTitle {
    self.subTitleLabel.attributedText = subTitle;
    [self updateAccessibilityLabel];
}

- (void)updateAccessibilityLabel {
    NSString *title = self.titleLabel.text;
    NSString *subtitle = self.subTitleLabel.text;
    NSMutableArray *components = [NSMutableArray arrayWithCapacity:2];
    if (title) {
        [components addObject:title];
    }
    if (subtitle) {
        [components addObject:subtitle];
    }
    self.containerView.accessibilityLabel = [components componentsJoinedByString:@" "];
}

- (void)prepareForReuse {
    [super prepareForReuse];
    [self reset];
}

- (void)reset {
    self.titleLabel.text = @"";
    self.subTitleLabel.text = @"";
    self.rightButtonEnabled = NO;
}

- (void)setRightButtonEnabled:(BOOL)rightButtonEnabled {
    if (_rightButtonEnabled == rightButtonEnabled) {
        return;
    }
    _rightButtonEnabled = rightButtonEnabled;
    self.rightButton.hidden = !self.rightButtonEnabled;
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
}

- (void)updateConstraints {
    if (self.rightButtonEnabled) {
        self.rightButtonWidthConstraint.constant = self.rightButtonWidthConstraintConstant;
    } else {
        self.rightButtonWidthConstraint.constant = 0;
    }
    [super updateConstraints];
}

@end


text:
import os
import shutil
import tarfile
import zipfile

import requests
from six.moves.urllib.error import HTTPError, URLError
from six.moves.urllib.request import urlretrieve

from odin.utils.crypto import md5_checksum, md5_folder

__all__ = [
    'download_and_extract',
    'download_google_drive',
    'get_file',
]

def download_google_drive(id, destination, chunk_size=32 * 1024):
  r""" Original code for dowloading the dataset:
  https://github.com/suvojit-0x55aa/celebA-HQ-dataset-download """
  from tqdm import qdm
  URL = "https://docs.google.com/uc?export=download"
  URL = "https://drive.google.com/uc?id="
  session = requests.Session()
  response = session.get(URL, params={'id': id}, stream=True)
  token = None
  for key, value in response.cookies.items():
    if key.startswith('download_warning'):
      token = value
  if token:
    params = {'id': id, 'confirm': token}
    response = session.get(URL, params=params, stream=True)
  total_size = int(response.headers.get('content-length', 0))
  with open(destination, "wb") as f:
    for chunk in tqdm(response.iter_content(chunk_size),
                      total=total_size,
                      unit='B',
                      unit_scale=True,
                      desc=destination):
      if chunk:  # filter out keep-alive new chunks
        f.write(chunk)

def download_and_extract(path,
                         url,
                         extract=True,
                         md5_download=None,
                         md5_extract=None):
  r""" Download a file to given path then extract the file

  Arguments:
    path : a String path to a folder
    url : a String of download URL
    extract : a Boolean, if True decompress the file
  """
  from tqdm import tqdm
  path = os.path.abspath(os.path.expanduser(path))
  if not os.path.exists(path):
    os.makedirs(path)
  assert os.path.isdir(path), "path to '%s' is not a directory" % path
  ### file name
  filename = url.split('/')[-1]
  filepath = os.path.join(path, filename)
  ### download
  if os.path.exists(filepath) and md5_download is not None:
    md5 = md5_checksum(filepath)
    if md5 != md5_download:
      print("MD5 of downloaded file mismatch! downloaded:%s  provided:%s" %
            (md5, md5_download))
      os.remove(filepath)
  if not os.path.exists(filepath):
    prog = tqdm(desc="Download '%s'" % filename, total=-1, unit="MB")

    def _progress(count, block_size, total_size):
      # to MB
      total_size = total_size / 1024. / 1024.
      block_size = block_size / 1024. / 1024.
      if prog.total < 0:
        prog.total = total_size
      prog.update(block_size)

    filepath, _ = urlretrieve(url, filepath, reporthook=_progress)
  ### no extraction needed
  if not extract:
    return filepath
  ### extract
  extract_path = os.path.join(path, os.path.basename(filename).split('.')[0])
  if os.path.exists(extract_path) and md5_extract is not None:
    md5 = md5_folder(extract_path)
    if md5 != md5_extract:
      print("MD5 extracted folder mismatch! extracted:%s provided:%s" %
            (md5, md5_extract))
      shutil.rmtree(extract_path)
  if not os.path.exists(extract_path):
    # .tar.gz
    if '.tar.gz' in filepath:
      with tarfile.open(filepath, 'r:gz') as f:
        print("Extracting files ...")
        f.extractall(path)
    # .zip
    elif '.zip' in filepath:
      # TODO
      raise NotImplementedError
    # unknown extension
    else:
      raise NotImplementedError("Cannot extract file: %s" % filepath)
  ### return
  return path, extract_path

def get_file(fname, origin, outdir, verbose=False):
  r'''
  Arguments:
    fname: output file name
    origin: url, link
    outdir: path to output dir
  '''
  fpath = os.path.join(outdir, fname)
  # ====== remove empty folder ====== #
  if os.path.exists(fpath):
    if os.path.isdir(fpath) and len(os.listdir(fpath)) == 0:
      shutil.rmtree(fpath)
  # ====== download package ====== #
  if not os.path.exists(fpath):
    if verbose:
      prog = Progbar(target=-1,
                     name="Downloading: %s" % os.path.basename(origin),
                     print_report=True,
                     print_summary=True)

    def dl_progress(count, block_size, total_size):
      if verbose:
        if prog.target < 0:
          prog.target = total_size
        else:
          prog.add(count * block_size - prog.seen_so_far)

    ###
    error_msg = 'URL fetch failure on {}: {} -- {}'
    try:
      try:
        urlretrieve(origin, fpath, dl_progress)
      except URLError as e:
        raise Exception(error_msg.format(origin, e.errno, e.reason))
      except HTTPError as e:
        raise Exception(error_msg.format(origin, e.code, e.msg))
    except (Exception, KeyboardInterrupt) as e:
      if os.path.exists(fpath):
        os.remove(fpath)
      raise
  return fpath


text:
exports = module.exports = function() {
    return function(context) {
        return context.charAt(0).toUpperCase() + context.slice(1);
    };
};


text:
<?php

namespace spec\Http\Client\Plugin;

use Http\Client\Plugin\RedirectPlugin;
use Http\Promise\FulfilledPromise;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class RedirectPluginSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Http\Client\Plugin\RedirectPlugin');
    }

    function it_is_a_plugin()
    {
        $this->shouldImplement('Http\Client\Plugin\Plugin');
    }

    function it_redirects_on_302(
        UriInterface $uri,
        UriInterface $uriRedirect,
        RequestInterface $request,
        ResponseInterface $responseRedirect,
        RequestInterface $modifiedRequest,
        ResponseInterface $finalResponse,
        Promise $promise
    ) {
        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('/redirect');

        $request->getRequestTarget()->willReturn('/original');
        $request->getUri()->willReturn($uri);
        $request->withUri($uriRedirect)->willReturn($modifiedRequest);

        $uri->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withFragment('')->willReturn($uriRedirect);
        $uriRedirect->withQuery('')->willReturn($uriRedirect);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $first = function (RequestInterface $receivedRequest) use($modifiedRequest, $promise) {
            if (Argument::is($modifiedRequest->getWrappedObject())->scoreArgument($receivedRequest)) {
                return $promise->getWrappedObject();
            }
        };

        $promise->getState()->willReturn(Promise::FULFILLED);
        $promise->wait()->shouldBeCalled()->willReturn($finalResponse);

        $finalPromise = $this->handleRequest($request, $next, $first);
        $finalPromise->shouldReturnAnInstanceOf('Http\Promise\FulfilledPromise');
        $finalPromise->wait()->shouldReturn($finalResponse);
    }

    function it_use_storage_on_301(UriInterface $uriRedirect, RequestInterface $request, RequestInterface $modifiedRequest)
    {
        $this->beAnInstanceOf('spec\Http\Client\Plugin\RedirectPluginStub');
        $this->beConstructedWith($uriRedirect, '/original', '301');

        $next = function () {
            throw new \Exception('Must not be called');
        };

        $request->getRequestTarget()->willReturn('/original');
        $request->withUri($uriRedirect)->willReturn($modifiedRequest);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');

        $this->handleRequest($request, $next, function () {});
    }

    function it_stores_a_301(
        UriInterface $uri,
        UriInterface $uriRedirect,
        RequestInterface $request,
        ResponseInterface $responseRedirect,
        RequestInterface $modifiedRequest,
        ResponseInterface $finalResponse,
        Promise $promise
    ) {

        $this->beAnInstanceOf('spec\Http\Client\Plugin\RedirectPluginStub');
        $this->beConstructedWith($uriRedirect, '', '301');

        $request->getRequestTarget()->willReturn('/301-url');
        $request->getUri()->willReturn($uri);

        $responseRedirect->getStatusCode()->willReturn('301');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('/redirect');

        $uri->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withFragment('')->willReturn($uriRedirect);
        $uriRedirect->withQuery('')->willReturn($uriRedirect);

        $request->withUri($uriRedirect)->willReturn($modifiedRequest);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $first = function (RequestInterface $receivedRequest) use($modifiedRequest, $promise) {
            if (Argument::is($modifiedRequest->getWrappedObject())->scoreArgument($receivedRequest)) {
                return $promise->getWrappedObject();
            }
        };

        $promise->getState()->willReturn(Promise::FULFILLED);
        $promise->wait()->shouldBeCalled()->willReturn($finalResponse);

        $this->handleRequest($request, $next, $first);
        $this->hasStorage('/301-url')->shouldReturn(true);
    }

    function it_replace_full_url(
        UriInterface $uri,
        UriInterface $uriRedirect,
        RequestInterface $request,
        ResponseInterface $responseRedirect,
        RequestInterface $modifiedRequest,
        ResponseInterface $finalResponse,
        Promise $promise
    ) {
        $request->getRequestTarget()->willReturn('/original');

        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('https://server.com:8000/redirect?query#fragment');

        $request->getUri()->willReturn($uri);
        $uri->withScheme('https')->willReturn($uriRedirect);
        $uriRedirect->withHost('server.com')->willReturn($uriRedirect);
        $uriRedirect->withPort('8000')->willReturn($uriRedirect);
        $uriRedirect->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withQuery('query')->willReturn($uriRedirect);
        $uriRedirect->withFragment('fragment')->willReturn($uriRedirect);

        $request->withUri($uriRedirect)->willReturn($modifiedRequest);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $first = function (RequestInterface $receivedRequest) use($modifiedRequest, $promise) {
            if (Argument::is($modifiedRequest->getWrappedObject())->scoreArgument($receivedRequest)) {
                return $promise->getWrappedObject();
            }
        };

        $promise->getState()->willReturn(Promise::FULFILLED);
        $promise->wait()->shouldBeCalled()->willReturn($finalResponse);

        $this->handleRequest($request, $next, $first);
    }

    function it_throws_http_exception_on_no_location(RequestInterface $request, ResponseInterface $responseRedirect)
    {
        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $request->getRequestTarget()->willReturn('/original');
        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(false);

        $promise = $this->handleRequest($request, $next, function () {});
        $promise->shouldReturnAnInstanceOf('Http\Promise\RejectedPromise');
        $promise->shouldThrow('Http\Client\Exception\HttpException')->duringWait();
    }

    function it_throws_http_exception_on_invalid_location(RequestInterface $request, ResponseInterface $responseRedirect)
    {
        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $request->getRequestTarget()->willReturn('/original');
        $responseRedirect->getHeaderLine('Location')->willReturn('scheme:///invalid');

        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);

        $promise = $this->handleRequest($request, $next, function () {});
        $promise->shouldReturnAnInstanceOf('Http\Promise\RejectedPromise');
        $promise->shouldThrow('Http\Client\Exception\HttpException')->duringWait();
    }

    function it_throw_multi_redirect_exception_on_300(RequestInterface $request, ResponseInterface $responseRedirect)
    {
        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $this->beConstructedWith(['preserve_header' => true, 'use_default_for_multiple' => false]);
        $responseRedirect->getStatusCode()->willReturn('300');

        $promise = $this->handleRequest($request, $next, function () {});
        $promise->shouldReturnAnInstanceOf('Http\Promise\RejectedPromise');
        $promise->shouldThrow('Http\Client\Plugin\Exception\MultipleRedirectionException')->duringWait();
    }

    function it_throw_multi_redirect_exception_on_300_if_no_location(RequestInterface $request, ResponseInterface $responseRedirect)
    {
        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $responseRedirect->getStatusCode()->willReturn('300');
        $responseRedirect->hasHeader('Location')->willReturn(false);

        $promise = $this->handleRequest($request, $next, function () {});
        $promise->shouldReturnAnInstanceOf('Http\Promise\RejectedPromise');
        $promise->shouldThrow('Http\Client\Plugin\Exception\MultipleRedirectionException')->duringWait();
    }

    function it_switch_method_for_302(
        UriInterface $uri,
        UriInterface $uriRedirect,
        RequestInterface $request,
        ResponseInterface $responseRedirect,
        RequestInterface $modifiedRequest,
        ResponseInterface $finalResponse,
        Promise $promise
    ) {
        $request->getRequestTarget()->willReturn('/original');

        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('/redirect');

        $request->getUri()->willReturn($uri);
        $uri->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withFragment('')->willReturn($uriRedirect);
        $uriRedirect->withQuery('')->willReturn($uriRedirect);

        $request->withUri($uriRedirect)->willReturn($modifiedRequest);
        $modifiedRequest->getUri()->willReturn($uriRedirect);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('POST');
        $modifiedRequest->withMethod('GET')->willReturn($modifiedRequest);

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $first = function (RequestInterface $receivedRequest) use($modifiedRequest, $promise) {
            if (Argument::is($modifiedRequest->getWrappedObject())->scoreArgument($receivedRequest)) {
                return $promise->getWrappedObject();
            }
        };

        $promise->getState()->willReturn(Promise::FULFILLED);
        $promise->wait()->shouldBeCalled()->willReturn($finalResponse);

        $this->handleRequest($request, $next, $first);
    }

    function it_clears_headers(
        UriInterface $uri,
        UriInterface $uriRedirect,
        RequestInterface $request,
        ResponseInterface $responseRedirect,
        RequestInterface $modifiedRequest,
        ResponseInterface $finalResponse,
        Promise $promise
    ) {
        $this->beConstructedWith(['preserve_header' => ['Accept']]);

        $request->getRequestTarget()->willReturn('/original');

        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('/redirect');

        $request->getUri()->willReturn($uri);
        $uri->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withFragment('')->willReturn($uriRedirect);
        $uriRedirect->withQuery('')->willReturn($uriRedirect);

        $request->withUri($uriRedirect)->willReturn($modifiedRequest);

        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');
        $modifiedRequest->getHeaders()->willReturn(['Accept' => 'value', 'Cookie' => 'value']);
        $modifiedRequest->withoutHeader('Cookie')->willReturn($modifiedRequest);
        $modifiedRequest->getUri()->willReturn($uriRedirect);

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $first = function (RequestInterface $receivedRequest) use($modifiedRequest, $promise) {
            if (Argument::is($modifiedRequest->getWrappedObject())->scoreArgument($receivedRequest)) {
                return $promise->getWrappedObject();
            }
        };

        $promise->getState()->willReturn(Promise::FULFILLED);
        $promise->wait()->shouldBeCalled()->willReturn($finalResponse);

        $this->handleRequest($request, $next, $first);
    }

    function it_throws_circular_redirection_exception(UriInterface $uri, UriInterface $uriRedirect, RequestInterface $request, ResponseInterface $responseRedirect, RequestInterface $modifiedRequest)
    {
        $first = function() {};

        $this->beAnInstanceOf('spec\Http\Client\Plugin\RedirectPluginStubCircular');
        $this->beConstructedWith(spl_object_hash((object)$first));

        $request->getRequestTarget()->willReturn('/original');
        $request->getUri()->willReturn($uri);

        $responseRedirect->getStatusCode()->willReturn('302');
        $responseRedirect->hasHeader('Location')->willReturn(true);
        $responseRedirect->getHeaderLine('Location')->willReturn('/redirect');

        $uri->withPath('/redirect')->willReturn($uriRedirect);
        $uriRedirect->withFragment('')->willReturn($uriRedirect);
        $uriRedirect->withQuery('')->willReturn($uriRedirect);

        $request->withUri($uriRedirect)->willReturn($modifiedRequest);
        $modifiedRequest->getUri()->willReturn($uriRedirect);
        $modifiedRequest->getRequestTarget()->willReturn('/redirect');
        $modifiedRequest->getMethod()->willReturn('GET');

        $next = function (RequestInterface $receivedRequest) use($request, $responseRedirect) {
            if (Argument::is($request->getWrappedObject())->scoreArgument($receivedRequest)) {
                return new FulfilledPromise($responseRedirect->getWrappedObject());
            }
        };

        $promise = $this->handleRequest($request, $next, $first);
        $promise->shouldReturnAnInstanceOf('Http\Promise\RejectedPromise');
        $promise->shouldThrow('Http\Client\Plugin\Exception\CircularRedirectionException')->duringWait();
    }
}

class RedirectPluginStub extends RedirectPlugin
{
    public function __construct(UriInterface $uri, $storedUrl, $status, array $config = [])
    {
        parent::__construct($config);

        $this->redirectStorage[$storedUrl] = [
            'uri' => $uri,
            'status' => $status
        ];
    }

    public function hasStorage($url)
    {
        return isset($this->redirectStorage[$url]);
    }
}

class RedirectPluginStubCircular extends RedirectPlugin
{
    public function __construct($chainHash)
    {
        $this->circularDetection = [
            $chainHash => [
                '/redirect'
            ]
        ];
    }
}


text:
package org.orienteer.notifications.scheduler;

import com.orientechnologies.orient.core.Orient;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Notification scheduler. Temporary fix. Scheduler in OrientDB 2 has connection leak.
 * Need upgrade to OrientDB 3
 */
public final class ONotificationScheduler {

  private static final ConcurrentHashMap<String, ONotificationTask> TASKS = new ConcurrentHashMap<>();

  private ONotificationScheduler() {}

  public static void scheduleTask(ONotificationTask task, Date firstTime) {
    scheduleTask(task, firstTime, 0);
  }

  public static void scheduleTask(ONotificationTask task, long delay) {
    scheduleTask(task, delay, 0);
  }

  public static void scheduleTask(ONotificationTask task, Date firstTime, long period) {
    stopTask(task.getName());
    TASKS.put(task.getName(), task);
    Orient.instance().scheduleTask(task, firstTime, period);
  }

  public static void scheduleTask(ONotificationTask task, long delay, long period) {
    stopTask(task.getName());
    TASKS.put(task.getName(), task);
    Orient.instance().scheduleTask(task, delay, period);
  }

  public static synchronized void stopTask(String name) {
    ONotificationTask task = TASKS.remove(name);

    if (task != null) {
      task.cancel();
    }
  }

  public static void stopAll() {
    TASKS.keySet().forEach(ONotificationScheduler::stopTask);
  }

}


text:
// <autogenerated />
using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("DotSpatial.Serialization")]
[assembly: AssemblyDescription("Helper assembly to save DotSpatial objects to file.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("DotSpatial.Serialization")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]

[assembly: Guid("f5b25381-8f89-4abb-8172-a3eff691719c")]


text:
class OrderItem
  module ServicePurchasing
    include OrderItem::Purchasing

    def find_item(service_or_id)
      id = service_or_id.is_a?(Service) ? service_or_id.id : service_or_id
      select {|i| i.service_id == id}.first
    end

    def purchase_stock!
      nil
    end

    private

    def assign_components(entry, purchase, quantity)
      point = purchase.price_points.where(:current => true).first

      entry.components.build(
        :price     => point.price,
        :quantity  => quantity,
        :total     => point.price * quantity,
      )
    end

    def stock_available?(service, n)
      true
    end

    def purchase_limited?(purchase)
      false
    end

    def maximum_quantity_allowed(purchase)
      Float::INFINITY
    end

    def find_or_create_item(service)
      find_item(service) || build(:service => service)
    end
end
end


text:
extern NSString *const FrontView;
extern NSString *const RearView;

typedef enum{

    kTagPartNameBubble = 10
}kTags;

@interface InvoBodySelectionViewController : UIViewController <UIScrollViewDelegate,UIGestureRecognizerDelegate,PainFaceDelegate,MFMailComposeViewControllerDelegate, UIDocumentInteractionControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *flipButton;

- (IBAction)flipTapped:(id)sender;
- (IBAction)clearButtonTapped:(id)sender;

@end


text:
package controlP5;

/**
 * controlP5 is a processing gui library.
 *
 *  2007-2010 by Andreas Schlegel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 * @author 		Andreas Schlegel (http://www.sojamo.de)
 * @modified	10/05/2010
 * @version		0.5.4
 *
 */

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import processing.core.PApplet;

/**
 * ControllerGroup is an abstract class and is extended by e.g. ControlGroup,
 * Tab, or ScrollList
 *
 * ControlGroup ScrollList Tab Textarea
 */
public abstract class ControllerGroup implements ControllerInterface, ControlP5Constants {

	protected CVector3f position;

	protected CVector3f positionBuffer;

	protected CVector3f absolutePosition;

	protected ControllerList controllers;

	protected ControlWindow _myControlWindow;

	protected ControlP5 controlP5;

	protected ControllerGroup _myParent;

	protected String _myName;

	protected int _myId = -1;

	protected CColor color = new CColor();

	protected boolean isMousePressed = false;

	protected boolean isInside = false;

	protected boolean isVisible = true;

	protected boolean isOpen = true;

	protected boolean isMoveable = true;

	protected Label _myLabel;

	protected Label _myValueLabel;

	protected int _myWidth = 99;

	protected int _myHeight = 9;

	protected boolean isXMLsavable = true;

	protected boolean isUpdate;

	protected List<ControlCanvas> _myControlCanvas;

	protected float _myValue;

	protected String _myStringValue;

	protected float[] _myArrayValue;

	protected boolean isCollapse = true;

	protected int _myPickingColor = 0x6600ffff;

	protected CVector3f autoPosition = new CVector3f(10, 30, 0);

	protected float tempAutoPositionHeight = 0;

	protected float autoPositionOffsetX = 10;

	/**
	 *
	 * @param theControlP5 ControlP5
	 * @param theParent ControllerGroup
	 * @param theName String
	 * @param theX float
	 * @param theY float
	 */
	public ControllerGroup(ControlP5 theControlP5, ControllerGroup theParent, String theName, float theX, float theY) {
		position = new CVector3f(theX, theY, 0);
		controlP5 = theControlP5;
		color.set((theParent == null) ? controlP5.color : theParent.color);
		_myName = theName;
		controllers = new ControllerList();
		_myControlCanvas = new Vector<ControlCanvas>();
		_myLabel = new Label(_myName, color.colorCaptionLabel);
		setParent((theParent == null) ? this : theParent);
	}

	protected ControllerGroup(int theX, int theY) {
		position = new CVector3f(theX, theY, 0);
		controllers = new ControllerList();
		_myControlCanvas = new Vector<ControlCanvas>();
	}

	/**
	 *
	 */
	public void init() {
	}

	public ControllerInterface parent() {
		return _myParent;
	}

	/**
	 *
	 * @param theParent ControllerGroup
	 */
	void setParent(ControllerGroup theParent) {
		if (_myParent != null && _myParent != this) {
			_myParent.remove(this);
		}

		_myParent = theParent;

		if (_myParent != this) {
			_myParent.add(this);
		}
		absolutePosition = new CVector3f(position);
		absolutePosition.add(_myParent.absolutePosition());
		positionBuffer = new CVector3f(position);
		_myControlWindow = _myParent.getWindow();

		for (int i = 0; i < controllers.size(); i++) {
			if (controllers.get(i) instanceof Controller) {
				((Controller) controllers.get(i))._myControlWindow = _myControlWindow;
			} else {
				((ControllerGroup) controllers.get(i))._myControlWindow = _myControlWindow;
			}
		}
	}

	/**
	 * set the group of the controller.
	 *
	 * @param theGroup ControllerGroup
	 */
	public void setGroup(ControllerGroup theGroup) {
		setParent(theGroup);
	}

	/**
	 * @param theName String
	 */
	public void setGroup(String theName) {
		setParent(controlP5.getGroup(theName));
	}

	/**
	 * move the group.
	 *
	 * @param theGroup ControlGroup
	 * @param theTab Tab
	 * @param theControlWindow ControlWindow
	 */
	public void moveTo(ControlGroup theGroup, Tab theTab, ControlWindow theControlWindow) {
		if (theGroup != null) {
			setGroup(theGroup);
			return;
		}

		if (theControlWindow == null) {
			theControlWindow = controlP5.controlWindow;
		}

		setTab(theControlWindow, theTab.name());
	}

	public void moveTo(ControlGroup theGroup) {
		moveTo(theGroup, null, null);
	}

	public void moveTo(Tab theTab) {
		moveTo(null, theTab, null);
	}

	public void moveTo(ControlWindow theControlWindow) {
		moveTo(null, theControlWindow.tab("default"), theControlWindow);
	}

	public void moveTo(String theTabName) {
		moveTo(null, controlP5.controlWindow.tab(theTabName), controlP5.controlWindow);
	}

	public void moveTo(String theTabName, ControlWindow theControlWindow) {
		moveTo(null, theControlWindow.tab(theTabName), theControlWindow);
	}

	public void moveTo(ControlWindow theControlWindow, String theTabName) {
		moveTo(null, theControlWindow.tab(theTabName), theControlWindow);
	}

	public void moveTo(Tab theTab, ControlWindow theControlWindow) {
		moveTo(null, theTab, theControlWindow);
	}

	/**
	 * set the tab of the controller.
	 *
	 * @param theName String
	 */
	public void setTab(String theName) {
		setParent(controlP5.getTab(theName));
	}

	public void setTab(ControlWindow theWindow, String theName) {
		setParent(controlP5.getTab(theWindow, theName));
	}

	/**
	 * set the tab of the controller.
	 *
	 * @param theTab Tab
	 */
	public void setTab(Tab theTab) {
		setParent(theTab);
	}

	/**
	 * get the instance of the tab this controller belongs to.
	 *
	 * @return Tab
	 */
	public Tab getTab() {
		if (this instanceof Tab) {
			return (Tab) this;
		}
		if (_myParent instanceof Tab) {
			return (Tab) _myParent;
		}
		return _myParent.getTab();
	}

	protected void updateFont(ControlFont theControlFont) {
		_myLabel.updateFont(theControlFont);
		if (_myValueLabel != null) {
			_myValueLabel.updateFont(theControlFont);
		}
		for (int i = 0; i < controllers.size(); i++) {
			if (controllers.get(i) instanceof Controller) {
				((Controller) controllers.get(i)).updateFont(theControlFont);
			} else {
				((ControllerGroup) controllers.get(i)).updateFont(theControlFont);
			}
		}
	}

	/**
	 *
	 * @return CVector3f
	 */
	public CVector3f position() {
		return position;
	}

	/**
	 *
	 * @return CVector3f
	 */
	public CVector3f absolutePosition() {
		return absolutePosition;
	}

	/**
	 * set the position of this controller.
	 *
	 * @param theX float
	 * @param theY float
	 */
	public void setPosition(float theX, float theY) {
		position.set((int) theX, (int) theY);
		positionBuffer.set(position);
		updateAbsolutePosition();
	}

	/**
	 *
	 */
	public void updateAbsolutePosition() {
		absolutePosition.set(position);
		absolutePosition.add(_myParent.absolutePosition());
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).updateAbsolutePosition();
		}

	}

	/**
	 *
	 */
	public void continuousUpdateEvents() {
		if (controllers.size() <= 0) {
			return;
		}
		for (int i = controllers.size() - 1; i >= 0; i--) {
			((ControllerInterface) controllers.get(i)).continuousUpdateEvents();
		}
	}

	/**
	 * call update if you want to update the value of or function call of a
	 * controller.
	 */
	public void update() {
		if (controllers.size() <= 0) {
			return;
		}
		for (int i = controllers.size() - 1; i >= 0; i--) {
			if (((ControllerInterface) controllers.get(i)).isUpdate()) {
				((ControllerInterface) controllers.get(i)).update();
			}
		}
	}

	/**
	 * enable or disable the update function of a controller.
	 *
	 * @param theFlag boolean
	 */
	public void setUpdate(boolean theFlag) {
		isUpdate = theFlag;
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setUpdate(theFlag);
		}
	}

	/**
	 * check the update status of a controller.
	 *
	 * @return boolean
	 */
	public boolean isUpdate() {
		return isUpdate;
	}

	/**
	 *
	 */
	public void updateEvents() {

		if (isOpen) {
			for (int i = controllers.size() - 1; i >= 0; i--) {
				((ControllerInterface) controllers.get(i)).updateEvents();
			}
		}
		if (isVisible) {

			if ((isMousePressed == _myControlWindow.mouselock)) {
				if (isMousePressed && ControlP5.keyHandler.isAltDown && isMoveable) {
					if (!ControlP5.isMoveable) {
						positionBuffer.x += _myControlWindow.mouseX - _myControlWindow.pmouseX;
						positionBuffer.y += _myControlWindow.mouseY - _myControlWindow.pmouseY;
						if (ControlP5.keyHandler.isShiftDown) {
							position.x = ((int) (positionBuffer.x) / 10) * 10;
							position.y = ((int) (positionBuffer.y) / 10) * 10;
						} else {
							position.set(positionBuffer);
						}
						updateAbsolutePosition();
					}
				} else {
					if (inside()) {
						if (!isInside) {
							isInside = true;
							onEnter();
						}
					} else {
						if (isInside && !isMousePressed) {
							onLeave();
							isInside = false;
						}
					}
				}
			}
		}
	}

	/**
	 * @see ControllerInterface.updateInternalEvents
	 *
	 */
	public void updateInternalEvents(PApplet theApplet) {
	}

	/**
	 *
	 * @param theApplet PApplet
	 */
	public final void draw(PApplet theApplet) {
		if (isVisible) {
			theApplet.pushMatrix();
			theApplet.translate(position.x(), position.y());
			preDraw(theApplet);
			_myControlWindow._myPicking.update(this);
			drawControllers(theApplet);
			postDraw(theApplet);
			theApplet.popMatrix();
		}
	}

	protected void drawControllers(PApplet theApplet) {
		if (isOpen) {

			for (int i = 0; i < _myControlCanvas.size(); i++) {
				if (((ControlCanvas) _myControlCanvas.get(i)).mode() == ControlCanvas.PRE) {
					((ControlCanvas) _myControlCanvas.get(i)).draw(theApplet);
				}
			}

			for (int i = 0; i < controllers.size(); i++) {
				if (((ControllerInterface) controllers.get(i)).isVisible()) {
					((ControllerInterface) controllers.get(i)).updateInternalEvents(theApplet);
					((ControllerInterface) controllers.get(i)).draw(theApplet);
				}
			}
			for (int i = 0; i < controllers.sizeDrawable(); i++) {
				((CDrawable) controllers.getDrawable(i)).draw(theApplet);
			}

			for (int i = 0; i < _myControlCanvas.size(); i++) {
				if (((ControlCanvas) _myControlCanvas.get(i)).mode() == ControlCanvas.POST) {
					((ControlCanvas) _myControlCanvas.get(i)).draw(theApplet);
				}
			}
		}
	}

	protected void preDraw(PApplet theApplet) {
	}

	protected void postDraw(PApplet theApplet) {
	}

	/**
	 * add a canvas to a controllerGroup such as a tab or group. use regular
	 * processing draw methods to add visual content.
	 *
	 * @param theCanvas
	 */
	public ControlCanvas addCanvas(ControlCanvas theCanvas) {
		_myControlCanvas.add(theCanvas);
		return theCanvas;
	}

	/**
	 * remove a canvas from a controller group.
	 *
	 * @param theCanvas
	 */
	public void removeCanvas(ControlCanvas theCanvas) {
		_myControlCanvas.remove(theCanvas);
	}

	/**
	 * add a controller to the group, but use Controller.setGroup() instead.
	 *
	 * @param theElement ControllerInterface
	 */
	public void add(ControllerInterface theElement) {
		controllers.add(theElement);
	}

	/**
	 * remove a controller from the group, but use Controller.setGroup() instead.
	 *
	 * @param theElement ControllerInterface
	 */

	public void remove(ControllerInterface theElement) {
		controllers.remove(theElement);
	}

	/**
	 *
	 * @param theElement CDrawable
	 */
	public void addDrawable(CDrawable theElement) {
		controllers.addDrawable(theElement);
	}

	/**
	 *
	 * @param theElement CDrawable
	 */
	public void remove(CDrawable theElement) {
		controllers.removeDrawable(theElement);
	}

	/**
	 * remove the controller from controlP5.
	 */
	public void remove() {
		if (_myParent != null) {
			_myParent.remove(this);
		}
		if (controlP5 != null) {
			controlP5.remove(this);
		}

		for (int i = controllers.size() - 1; i >= 0; i--) {
			controllers.get(i).remove();
		}
		controllers.clear();
		controllers.clearDrawable();
		controllers = new ControllerList();
		if (this instanceof Tab) {
			_myControlWindow.removeTab((Tab) this);
		}
	}

	/**
	 * get the name of the group.
	 *
	 * @return String
	 */
	public String name() {
		return _myName;
	}

	/**
	 *
	 * @return ControlWindow
	 */
	public ControlWindow getWindow() {
		return _myControlWindow;
	}

	/**
	 *
	 * @param theEvent KeyEvent
	 */
	public void keyEvent(KeyEvent theEvent) {
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).keyEvent(theEvent);
		}
	}

	/**
	 *
	 * @param theStatus boolean
	 * @return boolean
	 */
	public boolean setMousePressed(boolean theStatus) {
		if (!isVisible) {
			return false;
		}
		for (int i = controllers.size() - 1; i >= 0; i--) {
			if (((ControllerInterface) controllers.get(i)).setMousePressed(theStatus)) {
				return true;
			}
		}
		if (theStatus == true) {
			if (isInside) {
				isMousePressed = true;
				mousePressed();
				return true;
			}
		} else {
			if (isMousePressed == true) {
				isMousePressed = false;
				mouseReleased();
			}
		}
		return false;
	}

	void mousePressed() {
	}

	void mouseReleased() {
	}

	void onEnter() {
	}

	void onLeave() {
	}

	/**
	 *
	 * @param theId int
	 */
	public void setId(int theId) {
		_myId = theId;
	}

	/**
	 *
	 * @return int
	 */
	public int id() {
		return _myId;
	}

	/**
	 * set the color for the group when active.
	 *
	 * @param theColor int
	 */
	public void setColorActive(int theColor) {
		color.colorActive = theColor;
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setColorActive(theColor);
		}
	}

	/**
	 * set the foreground color of the group.
	 *
	 * @param theColor int
	 */
	public void setColorForeground(int theColor) {
		color.colorForeground = theColor;
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setColorForeground(theColor);
		}
	}

	/**
	 * set the background color of the group.
	 *
	 * @param theColor int
	 */
	public void setColorBackground(int theColor) {
		color.colorBackground = theColor;
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setColorBackground(theColor);
		}
	}

	/**
	 * set the color of the text label of the group.
	 *
	 * @param theColor int
	 */
	public void setColorLabel(int theColor) {
		color.colorCaptionLabel = theColor;
		if (_myLabel != null) {
			_myLabel.set(_myLabel.toString(), color.colorCaptionLabel);
		}
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setColorLabel(theColor);
		}
	}

	/**
	 * set the color of the value label.
	 *
	 * @param theColor int
	 */
	public void setColorValue(int theColor) {
		color.colorValueLabel = theColor;
		if (_myValueLabel != null) {
			_myValueLabel.set(_myValueLabel.toString(), color.colorValueLabel);
		}
		for (int i = 0; i < controllers.size(); i++) {
			((ControllerInterface) controllers.get(i)).setColorValue(theColor);
		}
	}

	/**
	 * set the label of the group.
	 *
	 * @param theLabel String
	 */
	public void setLabel(String theLabel) {
		_myLabel.setFixedSize(false);
		_myLabel.set(theLabel);
		_myLabel.setFixedSize(true);
	}

	/**
	 * check if the group is visible.
	 *
	 * @return boolean
	 */
	public boolean isVisible() {
		return isVisible;
	}

	/**
	 * set the group's visibility.
	 *
	 * @param theFlag boolean
	 */
	public void setVisible(boolean theFlag) {
		isVisible = theFlag;
	}

	/**
	 * hide the group.
	 */
	public void hide() {
		isVisible = false;
	}

	/**
	 * show the group.
	 */
	public void show() {
		isVisible = true;
	}

	/**
	 * set the moveable status of the group.
	 *
	 * @param theFlag boolean
	 */
	public void setMoveable(boolean theFlag) {
		isMoveable = theFlag;
	}

	/**
	 * check if the group is moveable.
	 *
	 * @return boolean
	 */
	public boolean isMoveable() {
		return isMoveable;
	}

	/**
	 *
	 * @param theFlag boolean
	 */
	public void setOpen(boolean theFlag) {
		isOpen = theFlag;
		if (_myValueLabel != null) {
			_myValueLabel.set(isOpen ? "-" : "+");
		}
	}

	/**
	 *
	 * @return boolean
	 */
	public boolean isOpen() {
		return isOpen;
	}

	/**
	 * set the status of the group to open.
	 */
	public void open() {
		setOpen(true);
	}

	/**
	 * set the status of the group to closed.
	 */
	public void close() {
		setOpen(false);
	}

	public int getPickingColor() {
		return _myPickingColor;
	}

	/**
	 *
	 * @return CColor
	 */
	public CColor color() {
		return color;
	}

	public CColor getColor() {
		return color;
	}

	/**
	 * !!! experimental, have to check if this spoils anything. implemented for
	 * ScrollList and MultiList to forward values to a dedicated method
	 */
	public float value() {
		return _myValue;
	}

	public String stringValue() {
		return _myStringValue;
	}

	public float[] arrayValue() {
		return _myArrayValue;
	}

	/**
	 * get a controller of the group.
	 *
	 * @param theController String
	 * @return Controller
	 */
	public Controller controller(String theController) {
		return controlP5.controller(theController);
	}

	public Label captionLabel() {
		return _myLabel;
	}

	public Label valueLabel() {
		return _myValueLabel;
	}

	public void enableCollapse() {
		isCollapse = true;
	}

	public void disableCollapse() {
		isCollapse = false;
	}

	public boolean isCollapse() {
		return isCollapse;
	}

	public int getWidth() {
		return _myWidth;
	}

	public int getHeight() {
		return _myHeight;
	}

	public ControllerGroup setWidth(int theWidth) {
		_myWidth = theWidth;
		return this;
	}

	public ControllerGroup setHeight(int theHeight) {
		_myHeight = theHeight;
		return this;
	}

	protected boolean inside() {
		return (_myControlWindow.mouseX > position.x() + _myParent.absolutePosition().x()
				&& _myControlWindow.mouseX < position.x() + _myParent.absolutePosition().x() + _myWidth
				&& _myControlWindow.mouseY > position.y() + _myParent.absolutePosition().y() - _myHeight && _myControlWindow.mouseY < position.y()
				+ _myParent.absolutePosition().y());
	}

	/**
	 *
	 * @return boolean
	 */
	public boolean isXMLsavable() {
		return isXMLsavable;
	}

	/**
	 *
	 * @return ControlP5XMLElement
	 */
	public ControlP5XMLElement getAsXML() {
		ControlP5XMLElement myXMLElement = new ControlP5XMLElement(new Hashtable(), true, false);
		myXMLElement.setAttribute("name", name());
		myXMLElement.setAttribute("label", _myLabel.toString());
		myXMLElement.setAttribute("id", new Integer(id()));
		myXMLElement.setAttribute("x", new Float(position().x()));
		myXMLElement.setAttribute("y", new Float(position().y()));
		myXMLElement.setAttribute("open", new Float(isOpen == true ? 1 : 0));
		myXMLElement.setAttribute("visible", new Float(isVisible == true ? 1 : 0));
		myXMLElement.setAttribute("moveable", new Float(isMoveable == true ? 1 : 0));
		addToXMLElement(myXMLElement);
		return myXMLElement;
	}

	@Override
	public String toString() {
		return "\nname:\t" + _myName + "\n" + "label:\t" + _myLabel.getText() + "\n" + "id:\t" + _myId + "\n" + "value:\t"
				+ _myValue + "\n" + "position:\t" + position + "\n" + "absolute:\t" + absolutePosition + "\n" + "width:\t"
				+ getWidth() + "\n" + "height:\t" + getHeight() + "\n" + "color:\t" + getColor() + "\n" + "visible:\t"
				+ isVisible + "\n" + "moveable:\t" + isMoveable + "\n";
	}
}


text:
(function () {

    describe(".on", function () {

        describe("binds a native event listener", function () {

            it("hears when a native event is triggered", function (expect) {
                var clicked = false;
                $('#slim_shady').on('click', function (e) {
                    if (e.target.id === 'slim_shady') {
                        clicked = true;
                    }
                });
                $('#slim_shady').click();
                expect(clicked).toBe(true);
            });

        });

        describe("binds a custom event listener", function () {

            it("hears when a custom event is triggered", function (expect) {
                var clicked = false;
                $('#slim_shady').on('goTime', function (e) {
                    if (e.target.id === 'slim_shady') {
                        clicked = true;
                    }
                });
                $('#slim_shady').trigger('goTime');
                expect(clicked).toBe(true);
            });

        });

        describe("is chainable", function () {
            it("returns dollar instance", function (expect) {
                expect($('#slim_shady').on('foo', function () {}).isDollar).toBe(true);
            });
        });

        describe("allows optional custom error handlers", function () {

            it("handles errors in triggered events", function (expect) {
                var handled;
                $.onEventError(function (err) {
                    handled = err.message;
                });
                $('#slim_shady').on('click', function () {
                    throw new Error('bad code');
                });
                $('#slim_shady').click();
                expect(handled).toBe('bad code');
            });

        });

    });

})();


text:
package ring

import (
	"fmt"
	"testing"
)

func TestRebalancerBasic(t *testing.T) {
	// 128 node, 3 replica ring should end up with 128 partitions and each node
	// assigned 3 replicas.
	b := NewBuilder()
	b.SetReplicaCount(3)
	for i := 0; i < 128; i++ {
		b.AddNode(true, 1, nil, nil, "", []byte("Conf"))
	}
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
		}
	}
	for i, count := range counts {
		if count != 3 {
			t.Fatal(i, count)
		}
	}
}

func TestRebalancerTier0(t *testing.T) {
	// 128 nodes with 16 evenly distributed tiers, 4 replicas should end up
	// with 32 partitions, 8 assignments per tier, and 1 assignment per node.
	// Also, no partition should have replicas in the same tier.
	b := NewBuilder()
	b.SetReplicaCount(4)
	for i := 0; i < 128; i++ {
		b.AddNode(true, 1, []string{fmt.Sprintf("tier%d", i%16)}, nil, "", []byte("Conf"))
	}
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	tiers := make(map[string]int)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
			tiers[b.nodes[nodeIndex].Tier(0)]++
		}
	}
	for tier, count := range tiers {
		if count != 8 {
			t.Fatal(tier, count)
		}
	}
	for i, count := range counts {
		if count != 1 {
			t.Fatal(i, count)
		}
	}
	for p := 0; p < len(b.replicaToPartitionToNodeIndex[0]); p++ {
		tiers := make(map[string]bool)
		for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
			tier := b.nodes[partitionToNodeIndex[p]].Tier(0)
			if _, ok := tiers[tier]; ok {
				t.Fatal(tier)
			}
			tiers[tier] = true
		}
	}
}

func TestRebalancerTier0b(t *testing.T) {
	// Same as TestRebalancerTier0 but give tier0 one of tier15's nodes.
	b := NewBuilder()
	b.SetReplicaCount(4)
	for i := 0; i < 127; i++ {
		b.AddNode(true, 1, []string{fmt.Sprintf("tier%d", i%16)}, nil, "", []byte("Conf"))
	}
	b.AddNode(true, 1, []string{"tier0"}, nil, "", []byte("Conf"))
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	tiers := make(map[string]int)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
			tiers[b.nodes[nodeIndex].Tier(0)]++
		}
	}
	for tier, count := range tiers {
		if tier == "tier0" {
			if count != 9 {
				t.Fatal(tier, count)
			}
		} else if tier == "tier15" {
			if count != 7 {
				t.Fatal(tier, count)
			}
		} else if count != 8 {
			t.Fatal(tier, count)
		}
	}
	for i, count := range counts {
		if count != 1 {
			t.Fatal(i, count)
		}
	}
	for p := 0; p < len(b.replicaToPartitionToNodeIndex[0]); p++ {
		tiers := make(map[string]bool)
		for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
			tier := b.nodes[partitionToNodeIndex[p]].Tier(0)
			if _, ok := tiers[tier]; ok {
				t.Fatal(tier)
			}
			tiers[tier] = true
		}
	}
}

func TestRebalancerTier0c(t *testing.T) {
	// A bit more extreme than TestRebalancerTier0b; giving tier0 a lot more
	// nodes than all the others. Here, the per node balance will suffer but
	// the tier distinctions should remain.
	b := NewBuilder()
	b.SetReplicaCount(4)
	for i := 0; i < 96; i++ {
		b.AddNode(true, 1, []string{fmt.Sprintf("tier%d", i%16)}, nil, "", []byte("Conf"))
	}
	for i := 0; i < 32; i++ {
		b.AddNode(true, 1, []string{"tier0"}, nil, "", []byte("Conf"))
	}
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	tiers := make(map[string]int)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
			tiers[b.nodes[nodeIndex].Tier(0)]++
		}
	}
	for tier, count := range tiers {
		if tier == "tier0" {
			if count != 32 {
				t.Fatal(tier, count)
			}
		} else if tier == "tier1" {
			if count != 12 {
				t.Fatal(tier, count)
			}
		} else if count != 6 {
			t.Fatal(tier, count)
		}
	}
	countCounts := make([]int, 3)
	for i, count := range counts {
		if count > 2 {
			t.Fatal(i, count)
		}
		countCounts[count]++
	}
	if countCounts[0] != 6 {
		t.Fatal(countCounts[0])
	}
	if countCounts[1] != 116 {
		t.Fatal(countCounts[1])
	}
	if countCounts[2] != 6 {
		t.Fatal(countCounts[2])
	}
	for p := 0; p < len(b.replicaToPartitionToNodeIndex[0]); p++ {
		tiers := make(map[string]bool)
		for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
			tier := b.nodes[partitionToNodeIndex[p]].Tier(0)
			if _, ok := tiers[tier]; ok {
				t.Fatal(tier)
			}
			tiers[tier] = true
		}
	}
}

func TestRebalancerTier1(t *testing.T) {
	// 128 nodes with 32 evenly distributed tier0s and 16 tier1s, 4 replicas
	// should end up with 32 partitions, 4 assignments per tier0, 8 assignments
	// per tier1, and 1 assignment per node. Also, no partition should have
	// replicas in the same tier.
	b := NewBuilder()
	b.SetReplicaCount(4)
	for i := 0; i < 128; i++ {
		b.AddNode(true, 1, []string{fmt.Sprintf("tier0-%d", i%32), fmt.Sprintf("tier1-%d", i%16)}, nil, "", []byte("Conf"))
	}
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	tier0s := make(map[string]int)
	tier1s := make(map[string]int)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
			tier0s[b.nodes[nodeIndex].Tier(0)]++
			tier1s[b.nodes[nodeIndex].Tier(1)]++
		}
	}
	for tier, count := range tier0s {
		if count != 4 {
			t.Fatal(tier, count)
		}
	}
	for tier, count := range tier1s {
		if count != 8 {
			t.Fatal(tier, count)
		}
	}
	for i, count := range counts {
		if count != 1 {
			t.Fatal(i, count)
		}
	}
	for p := 0; p < len(b.replicaToPartitionToNodeIndex[0]); p++ {
		tier0s := make(map[string]bool)
		tier1s := make(map[string]bool)
		for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
			tier := b.nodes[partitionToNodeIndex[p]].Tier(0)
			if _, ok := tier0s[tier]; ok {
				t.Fatal(tier)
			}
			tier0s[tier] = true
			tier = b.nodes[partitionToNodeIndex[p]].Tier(1)
			if _, ok := tier1s[tier]; ok {
				t.Fatal(tier)
			}
			tier1s[tier] = true
		}
	}
}

func TestRebalancerTier1b(t *testing.T) {
	// Similar to TestRebalancerTier1 but give tier0-0,tier1-0 a lot more
	// nodes. Assert that balancing suffers but tier distinctions are kept.
	b := NewBuilder()
	b.SetReplicaCount(4)
	for i := 0; i < 96; i++ {
		b.AddNode(true, 1, []string{fmt.Sprintf("tier0-%d", i%32), fmt.Sprintf("tier1-%d", i%16)}, nil, "", []byte("Conf"))
	}
	for i := 0; i < 32; i++ {
		b.AddNode(true, 1, []string{"tier0-0", "tier1-0"}, nil, "", []byte("Conf"))
	}
	b.resizeIfNeeded()
	rb := newRebalancer(b)
	rb.rebalance()
	counts := make([]int, 128)
	tier0s := make(map[string]int)
	tier1s := make(map[string]int)
	for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
		for _, nodeIndex := range partitionToNodeIndex {
			counts[nodeIndex]++
			tier0s[b.nodes[nodeIndex].Tier(0)]++
			tier1s[b.nodes[nodeIndex].Tier(1)]++
		}
	}
	for tier, count := range tier0s {
		if tier == "tier0-0" {
			if count != 32 {
				t.Fatal(tier, count)
			}
		} else if count > 6 {
			t.Fatal(tier, count)
		}
	}
	for tier, count := range tier1s {
		if tier == "tier1-0" {
			if count != 32 {
				t.Fatal(tier, count)
			}
		} else if count > 12 {
			t.Fatal(tier, count)
		}
	}
	for i, count := range counts {
		if count > 2 {
			t.Fatal(i, count)
		}
	}
	for p := 0; p < len(b.replicaToPartitionToNodeIndex[0]); p++ {
		tier0s := make(map[string]bool)
		tier1s := make(map[string]bool)
		for _, partitionToNodeIndex := range b.replicaToPartitionToNodeIndex {
			tier := b.nodes[partitionToNodeIndex[p]].Tier(0)
			if _, ok := tier0s[tier]; ok {
				t.Fatal(tier)
			}
			tier0s[tier] = true
			tier = b.nodes[partitionToNodeIndex[p]].Tier(1)
			if _, ok := tier1s[tier]; ok {
				t.Fatal(tier)
			}
			tier1s[tier] = true
		}
	}
}


text:
'use strict';

/**
 * @internal
 *
 * Iterates over the identifying arguments in the supplied root call.
 * If the identifying value is null or undefined, the supplied callback will be
 * invoked once.
 */
function forEachRootCallArg(query, callback) {
  require('fbjs/lib/invariant')(!query.getBatchCall(), 'forEachRootCallArg(): Cannot iterate over batch call variables.');
  function each(identifyingArgValue, fn) {
    if (Array.isArray(identifyingArgValue)) {
      identifyingArgValue.forEach(function (value) {
        return each(value, fn);
      });
    } else {
      fn({
        identifyingArgValue: identifyingArgValue,
        identifyingArgKey: identifyingArgValue == null ? null : typeof identifyingArgValue === 'string' ? identifyingArgValue : require('./stableStringify')(identifyingArgValue)
      });
    }
  }
  var identifyingArg = query.getIdentifyingArg();
  var identifyingArgValue = identifyingArg && identifyingArg.value || null;
  each(identifyingArgValue, callback);
}

module.exports = forEachRootCallArg;


text:
package org.apache.sshd.client.channel.exit;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.util.EventNotifier;
import org.apache.sshd.common.util.buffer.Buffer;

/**
 * @author Apache MINA SSHD Project
 * @see    RFC4254 section 6.10
 */
public class ExitStatusChannelRequestHandler extends AbstractChannelExitRequestHandler<Integer> {
    public static final String NAME = "exit-status";

    public ExitStatusChannelRequestHandler(AtomicReference<Integer> holder, EventNotifier<? super String> notifier) {
        super(holder, notifier);
    }

    @Override
    public final String getName() {
        return NAME;
    }

    @Override
    protected Integer processRequestValue(Channel channel, String request, Buffer buffer) throws Exception {
        return processRequestValue(channel, buffer.getInt());
    }

    protected Integer processRequestValue(Channel channel, int exitStatus) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("processRequestValue({}) status={}", channel, exitStatus);
        }

        return exitStatus;
    }
}


text:
// Copyright (C) 2007 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.caja.parser.quasiliteral;

import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.ParseTreeNodeContainer;

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

/**
 * Quasiliteral "hole" matching zero to many values (regexp "*"). The match is always
 * greedy, and no backtracking is done.
 *
 * @author ihab.awad@gmail.com (Ihab Awad)
 */
public class MultipleQuasiHole extends AbstractQuasiHole {
  public MultipleQuasiHole(Class<? extends ParseTreeNode> matchedClass, String identifier) {
    super(matchedClass, identifier);
  }

  @Override
  protected boolean consumeSpecimens(
      List<ParseTreeNode> specimens,
      Map<String, ParseTreeNode> bindings) {
    List<ParseTreeNode> matches = new ArrayList<ParseTreeNode>();
    while (specimens.size() > 0 && isCompatibleClass(specimens.get(0))) {
      matches.add(specimens.remove(0));
    }
    return putIfDeepEquals(bindings, getIdentifier(), new ParseTreeNodeContainer(matches));
  }

  @Override
  protected boolean createSubstitutes(
      List<ParseTreeNode> substitutes,
      Map<String, ParseTreeNode> bindings) {
    if (bindings.containsKey(getIdentifier())) {
      for (ParseTreeNode child : bindings.get(getIdentifier()).children()) {
        substitutes.add(child.clone());
      }
      return true;
    }
    return false;
  }

  @Override
  protected String getQuantifierSuffix() { return "*"; }
}


text:
package com.pivotal.gemfirexd.internal.impl.io;

import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.io.StorageFile;
import com.pivotal.gemfirexd.internal.io.StorageRandomAccessFile;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * This class provides a jar file based implementation of the StorageFile interface. It is used by the
 * database engine to access persistent data and transaction logs under the jar subsubprotocol.
 */
class JarDBFile extends InputStreamFile
{

    private final JarStorageFactory storageFactory;

    JarDBFile( JarStorageFactory storageFactory, String path)
    {
        super( storageFactory, path);
        this.storageFactory = storageFactory;
    }

    JarDBFile( JarStorageFactory storageFactory, String parent, String name)
    {
        super( storageFactory, parent, name);
        this.storageFactory = storageFactory;
    }

    JarDBFile( JarDBFile dir, String name)
    {
        super( dir,name);
        this.storageFactory = dir.storageFactory;
    }

    private JarDBFile( JarStorageFactory storageFactory, String child, int pathLen)
    {
        super( storageFactory, child, pathLen);
        this.storageFactory = storageFactory;
    }

    /**
     * Tests whether the named file exists.
     *
     * @return true if the named file exists, false if not.
     */
    public boolean exists()
    {
        return getEntry() != null;
    } // end of exists

    private ZipEntry getEntry()
    {
        return storageFactory.zipData.getEntry( path);
    }

    /**
     * Returns the length of the named file if it is not a directory. The return value is not specified
     * if the file is a directory.
     *
     * @return The length, in bytes, of the named file if it exists and is not a directory,
     *         0 if the file does not exist, or any value if the named file is a directory.
     */
    public long length()
    {
        ZipEntry entry = getEntry();
        if( entry == null)
            return 0;
        return entry.getSize();
    } // end of length

    /**
     * Get the name of the parent directory if this name includes a parent.
     *
     * @return An StorageFile denoting the parent directory of this StorageFile, if it has a parent, null if
     *         it does not have a parent.
     */
    StorageFile getParentDir( int pathLen)
    {
        return new JarDBFile( storageFactory, path, pathLen);
    }

    /**
     * Creates an input stream from a file name.
     *
     * @return an input stream suitable for reading from the file.
     *
     * @exception FileNotFoundException if the file is not found.
     */
    public InputStream getInputStream( ) throws FileNotFoundException
    {
        ZipEntry zipEntry = getEntry( );
		if (zipEntry == null)
			throw new java.io.FileNotFoundException(path);

        try
        {
            return storageFactory.zipData.getInputStream(zipEntry);
        }
        catch( IOException ioe){ throw new java.io.FileNotFoundException(path);}
    } // end of getInputStream

    /**
     * Get the file name for diagnostic purposes. Usually the same as getPath().
     *
     * @return the file name
     */
    public String toString()
    {
        return path;
    }
	/**
     * Return a URL for this file (resource). Returns a URL according to the
     * spec for java.net.JarURLConnection
     *
     * @see com.pivotal.gemfirexd.internal.io.StorageFile#getURL()
     */
    public URL getURL() throws MalformedURLException {
        File pathFile = new File(storageFactory.zipData.getName());

        String pathFileURL = pathFile.toURL().toString();

        return new URL("jar:" + pathFileURL + "!/" + path);
    }
}


text:
#import "IoTNotReachable.h"

@interface IoTNotReachable ()

@end

@implementation IoTNotReachable

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.hidesBackButton = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)retry:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end


text:
package org.tianjyan.pwd.service;

import org.tianjyan.pwd.model.Password;

import java.util.List;

public interface OnGetAllPasswordCallback {
    void onGetAllPassword(String groupName, List<Password> passwords);
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".app.activities.MainActivity2">

    <item
        android:id="@+id/action_vector_image"
        android:title="@string/action_vector_image"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_fire_example"
        android:title="@string/action_fire_demo"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_clear_pending"
        android:title="@string/action_clear_pending"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_list_photos"
        android:title="@string/action_show_photos"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_photo_calendar"
        android:title="@string/action_photo_calendar"
        app:showAsAction="never" />
</menu>


text:
package java.io;

/**
 * Thrown when an instance is required to have a Serializable interface.
 * The serialization runtime or the class of the instance can throw
 * this exception. The argument should be the name of the class.
 *
 * @author  unascribed
 * @since   JDK1.1
 */
public class NotSerializableException extends ObjectStreamException {

    private static final long serialVersionUID = 2906642554793891381L;

    /**
     * Constructs a NotSerializableException object with message string.
     *
     * @param classname Class of the instance being serialized/deserialized.
     */
    public NotSerializableException(String classname) {
        super(classname);
    }

    /**
     *  Constructs a NotSerializableException object.
     */
    public NotSerializableException() {
        super();
    }
}


text:
use strict;
use warnings;

#
#  Use the CSV module
#  Created By Nick
use Text::CSV;
my $csvInput = Text::CSV->new({ sep_char => ',' });
#
if ($#ARGV != 1 ) {
   print "Usage: NHLteamRoster.pl <results.csv> <teamID>\n ";
   exit;
}

my $fileName  = $ARGV[0];
my $teamID       = $ARGV[1];
my $date = "";
my $visitor     = "";
my $home     = "";
my $vGoal      = "";
my $hGoal   = "";

my @fieldName;
my @teamScore;
my $count = 0;   # Number of roster array elements
my $found = 0;
open my $fileFH, '<', $fileName
   or die "Unable to open teams file: $fileName";

my $fileRecord = <$fileFH>;

while ( $fileRecord = <$fileFH> ) {
    chomp ( $fileRecord );
    if ( $csvInput->parse($fileRecord) ) {               # check to see if you can break the record into its component (columns)
    my @fieldName = $csvInput->fields();             # put all of the columns from this record into the @teamsField array
       	$date   = $fieldName[0];
 	    $visitor= $fieldName[2];
	    $home   = $fieldName[5];
	    $vGoal =  $fieldName[3];
	    $hGoal  = $fieldName[6];

      if ( $visitor eq $teamID) {
           print $visitor." ". $vGoal." ".$home. " ".$hGoal."\n";
           $found = 1;
      }
      if($home eq $teamID){
          print $home." ".$hGoal." ".$visitor." ". $vGoal."\n";
          $found = 1;
      }

      $fileRecord = "";
   } else {
      warn "Line could not be parsed: $fileRecord\n";
   }
}
close ($fileFH);      # Always close a file as soon as you are finished with it

if(!$found){
    printf "TeamID: ".$teamID." could not be found in file: ".$fileName."\n";
}
#
#   If the team ID does not exist for this particular year then abort the program
#


text:
require File.join(File.dirname(__FILE__), '../lib/servitor')

require 'rspec'

RSpec.configure do

end


text:
import unittest
from JSONx.lexer import *

class TestLexer(unittest.TestCase):

    def assert_list(self, source, expected_types):
        tokens = tokenize(source)
        token_types = map(lambda _: _.type, tokens)
        self.assertEqual(token_types, expected_types)

    def assert_token(self, source, expected_type, expected_value):
        tokens = map(lambda _: (_.type, _.value), tokenize(source))
        self.assertTrue(tokens)
        self.assertEqual(tokens[0], (expected_type, expected_value))

    def test_empty(self):
        self.assert_list("", [Type.EOF])

    def test_numbers(self):
        self.assert_token("0", Type.NUMBER, '0')
        self.assert_token("-1", Type.NUMBER, '-1')
        self.assert_token("123", Type.NUMBER, '123')
        self.assert_token("3.14", Type.NUMBER, '3.14')
        self.assert_token("3.14e0", Type.NUMBER, '3.14e0')
        self.assert_token("1e-1", Type.NUMBER, '1e-1')

    def test_keywords(self):
        self.assert_token("true", Type.KEYWORD, 'true')
        self.assert_token("false", Type.KEYWORD, 'false')
        self.assert_token("null", Type.KEYWORD, 'null')

    def test_specials(self):
        self.assert_token("{", Type.LEFT_CURLY_BRACKET, '{')
        self.assert_token("}", Type.RIGHT_CURLY_BRACKET, '}')
        self.assert_token("[", Type.LEFT_SQUARE_BRACKET, '[')
        self.assert_token("]", Type.RIGHT_SQUARE_BRACKET, ']')
        self.assert_token(",", Type.COMMA, ',')
        self.assert_token(":", Type.COLON, ':')
        self.assert_token("$", Type.DOLLAR, '$')

    def test_whitespaces(self):
        self.assert_token(" -1", Type.NUMBER, '-1')      # one space
        self.assert_token("   -1", Type.NUMBER, '-1')    # many spaces
        self.assert_token("\n-1", Type.NUMBER, '-1')     # new line
        self.assert_token("\t-1", Type.NUMBER, '-1')     # tabulation
        self.assert_token("\t \n-1", Type.NUMBER, '-1')  # mix

    def test_comments(self):
        self.assert_token("// 123\n-1", Type.NUMBER, '-1')        # singleline comment
        self.assert_token("/* 123 */-1", Type.NUMBER, '-1')       # multiline comment
        self.assert_token("/* // 123\n */-1", Type.NUMBER, '-1')  # singleline in multiline

    def test_string(self):
        self.assert_token(r'"\""', Type.STRING, u'"')
        self.assert_token(r'"\n"', Type.STRING, u'\n')
        self.assert_token(r'"\r\n"', Type.STRING, u'\r\n')
        self.assert_token(r'"\uFFFF"', Type.STRING, u'\uFFFF')
        self.assert_token(r'"\xFF"', Type.STRING, u'\xFF')

    def test_sequence(self):
        self.assert_list("{}", [Type.LEFT_CURLY_BRACKET, Type.RIGHT_CURLY_BRACKET, Type.EOF])
        self.assert_list("1,2", [Type.NUMBER, Type.COMMA, Type.NUMBER, Type.EOF])