text:
Update Contact Details.

You are here

Table

Update Contact

Update Contact

                  <form class="form-horizontal" role="form" parsley-validate=""  action ="<?php echo base_url();?>index.php/Action/Update_contact_data/<?php echo $employee['a_id']?>" id="basicvalidations" method="POST" enctype="multipart/form-data">

                        Address *

                           <input type="text"  class="form-control parsley-validated" name="address" value="<?php echo $employee['address']; ?>"  id="fullname" parsley-trigger="change" parsley-required="true" parsley-minlength="4" parsley-validation-minlength="1">

                        Phone

                           <input type="text" class="form-control parsley-validated" name="phone" value="<?php echo $employee['phone']; ?>" id="fullname" parsley-trigger="change" parsley-required="true" parsley-minlength="4" parsley-validation-minlength="1">

                        Email

                           <input type="email" class="form-control parsley-validated" name="email" value="<?php echo $employee['email']; ?>" id="fullname" parsley-trigger="change" parsley-required="true" parsley-minlength="4" parsley-validation-minlength="1">

                           <button type="submit" class="btn btn-primary">Submit</button>
                           <button type="reset" class="btn btn-default">Reset</button>

                  </form>


text:
title: Factorial digit sum
localeTitle: مجموع أرقام عامل
---
## المشكلة 20: مجموع أرقام عامل

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-20-factorial-digit-sum/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <title>Adam Michel</title>
  <link rel="stylesheet" type="text/css" href="/css/styles.css">

Adam Michel

Software builder and happiness engineer for startups.


text:
import os, sys, copy

def findInPath(fileName, path=None):
    if path is None:
        path = os.environ.get('PATH', '')

    dirs = path.split(os.pathsep)
    for dir in dirs:
        if os.path.isfile(os.path.join(dir, fileName)):
            return os.path.join(dir, fileName)
        if os.name == 'nt' or sys.platform == 'cygwin':
            if os.path.isfile(os.path.join(dir, fileName + ".exe")):
                return os.path.join(dir, fileName + ".exe")
    return None

# Mozilla prefs

MOZILLA_DEFAULT_PREFS = {'extensions.update.enabled'    : False,
                         'extensions.update.notifyUser' : False,
                         'browser.shell.checkDefaultBrowser' : False,
                         'browser.tabs.warnOnClose' : False,
                         'browser.warnOnQuit': False,
                         'browser.sessionstore.resume_from_crash': False,
                        }

MOZILLA_PREFERENCES = {} # For user config file to set additional prefs
MOZILLA_CMD_ARGS = []
MOZILLA_ENV = copy.copy(os.environ)
MOZILLA_ENV.update({'MOZ_NO_REMOTE':"1",})

MOZILLA_CREATE_NEW_PROFILE = True

if sys.platform == 'darwin':
    NETWORK_INTERFACE_NAME = None
    firefoxApp = os.path.join('Applications', 'Firefox.app')
    firefoxDir = os.path.join(os.path.expanduser('~/'), firefoxApp)

    if not os.path.isdir(firefoxDir):
        firefoxDir = os.path.join('/', firefoxApp)

    MOZILLA_DEFAULT_PROFILE = os.path.join(firefoxDir, 'Contents', 'MacOS', 'defaults', 'profile')
    MOZILLA_BINARY          = os.path.join(firefoxDir, 'Contents', 'MacOS', 'firefox-bin')

elif sys.platform == 'linux2':
    firefoxBin = findInPath('firefox')

    if firefoxBin is not None and os.path.isfile(firefoxBin):
        MOZILLA_BINARY = firefoxBin

    MOZILLA_DEFAULT_PROFILE = None

    def NaN(str):
        try: int(str); return False;
        except: return True

    for path, name in (('/opt', 'firefox',),
                       ('/usr/lib', 'iceweasel',),
                       ('/usr/share', 'firefox',),
                       ('/usr/lib', 'mozilla-firefox',),
                       ('/usr/lib', 'firefox',),
                       ('/usr/lib64', 'iceweasel',),
                       ('/usr/lib64', 'mozilla-firefox',),
                       ('/usr/lib64', 'firefox',),
                       ):
        if os.path.isdir(path):
            profiles = sorted([d for d in os.listdir(os.path.join(path)) if (
                               d.startswith(name) ) and
                               ( os.path.isdir(os.path.join(path, d, 'defaults', 'profile')) ) and
                               ( ('-' not in d) or ( len(name+'-') <= len(d) and not NaN(d[len(name+'-')]) or
                               (d == 'mozilla-firefox')) )
                               ])
            if len(profiles) > 0:
                MOZILLA_DEFAULT_PROFILE = os.path.join(path, profiles[-1], 'defaults', 'profile')

elif os.name == 'nt' or sys.platform == 'cygwin':
    firefoxBin = findInPath('firefox')

    if sys.platform == 'cygwin':
        program_files = os.environ['PROGRAMFILES'].replace("\\", os.path.sep).replace(':', '')
        program_files = program_files[0].lower() + program_files[1:]
        program_files = '/cygdrive/'+program_files.replace("\\", os.path.sep)
    else:
        program_files = os.environ['ProgramFiles']

    bin_locations = [os.path.join(program_files, 'Mozilla Firefox', 'firefox.exe'),
                     os.path.join(program_files, 'Mozilla Firefox3', 'firefox.exe'),
                    ]

    if firefoxBin is None:
        for loc in bin_locations:
            if os.path.isfile(loc):
                firefoxBin = loc

    if firefoxBin is not None and os.path.isfile(firefoxBin):
        firefoxDir = os.path.dirname(firefoxBin)

        MOZILLA_BINARY          = firefoxBin
        MOZILLA_DEFAULT_PROFILE = os.path.join(firefoxDir, 'defaults', 'profile')


text:
#include "sphere.hpp"
#include <glm/vec3.hpp>
#include <cmath>

Sphere::Sphere() :
Shape{"none"},
center_{0.0, 0.0, 0.0},
radius_{1.0} {}

Sphere::Sphere(glm::vec3 const& center, double radius) :
Shape{"sphere_radius"},
center_{center},
radius_{radius} {}

Sphere::Sphere(Sphere const& x) :
Shape{"sphere_copy"},
center_{x.center_},
radius_{x.radius_} {}

double Sphere::getradius()
{
	return radius_;
}

glm::vec3 Sphere::getcenter()
{
	return center_;
}

double Sphere::area() const
{
	double a = 4*M_PI*radius_*radius_;
	return a;
}

double Sphere::volume() const
{
	double v = (4.0/3.0)*M_PI*radius_*radius_*radius_;
	return v;
}

/*std::string const& Sphere::name() const
{
  return name_;
}

Color const& Sphere::color() const
{
  return color_;
}*/

std::ostream& Sphere::print(std::ostream& os) const
{
  os << "Sphere";
  Shape::print(os);
  os << radius_;

  return os;
}

bool Sphere::intersect(Ray const& r) const
{
  auto v = glm::normalize(r.direction);
  float distance = 0;
  return glm::intersectRaySphere(r.origin, v, center_,radius_, distance);
}


text:
package newrelic

import (
	"fmt"

	"github.com/hashicorp/terraform/helper/schema"
)

func float64Gte(gte float64) schema.SchemaValidateFunc {
	return func(i interface{}, k string) (s []string, es []error) {
		v, ok := i.(float64)
		if !ok {
			es = append(es, fmt.Errorf("expected type of %s to be float64", k))
			return
		}

		if v >= gte {
			return
		}

		es = append(es, fmt.Errorf("expected %s to be greater than or equal to %v, got %v", k, gte, v))
		return
	}
}

func intInSlice(valid []int) schema.SchemaValidateFunc {
	return func(i interface{}, k string) (s []string, es []error) {
		v, ok := i.(int)
		if !ok {
			es = append(es, fmt.Errorf("expected type of %s to be int", k))
			return
		}

		for _, p := range valid {
			if v == p {
				return
			}
		}

		es = append(es, fmt.Errorf("expected %s to be one of %v, got %v", k, valid, v))
		return
	}
}


text:
module TDev {
    // device signature:
    //   touch-enabled
    //   physical keyboard present
    //   user-agent
    //   portrait vs landscape
    export enum Ticks {
        noEvent,

        mainInit,
        mainHashChange,
        mainKeyEvent,
        mainShortcutKeyEvent,  // i.e., not coming from textbox/textarea
        mainResetWorld,

        artSoundPreviewPlay,

        docsEdit,

        exportAzure,
        exportCordova,
        exportHTML5,

        scriptPropsIconArt,
        scriptPropsSplashArt,

        hourOfCodeDoneStep,
        hourOfCodeKeepCoding,
        hourOfCodeConfirm,
        hourOfCodeDone,
        hourOfCodeMore,
        hourOfCodeFinal,

        tutorialTranslateSplash,
        tutorialTranslateStep,
        tutorialTranslateScript,
        tutorialKeepEditing,
        tutorialMoreTutorials,

        dodStart,
        dodDrop,
        dodWrongTarget,

        cordovaBuild,

        translateDocTopic,

        legalNoticeSignIn,
        legalNoticeAgree,

        calcAddMissingArgs,
        calcBackspace,
        calcCopy,
        calcCut,
        calcDedicatedOp,
        calcEdit,
        calcEditString,
        calcExtract,
        calcPromoteToParameter,
        calcGoToDef,
        calcFindRefs,
        calcUnselect,
        calcExtend,
        calcReplaceInScript,
        calcReplaceInSelection,
        calcReplaceInAction,
        calcInsertAssignment,
        calcInsertString,
        calcIntelliButton,
        calcIntelliButton0,
        calcIntelliButton1,
        calcIntelliButton2,
        calcIntelliButton3,
        calcIntelliButton4,
        calcIntelliButton5plus,
        calcIntelliLiteral,
        calcIntelliLocal,
        calcIntelliProperty,
        calcIntelliPropertyPrimary,
        calcIntelliSingleton,
        calcIntelliLibrary,
        calcKeyboardSearch,
        calcMoveCursorLeft,
        calcMoveCursorRight,
        calcNewLine,
        calcNextIntelliTopPage,
        calcNextIntelliPageSearch,
        calcNextIntelliPage,
        calcNextIntelliPage0,
        calcNextIntelliPage1,
        calcNextIntelliPage2,
        calcNextIntelliPage3,
        calcNextIntelliPage4,
        calcNextIntelliPage5plus,
        calcAsync,
        calcAwait,
        calcNot,
        calcNumber,
        calcPaste,
        calcPickColor,
        calcPickNumber,
        calcDemoteIntoLocal,
        calcPromoteIntoGlobal,
        calcPromoteIntoField,
        calcRenameLocal,
        calcRenameProperty,
        calcSearchBack,
        calcSearchRun,
        calcSimplify,
        calcStrip,
        calcSpecialKey,
        calcStartSearch,
        calcStoreInVar,
        calcSwapBoolean,
        calcSwapAsync,
        calcIntelliAsync,
        calcSwitchToNormal,
        calcSwitchToNumber,
        calcTrueFalse,
        calcUndo,
        calcGoToBoxProperty,
        calcAddBoxProperty,
        calcInsertStringParamterValue,
        calcHelp,
        calcElseIf,
        calcUnElseIf,
        calcBindGlobal,
        calcFixItAtomic,
        calcEditArt,
        calcAddOptionalParameter,
        calcChangeOptionalParameter,

        codeAddAbove,
        codeAddBelow,
        codeBoxed,
        codeCopy,
        codeCopySelection,
        codeDeleteSelection,
        codeCut,
        codeCutSelection,
        codeCycleSidePane,
        codeCycleSidePaneFull,
        codeExtractAction,
        codeFocusSidePane,
        codeFocusSidePaneFull,
        codeFor,
        codeForEach,
        codeHub,
        codeIf,
        codeMoveLeft,
        codeNewVar,
        codePaste,
        codeRun,
        codeResume,
        codeStartSelection,
        codeSurround,
        codeUndo,
        codeSplit,
        codeWhile,
        codeUninstallScript,
        codeBackFromSearch,
        codeDelete,

        actionPropPrivate,
        actionPropTest,
        actionPropOffload,
        actionPropAtomic,

        btnPaste,
        btnCopy,
        btnCut,
        btnSelect,
        btnTryFix,
        btnUndoFix,
        btnAddUp,
        btnAddDown,
        btnMoveLeft,
        btnBreakpoint,
        btnChangeKind,
        calcBtnBackspace,
        calcBtnUndo,
        calcBtnNumberKeypad,
        calcBtnMiscKeypad,
        calcBtnNormalKeypad,
        calcBtnApiSearch,
        editBtnSideSearch,
        chooseCancel,
        editTapBelow,

        coverageShown,
        coverageOpenInEditor,
        coverageBucketSurveyActionEdit,
        coverageBucketSurveyStatementEdit,
        coverageBucketSurveyDebugger,
        coverageBucketSurveyBreakpoint,
        coverageBucketSurveyExceededSuccessfully,

        profileShown,
        profileOpenInEditor,

        debuggerExit,
        debuggerContinue,
        debuggerStepIn,
        debuggerStepOver,
        debuggerStepOut,
        debuggerToggleBreakpoint,
        debuggerViewInit,
        debuggerPauseWall,
        debuggerShowValues,
        debuggerShowStack,
        debuggerGotoWall,
        debuggerGotoCurrent,
        debuggerAppLog,
        debuggerHelp,
        debuggerValueClicked,
        debuggerKeyboardEvent,

        editorTutorialClose,
        editorTutorialNext,
        editorTutorialPrevious,

        sideAddAction,
        sideAddActionTest,
        sideAddActionTypeDef,
        sideAddEvent,
        sideAddLibrary,
        sideAddPage,
        sideAddRecord,
        sideAddObject,
        sideAddTable,
        sideAddIndex,
        sideAddResource,
        sideAddVariable,
        sideAddAnything,
        sideHelp,
        sideBraces,
        sideDebug,
        sideLogs,
        sideErrors,
        sideDeployWebSite,
        sidePlugins,
        sideButtonPlugin,
        sidePreview,
        sideHistory,
        sideHistoryGoTo,
        sidePaste,
        sideScript,
        sideScriptGoToDecl,
        sideSearch,
        sideSearchGoToDecl,
        sideSearchGoToStmt,
        sidePublish,
        sideShare,
        sideDisconnect,
        sideRun,
        sideCut,
        sideCopy,
        sideDelete,
        sideFindRefs,
        sideActionHeaderInit,
        sideCommentInit,
        sideParameterInit,
        sideResetSidePane,
        sideInlineActionInit,
        sideExport,
        sideAllTests,
        sideTestOne,
        sideEditLibrary,
        sideUpdate,
        sideUpdateOne,
        sideActionAddInput,
        sideActionAddOutput,
        sideMoveToLibrary,
        sideTutorialCancel,
        sideTutorialRedisplay,

        appsCreateAzureWebsite,
        appsDeployWebsite,

        pluginStop,
        pluginRunOperation,
        pluginAddMore,
        pluginRunAnnotationOperation,

        searchApiSynthesis,
        searchApiSearchArt,
        searchApiSearchLib,
        searchApiSearchAuto,
        searchApiInsertArt,
        searchApiUploadArt,
        searchApiInsertLib,

        wallBack, // do not rename, or fix tipmanager
        wallJS,
        wallEdit,
        wallReplay,
        wallScreenshot,
        wallLogs,
        wallStop,
        wallStopForce,
        wallPause,
        wallResume,
        wallRun,
        wallTraces,
        wallAddHeart,
        wallRemoveHeart,

        commentAttach,
        commentBugTracking,

        coreRun,
        coreResume,
        coreRerun,
        corePublishHidden,
        corePublishPublic,

        runtimePlayAgain,
        runtimeBack,

        appUpdateAvailable,
        appNoUpdate,
        appQuickUpdate,
        appUpdate,

        editorUpdateScript,
        editorUpdateLibrary,
        editorRunWithProfiling,
        editorRunWithCoverage,
        editorRunAsMinion,

        viewActionInit,
        viewLibraryRefInit,
        viewRecordInit,
        viewScriptInit,
        viewVariableInit,

        hubCreateScript,
        hubCreateGame,
        hubCreateGroup,
        hubJoinGroup,
        hubUploadPicture,
        hubUploadSound,
        hubGameTutorial,
        hubWinStore,
        hubDocs,
        hubFirstTutorial,
        hubDocsTutorial,
        hubBasicEditorVideo,
        hubBasicEditorVideoVoice,
        hubBasicEditorVideoSubtitles,
        hubBeginnersGettingStarted,
        hubChatSearch,
        hubRateTouchdevelop,
        hubChooseSkill,
        hubDevBootCamp,
        hubDocsApi,
        hubDocsWhatsNew,
        hubAdvancedEditorVideo,
        hubSeeMoreMyScripts,
        hubSeeMoreNewScripts,
        hubSeeMoreArt,
        hubSeeMoreUsers,
        hubSeeMoreCloudOther,
        hubSeeMoreShowcase,
        hubSeeMoreTopScripts,
        hubSeeMoreDocs,
        hubSeeMoreCloud,
        hubSeeMoreGroups,
        hubMyScriptsShowcase,
        hubMyScriptsTemplate,
        hubNotifications,
        hubUpdates,
        hubDoUpdates,
        hubTests,
        hubShowcaseMgmt,
        hubBenchmarks,
        hubForum,
        hubFacebook,
        hubTwitter,
        hubYouTube,
        hubSettings,
        hubAbout,
        hubHelp,
        hubWrongTime,
        hubTag,
        hubTagFromList,
        hubTagSearch,
        hubFeedback,
        hubChooseWallpaper,

        changeSkillScriptProperties,
        changeSkillActionProperties,
        changeSkillScriptExplorer,

        editorSkillBlock,
        editorSkillClassic,
        editorSkillCurly,

        groupCodeReset,
        groupCodeNew,
        groupCodeGet,
        groupDelete,
        groupLeave,
        groupJoin,
        groupAllowAnyoneToJoin,
        groupRequireInvitationCodeToJoin,
        groupChangePicture,

        publishShareGroup,

        browseRun,
        browseEdit,
        browsePin,
        browseHeart,
        browseUnHeart,
        browsePublish,
        browsePush,
        browseDiffBase,
        browseUpdate,
        browseSendPullRequest,
        browsePublicationNotes,
        browseListBugs,
        browseShare,
        browseListMyScripts,
        browseListNew,
        browseListTop,
        browseListShowcase,
        browseListForum,
        browseListDocs,
        browseListHelp,
        browseListGroups,
        browseListArt,
        browseListMyArt,
        browseListTags,
        browseFollowTopic,

        introSlideGetStarted,
        introSlideLimitations,
        introSlideCreateApps,
        introSlidePopCorn,
        introSlideLogIn,
        introSlideDismiss,

        recordAddKey,
        recordAddValue,
        recordPersTemporary,
        recordPersLocal,
        recordPersCloud,
        recordPersPartial,
        recordExported,

        dbgEvent,
        dbgLogEvent,

        learnPlayVideo,
        learnBrowseDoc,

        offlineLoginSync,
        offlineLoginSyncNoToken,
        offlineLoginGettingStarted,

        offlineEnsureLogin,
        offlineEnsureLoginOk,

        translateNagDisplay,
        translateNagOk,

        benchmarksNagDisplay,
        benchmarksNagDismiss,
        benchmarksNagRunOne,
        benchmarksNagRunSuite,

        songAlbumPlay,
        songPlay,

        warningNotificationTap,

        crashDialogEdit,
        crashDialogDebug,

        toLibNewLib,
        toLibExistingLib,
        toLibOKtoMove,
        toLibAdvanceSelectedToPending,
        toLibMakeTheMove,
        toLibDiscardPending,
        toLibExitToEditor,

        collabFirstLoad,
        collabResume,
        collabRecordAst,
        collabRealMerge,
        collabPostChatMessage,
        collabStartCollaboration,
        collabStopCollaboration
    }

    export interface TickEvent
    {
        timestamp:number;
        event:Ticks;
        arg?:string;
    }

    export interface BugReport {
        exceptionConstructor: string;
        exceptionMessage: string;
        context: string;
        currentUrl: string;
        jsUrl: string;
        scriptId: string;
        stackTrace: string;
        sourceURL: string;
        line: number;
        eventTrace: string;
        userAgent: string;
        resolution: string;
        timestamp: number;
        platform: string[];
        worldId: string;
        kind: string;
        attachments: string[];
    }

    export interface TicksReport {
        dateStr: string;
        sessionEvents: any;
        platform: string[];
        worldId: string;
        jsUrl: string;
    }

    export interface RecordedEvents
    {
        dateStr:string; // YYYY.MM.DD
        sessionEvents:any; // { (tickName: number)* }
        chunkId:number;
    }

    export module Ticker {
        var logMsgs:TickEvent[] = [];
        var logSz = 200;
        var logIdx = -1;
        var thresholdTime = -1
        var dateStr = ""
        var sessionEvents:any = {}
        var disabled = false;
        var delay = 10; // initial, 10s
        var chunkId = 1;
        var maxDelay = 1200; // 1200s
        var initialized = false;

        export var mainJsName = "unknown";

        export var fillEditorInfoBugReport: (b: BugReport) => void;
        export var fillEditorInfoTicksReport: (b: TicksReport) => void;

        function setDate():void
        {
            var now = new Date()
            dateStr = Util.fmt("{0}.{1}.{2}", now.getFullYear(), now.getMonth() + 1, now.getDate())
            if (delay > maxDelay)
                delay = maxDelay;
            thresholdTime = now.getTime() + delay*1000;
        }

        export function disable()
        {
            disabled = true
        }

        export function init()
        {
            var d = window.localStorage["ticksDelay"] * 1;
            if (d) delay = d;

            setDate();

            var archived = window.localStorage["archivedEvents"]
            if (archived) {
                var prevEvents:RecordedEvents[];
                try {
                    prevEvents = JSON.parse(archived)
                } catch (e) {
                    Util.log("bogus JSON in archivedEvents: " + archived)
                    Util.check(false, "malformed JSON in archived events");
                    delete window.localStorage["archivedEvents"]
                }

                if (prevEvents) {
                    prevEvents.forEach((e) => {
                        chunkId = Math.max(e.chunkId, chunkId)
                    });
                    chunkId++;
                    var last = prevEvents.peek()
                    if (!!last && last.dateStr == dateStr) {
                        sessionEvents = last.sessionEvents
                        prevEvents.pop()
                        window.localStorage["archivedEvents"] = JSON.stringify(prevEvents)
                    }
                    sendOutEvents(prevEvents);
                }
            }

            initialized = true;
        }

        export function saveCurrent(sendCurrent = false)
        {
            var prevEvents:RecordedEvents[] = []

            var archived = window.localStorage["archivedEvents"]
            if (archived)
                prevEvents = JSON.parse(archived)
            prevEvents.push({
                sessionEvents: sessionEvents,
                dateStr: dateStr,
                chunkId: chunkId++
            })

            prevEvents = prevEvents.filter((e) => !!e.dateStr)

            if (prevEvents.length > 30)
                prevEvents = prevEvents.slice(prevEvents.length - 30)

            var newVal = JSON.stringify(prevEvents)
            if (newVal.length > 50000)
                newVal = "[]" // drop it if it's getting big
            window.localStorage["archivedEvents"] = newVal

            if (sendCurrent && Cloud.getAccessToken() && Cloud.isOnline())
                (<any>sendOutEvents)(prevEvents); // TSBUG: stack overflow
        }

        function checkDate():void
        {
            if (Util.now() > thresholdTime) {
                setDate()
                saveCurrent(true)
                RT.Perf.saveCurrent(true);
                if (delay < maxDelay) {
                    delay *= 1.1;
                    window.localStorage["ticksDelay"] = delay + "";
                }
                sessionEvents = {}
            }
        }

        function sendOutEvents(events:RecordedEvents[])
        {
            if (events.length == 0) return;
            var currId = events[0].chunkId
            var req = <TicksReport>{
                dateStr: events[0].dateStr,
                sessionEvents: events[0].sessionEvents,
                platform: Browser.platformCaps,
                worldId: "",
                jsUrl: mainJsName
            }
            if (fillEditorInfoTicksReport)
                fillEditorInfoTicksReport(req);

            Cloud.postTicksAsync(req).done(() => {
                var events = window.localStorage["archivedEvents"]
                if (events) {
                    var newEvents:RecordedEvents[] = JSON.parse(events);
                    window.localStorage["archivedEvents"] = JSON.stringify(newEvents.filter((t) => t.chunkId != currId))
                    sendOutEvents(newEvents)
                }
            }, e => { }) // ignore error; will try again later
        }

        export function tickName(t:Ticks):string
        {
            return enumToString(Ticks, t);
        }

        export function tickN(t:Ticks, v:number)
        {
            tick(t + Util.boundTo(0, v, 5))
        }

        export function dbg(f:string, ...args:any[])
        {
            var msg = Util.fmt_va(f, args);
            tick(Ticks.dbgEvent, msg);
        }

        export function localStorageState()
        {
            if (!window || !window.localStorage) return "";

            var l = window.localStorage;
            var r = "";
            for (var i = 0; i < l.length; ++i) {
                r += l.key(i) + " -> " + l[l.key(i)].length + ",  ";
            }
            return r;
        }

        export function mkBugReport(err:any, ctx = "")
        {
            var r:BugReport = {
                exceptionConstructor: "(unknown)",
                exceptionMessage: "(unknown)",
                context: ctx,
                currentUrl: "",
                worldId: "",
                kind: "",
                scriptId: "",
                stackTrace: "",
                sourceURL: "",
                line: -1,
                eventTrace: "",
                userAgent: "",
                resolution: "",
                jsUrl: mainJsName,
                timestamp: Util.now(),
                platform: [],
                attachments: [],
            }

            if (fillEditorInfoBugReport)
                fillEditorInfoBugReport(r);

            if (Array.isArray(err.bugAttachments))
                r.attachments.pushRange(err.bugAttachments)

            try {
                var isDatabaseError = Util.isError(err, e => e.isDatabaseError);
                var isNetworkError = Util.isError(err, e => e.isNetworkError);
                r.kind = isDatabaseError ? "databaseError" : isNetworkError ? "networkError" : "";
                if (!err) r.exceptionMessage = "(null)";
                else if (err.message) {
                    r.exceptionMessage = err.message + "";
                    if (err.stack)
                        r.stackTrace = err.stack + "";
                    else if (err.sourceURL) // Safari doesn't give full stack trace, just top-level method
                        r.stackTrace = "@" + err.sourceURL + ":" + err.line;
                } else if (Array.isArray(err)) {
                    r.exceptionMessage = err.join("\n");
                } else {
                    r.exceptionMessage = err + "";
                }

                if (err && err.name && err.name != "Error")
                    r.exceptionConstructor = err.name;
                else
                    r.exceptionConstructor = r.exceptionMessage.substr(0, 40);
                if (isDatabaseError)
                    r.exceptionConstructor = "DB " + r.exceptionConstructor;
                if (/autotest-/.test(ctx))
                    r.exceptionConstructor = "TEST " + r.exceptionConstructor;

                if (err.wabCrashInfo) {
                    r.stackTrace = err.wabCrashInfo + "\nJavaScript:\n" + r.stackTrace;
                    r.exceptionConstructor = "WAB " + r.exceptionConstructor;
                }

                if (r.exceptionMessage && /\[object /.test(r.exceptionMessage)) {
                    var msg = r.exceptionMessage;
                    var errorInfo = Util.getErrorInfo(err);
                    if (errorInfo)
                        msg += " " + errorInfo;
                    else
                        Object.keys(err).forEach((k) => {
                            if (msg.length < 2000) {
                                msg += " " + k + ": '" + err[k] + "'";
                            }
                        });
                    r.exceptionMessage = msg;
                }

                if (/QUOTA/.test(r.exceptionMessage))
                    r.exceptionMessage += "  " + localStorageState();

                Ticker.dbg("CRASH REPORT " + r.exceptionMessage); // in case there is another crash report later

                if (err.sourceURL)
                    r.sourceURL = err.sourceURL;
                if (err.line)
                    r.line = err.line;
            } catch (e) {
                debugger;
            }

            try {
                RT.App.log("CRASH " + r.exceptionMessage)
            } catch (e) { }

            try {
                r.eventTrace = getRecentEvents().map((e) => {
                    var s = 1000000000 + (r.timestamp - e.timestamp) + "";
                    s = s.slice(-9);
                    return s.slice(0, 6) + "." + s.slice(6, 9) + ": " + tickName(e.event) + (e.arg ? "|" + e.arg : "");
                }).join("\n")
                if (!r.eventTrace)
                    r.eventTrace = Util.getLogMsgs().map(m => m.elapsed + ": " + m.msg).join("\n");
            } catch (e) {
                debugger;
            }

            if ((<any>window).tdAppInsights)
                try {
                (<any>window).tdAppInsights.trackException(err, r);
                } catch (e) { }

            return r;
        }

        export function bugReportToString(b:BugReport)
        {
            var e = (s:string) => s.replace(/\r?\n/, " ");
            return "Error: " + e(b.exceptionMessage) + "\n" +
                   "URL: " + e(b.currentUrl) + " (script: " + e(b.scriptId) + ", context: " + e(b.context) + ")\n" +
                   "JS-URL: " + e(b.jsUrl) + "\n" +
                   "Platform: " + e(Browser.platformCaps.join(", ")) + "\n" +
                   "UserAgent: " + e(b.userAgent) + " (resolution: " + e(b.resolution) + ")\n" +
                   "Date: " + new Date(b.timestamp).toString() + "\n" +
                   "\n" +
                   "RecentEvents:\n" + b.eventTrace + "\n\n" +
                   "StackTrace:\n" + b.stackTrace + "\n\n";
        }

        export function bugReportForHash(b:BugReport)
        {
            return b.exceptionMessage + " " + b.stackTrace;
        }

        export function rawTick(tn:string)
        {
            if (!initialized || disabled) return;

            checkDate();

            tn = tn.replace(/[^a-zA-Z_]/g, "_")

            Util.log("TICK: " + tn)
            if (sessionEvents[tn])
                sessionEvents[tn]++;
            else
                sessionEvents[tn] = 1;
        }

        function tickBase(t: Ticks, sep: string, arg?: string) {
            if (t == Ticks.noEvent || !t) return;

            var tn = tickName(t)
            if (arg)
                tn += sep + arg;
            if (t == Ticks.dbgLogEvent) {
                t = Ticks.dbgEvent;
            } else if (t == Ticks.dbgEvent)
                Util.log("DBG: " + tn);
            else Util.log("TICK: " + tn);

            if (!initialized || disabled) return;

            checkDate();

            var m = <TickEvent>{ timestamp: Util.now(), event: t, arg: arg }
            if (logIdx >= 0) {
                logMsgs[logIdx++] = m;
                if (logIdx >= logSz) logIdx = 0;
            } else {
                logMsgs.push(m);
                if (logMsgs.length >= logSz)
                    logIdx = 0;
            }

            // this one we only wanted logged, not counted
            if (t != Ticks.dbgEvent) {
                if (sessionEvents[tn])
                    sessionEvents[tn]++;
                else
                    sessionEvents[tn] = 1;

                if ((<any>window).tdAppInsights)
                    try {
                        (<any>window).tdAppInsights.trackEvent(tn);
                    } catch (e) { }
            }
        }

        export function tickArg(t: Ticks, arg?: string) {
            return tickBase(t, "$", arg);
        }

        export function tick(t:Ticks, arg?:string)
        {
            return tickBase(t, "|", arg);
        }

        export function getRecentEvents()
        {
            if (logIdx >= 0)
                return logMsgs.slice(logIdx).concat(logMsgs.slice(0, logIdx));
            else
                return logMsgs.slice(0);
        }
    }

    export function tick(t: Ticks, arg?: string) { Ticker.tick(t, arg) }
    export function tickArg(t: Ticks, arg?: string) { Ticker.tickArg(t, arg) }
    export function tickN(t:Ticks, v:number) { Ticker.tickN(t, v) }
}


text:
package i18n_test

import (
	"github.com/cloudfoundry/cli/cf/i18n"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("I18n", func() {
	Describe("SupportedLocales", func() {
		It("returns the list of locales in resources", func() {
			supportedLocales := i18n.SupportedLocales()
			Expect(supportedLocales).To(ContainElement("fr-FR"))
			Expect(supportedLocales).To(ContainElement("it-IT"))
			Expect(supportedLocales).To(ContainElement("ja-JP"))
			Expect(supportedLocales).To(ContainElement("zh-Hans"))
			Expect(supportedLocales).To(ContainElement("zh-Hant"))
			Expect(supportedLocales).To(ContainElement("en-US"))
			Expect(supportedLocales).To(ContainElement("es-ES"))
			Expect(supportedLocales).To(ContainElement("pt-BR"))
			Expect(supportedLocales).To(ContainElement("de-DE"))
			Expect(supportedLocales).To(ContainElement("ko-KR"))
		})
	})

	Describe("IsSupportedLocale", func() {
		It("returns true for supported locales", func() {
			Expect(i18n.IsSupportedLocale("fr-FR")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("Fr_Fr")).To(BeTrue())

			Expect(i18n.IsSupportedLocale("it-IT")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("ja-JP")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("zh-Hans")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("zh-Hant")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("en-US")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("es-ES")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("pt-BR")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("de-DE")).To(BeTrue())
			Expect(i18n.IsSupportedLocale("ko-KR")).To(BeTrue())
		})

		It("returns false for unsupported locales", func() {
			Expect(i18n.IsSupportedLocale("potato-Tomato")).To(BeFalse())
		})
	})
})


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.yourtion.SuperIDRN">

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false"/>
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false"/>
    <uses-feature
        android:name="android.hardware.camera.setParameters"
        android:required="false"/>

    <uses-permission android:name="android.permission.CAMERA"/>
    <!-- 阅读消息 -->
    <uses-permission android:name="android.permission.READ_SMS"/>
    <!-- 接收消息 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <!-- 读写⽂文件 -->
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 网络状态 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:allowBackup="true"
        android:supportsRtl="true"
        >

    <activity
            android:name="com.isnc.facesdk.aty.Aty_FaceDetect"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_NormalFaceDetect"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_AgreeItem"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_Auth"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_EditUserinfo"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_ClipPicture"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_CountryPage"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>
        <activity
            android:name="com.isnc.facesdk.aty.Aty_SecureEmail"
            android:label="SuperID"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar">
        </activity>

    </application>

</manifest>


text:
'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        '<%= nodeunit.tests %>',
      ],
      options: {
        jshintrc: '.jshintrc',
      },
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp'],
    },

    // set up tmp folders
    mkdir: {
      all: {
        options: {
          create: ['tmp/default', 'tmp/csp', 'tmp/inline', 'tmp/excludes', 'tmp/strip']
        }
      }
    },

    // Configuration to be run (and then tested).
    vulcanize: {
      default: {
        options: {
        },
        files: {
          'tmp/default/vulcanized.html': ['test/fixtures/index.html'],
        },
      },
      csp: {
        options: {
          csp: true
        },
        files: {
          'tmp/csp/vulcanized.html': ['test/fixtures/index.html'],
        },
      },
      inline: {
        options: {
          inline: true
        },
        files: {
          'tmp/inline/vulcanized.html': ['test/fixtures/index.html'],
        }
      },
      excludes: {
        options: {
          excludes: {
            imports: ['polymer.html']
          }
        },
        files: {
          'tmp/excludes/vulcanized.html': ['test/fixtures/index.html']
        }
      },
      strip: {
        options: {
          strip: true
        },
        files: {
          'tmp/strip/vulcanized.html': ['test/fixtures/index.html']
        }
      }
    },

    // Unit tests.
    nodeunit: {
      tests: ['test/*_test.js'],
    },

  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-mkdir');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', ['clean', 'mkdir', 'vulcanize', 'nodeunit']);

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'test']);

};


text:
/* See LICENSE for licensing information */

/**
 * \file dh_sizes.h

 * \brief Definitions for sizes of Diffie-Hellman groups elements in Z_p.
 *
 * Tor uses these definitions throughout its codebase, even in parts that
 * don't actually do any Diffie-Hellman calculations.
 **/

#ifndef TOR_DH_SIZES_H
#define TOR_DH_SIZES_H

/** Length of our legacy DH keys. */
#define DH1024_KEY_LEN (1024/8)

#endif /* !defined(TOR_DH_SIZES_H) */


text:
title:  "CoreData之Transformable属性"
date:   2016-12-23 11:39:23
categories: [iOS]
tags: [iOS]
comments: true
---
我们经常用到CoreData存储数据,但是CoreData能存储的基本都是一些标准的数据类型,当我们想存储`NSDictionary`、`NSArray`时,基本都是把它们转为 `NSData` 然后用 binary data 的类型写入到 Core Data,然后要用的时候再从 Core Data 中读出 NSData,再转回`NSDictionary`或者    `NSArray`。比如NSDictionary,我们可能用`NSJSONSerialization`的

``` objective_c
//NSData->NSDictionary
+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
//NSDictionary->NSData
+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
```

这两个方法转换,对NSArray,我们可能用`NSKeyedArchiver`的

``` objective_c
//NSArray->NSData
+ (NSData *)archivedDataWithRootObject:(id)rootObject;
//NSData->NSArray
+ (nullable id)unarchiveObjectWithData:(NSData *)data;
```

这两个方法转换。显然每次这样做是挺麻烦的。再看看Core Data还支持哪些我们没用过的类型,于是乎就看到了`Transformable `。

![CoreData支持Transformable类型](http://upload-images.jianshu.io/upload_images/1136939-b221b8027c4996c5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

关于`Transformable`,苹果开发文档是这样说的:

>The idea behind transformable attributes is that you access an attribute as a non-standard type, but behind the scenes Core Data uses an instance of NSValueTransformer to convert the attribute to and from an instance of NSData. Core Data then stores the data instance to the persistent store.

意思就是用了transformable属性,CoreData在底层自动帮我们把非标准类型与NSData之间做了转换,这就节省了很多人力,而且减少了错误概率。这个转换过程依赖了一个`NSValueTransformer`实例。`NSValueTransformer`用于把一个值转换为另一个值。它指定了可以处理哪类输入,并且合适时甚至支持反向的转换。

它的主要方法有:

``` objective_c
+ (void)setValueTransformer:(nullable NSValueTransformer *)transformer forName:(NSValueTransformerName)name;
 // class of the "output" objects, as returned by transformedValue:
+ (Class)transformedValueClass;
 // flag indicating whether transformation is read-only or not
+ (BOOL)allowsReverseTransformation;
 // by default returns value
- (nullable id)transformedValue:(nullable id)value;
// by default raises an exception if +allowsReverseTransformation returns NO and otherwise invokes transformedValue:
- (nullable id)reverseTransformedValue:(nullable id)value;
```

一个单例用一个名字来注册,其他几个方法定义了输入与输出的类型以及反向转换。

我们创建一个Students.xcdatamodel, 新建一个StudentEntity,有四个属性是`Tranformable`的,其中`courses`实际上是想存储NSArray类型,对应学生的课程表; `scores`实际上是想存储NSDictionary类型,对应学生的各科成绩;`contact`实际上是想存储自定义的Contact类型,对应学生的各种联系方式; `avatar`实际上是想存储UIImage类型,对应学生的头像。

![Students.xcdatamodel](http://upload-images.jianshu.io/upload_images/1136939-6b2e0204e6b28182.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

如果我们不指定NSValueTransformer的名字,Core Data 会默认使用
 NSKeyedUnarchiveFromDataTransformerName来注册一个transformer,它实际上用`archivedDataWithRootObject:`和`unarchiverObjectWithData:`方法来做类型转换。使用这个默认的transformer的非标准数据类型必须实现 NSCoding 协议,才能将其实例序列化为 NSData,并且进行存取。所以对于那些支持用`NSKeyedArchiver`转化并且实现了NSCoding协议的类型就可以直接使用默认的transformer了,比如NSDictionary、NSArrary等。
但是,对于一些不能直接用`NSKeyedArchiver`转换的非标准类型就不可以直接使用默认的transformer了,比如UIImage需要借助UIImagePNGRepresentation方法转换为NSData进行归档。此时,我们就需要自定义一个`NSValueTransformer`实例,并且重载几个关键的方法。

> If you specify a custom transformer, it must transform an instance of the non-standard data type into an instance of NSData and support reverse transformation.

首先,我们如上图所示,对`avatar`属性的Value Transformer取个名字,比如UIIMageToNSDataTransformer, 那在对应的studentEntity.h文件中,我们定义一个UIIMageToNSDataTransformer类继承自NSValueTransformer。

``` objective_c
// studentEntity.h
@interface StudentEntity : RHManagedObject
@property (nonatomic,strong) NSNumber *sid;
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSNumber *age;
@property (nonatomic,strong) id       courses;//dictionary
@property (nonatomic,strong) id       scores;//array
@property (nonatomic,strong) id       avatar;//image;
@property (nonatomic,strong) id       contact;//custom class
@end

@interface UIIMageToNSDataTransformer: NSValueTransformer

@end
```

在studentEntity.m文件中重载几个方法:

``` objective_c
+ (Class)transformedValueClass {
    return [NSData class];
}
+ (BOOL)allowsReverseTransformation {
    return YES;
}
- (id)transformedValue:(id)value
{
    if (value == nil) {
        return nil;
    }
    if ([value isKindOfClass:[NSData class]]) {
        return value;
    }
    return UIImagePNGRepresentation((UIImage *)value);
}
- (id)reverseTransformedValue:(id)value
{
    return [UIImage imageWithData:(NSData *)value];
}
```
这样,就可以像NSDictionary一样简便地存取UIImage属性值了。

另外,对于我们自定义的Contact类型,要想使用这种转化,必须要实现NSCoding协议,既实现:

``` objective_c
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
```
这两个方法。我们这样做:

``` objective_c
@interface Contact : NSObject <NSCoding>

@property (nonatomic, strong) NSString  *addr;
@property (nonatomic, strong) NSString  *phone;
@property (nonatomic, assign) NSInteger qq;

@end

@implementation Contact

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _addr   = [aDecoder decodeObjectForKey:@"addr"];
        _phone  = [aDecoder decodeObjectForKey:@"phone"];
        _qq     = [aDecoder decodeIntegerForKey:@"qq"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_addr forKey:@"addr"];
    [aCoder encodeObject:_phone forKey:@"phone"];
    [aCoder encodeInteger:_qq forKey:@"qq"];
}

@end
```
至此,我们就可以很方便地存取上面所有的数据了,而不用每次手动转化了。

``` objective_c
- (instancetype)initWithModel:(StudentModel *)model
{
    self = [super init];
    if (self) {
        self.sid    = model.sid;
        self.name   = model.name;
        self.age    = model.age;
        self.avatar = model.avatar;//直接赋值,不需转化
        self.courses = model.courses;//直接赋值,不需转化
        self.scores  = model.scores;//直接赋值,不需转化
        self.contact = model.contact;//直接赋值,不需转化
    }
    return self;
}

- (void)setModel:(StudentModel *)model {
    model.sid   = self.sid;
    model.name  = self.name;
    model.age   = self.age;
    model.avatar = self.avatar;//直接赋值,不需转化
    model.courses = self.courses;//直接赋值,不需转化
    model.scores  = self.scores;//直接赋值,不需转化
    model.contact = self.contact;//直接赋值,不需转化
}
```

我们先测试写入数据:

``` objective_c

StudentProfile *profile = [[StudentProfile alloc] init];
profile.sid     = @(1001);
profile.name    = @"小明";
profile.age     = @(12);
profile.courses = [NSMutableArray arrayWithObjects:kCourseYuwen,kCourseShuxu,kCourseYinyu, nil];
profile.avatar  = [UIImage imageNamed:@"default_avatar"];
profile.scores  = [NSMutableDictionary dictionary];
[profile.scores setObject:@(80) forKey:kCourseYuwen];
[profile.scores setObject:@(91) forKey:kCourseShuxu];
[profile.scores setObject:@(88) forKey:kCourseYinyu];

profile.contact = [Contact new];
profile.contact.addr = @"希望小学3年2班";
profile.contact.phone = @"188-1221-3309";
profile.contact.qq = 1033294537;
//save data
[[_Dao getStudentDao] saveStudentProfile:profile commit:YES];
```

然后读取数据:

``` objective_c
NSArray *students = [[_Dao getStudentDao] loadAll];

for (StudentProfile *student in students) {
    NSLog(@"==========ID  :%@==========",student.sid);
    NSLog(@"==========NAME:%@==========",student.name);
    NSLog(@"==========AGE :%@==========",student.age);
    for (id key in student.scores) {
        NSString *course = key;
        NSLog(@"==========%@ :%@分==========",course,[student.scores objectForKey:key]);
    }
    NSLog(@"==========ADDR :%@==========",student.contact.addr);
    NSLog(@"==========PHONE:%@==========",student.contact.phone);
    NSLog(@"==========QQ   :%ld==========",student.contact.qq);

    UIImage *avatar = student.avatar;
    NSLog(@"==========AVATAR :%@==========",avatar);
}
```

输入结果:

``` objective_c
==========ID  :1001==========
==========NAME:小明==========
==========AGE :12==========
==========语文 :80分==========
==========数学 :91分==========
==========英语 :88分==========
==========ADDR :希望小学3年2班==========
==========PHONE:188-1221-3309==========
 ==========QQ  :1033294537==========
==========AVATAR :<UIImage: 0x60000009cf20>, {60, 48}==========
```

如果我们不自定义UIIMageToNSDataTransformer的,avatar输出是NULL,既存取失败的。如果Contact不实现NSCoding协议,程序会crash的。

BTW:使用自定义的 transformer 还可以引申出另一个应用,就是可以用于对 entity 中某个 attribute 进行加密/解密,用自定义的加密/解密算法。单独对某个 attribute 进行加密/解密,可以避免对整个 entity 甚至是整个 database 进行加密/解密,提高了性能,降低了内存消耗。

更深入的学习可以参考 [TransformerKit库](https://github.com/mattt/TransformerKit/blob/master/TransformerKit/NSValueTransformer%2BTransformerKit.m#L36)


text:
package org.etower.repository.main;

import org.etower.core.domain.EtLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface SysLogDao extends PagingAndSortingRepository<EtLog, Long>,
		JpaSpecificationExecutor<EtLog> {

	@Modifying
	@Query("delete from EtLog log where log.id = ?1")
	void deleteById(Long id);
}


text:
package org.ejml.equation;

import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;

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

/**
 * matrix used to construct a matrix from a sequence of concatenations.
 *
 * @author Peter Abeles
 */
public class MatrixConstructor {

    VariableMatrix output;
    List<Item> items = new ArrayList<Item>();

    List<VariableScalar> tmp = new ArrayList<VariableScalar>();

    public MatrixConstructor(ManagerTempVariables manager) {
        this.output = manager.createMatrix();
    }

    public void addToRow(Variable variable) {
       items.add( new Item(variable));
    }

    public void endRow() {
        items.add(new Item());
    }

    public void construct() {
        // make sure the last item is and end row
        if( !items.get(items.size()-1).endRow )
            endRow();

        setToRequiredSize(output.matrix);

        int matrixRow = 0;
        List<Item> row = new ArrayList<Item>();
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);

            if( item.endRow ) {
                Item v = row.get(0);
                int numRows = v.getRows();
                int numCols = v.getColumns();
                if( v.matrix ) {
                    CommonOps.insert(v.getMatrix(),output.matrix,matrixRow,0);
                } else {
                    output.matrix.set(matrixRow,0,v.getValue());
                }
                for (int j = 1; j < row.size(); j++) {
                    v = row.get(j);
                    if( v.getRows() != numRows)
                        throw new RuntimeException("Row miss-matched. "+numRows+" "+v.getRows());
                    if( v.matrix ) {
                        CommonOps.insert(v.getMatrix(),output.matrix,matrixRow,numCols);
                    } else {
                        output.matrix.set(matrixRow, numCols, v.getValue());
                    }
                    numCols += v.getColumns();
                }
                matrixRow += numRows;
                row.clear();
            } else {
                row.add(item);
            }
        }

    }

    public VariableMatrix getOutput() {
        return output;
    }

    protected void setToRequiredSize( DenseMatrix64F matrix ) {

        int matrixRow = 0;
        int matrixCol = 0;
        List<Item> row = new ArrayList<Item>();
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);

            if( item.endRow ) {
                Item v = row.get(0);
                int numRows = v.getRows();
                int numCols = v.getColumns();
                for (int j = 1; j < row.size(); j++) {
                    v = row.get(j);
                    if( v.getRows() != numRows)
                        throw new RuntimeException("Row miss-matched. "+numRows+" "+v.getRows());
                    numCols += v.getColumns();
                }
                matrixRow += numRows;

                if( matrixCol == 0 )
                    matrixCol = numCols;
                else if( matrixCol != numCols )
                    throw new RuntimeException("Unexpected number of columns");

                row.clear();
            } else {
                row.add(item);
            }
        }

        matrix.reshape(matrixRow,matrixCol);
    }

    private static class Item
    {
        Variable variable;
        boolean endRow;
        boolean matrix;

        private Item(Variable variable) {
            this.variable = variable;
            matrix = variable instanceof VariableMatrix;
        }

        private Item() {
            endRow = true;
        }

        public int getRows() {
            if( matrix ) {
                return ((VariableMatrix)variable).matrix.numRows;
            } else {
                return 1;
            }
        }

        public int getColumns() {
            if( matrix ) {
                return ((VariableMatrix)variable).matrix.numCols;
            } else {
                return 1;
            }
        }

        public DenseMatrix64F getMatrix() {
            return ((VariableMatrix)variable).matrix;
        }

        public double getValue() {
            return ((VariableScalar)variable).getDouble();
        }
    }
}


text:
require 'koala/api'
require 'koala/api/graph_batch_api'

module Koala
  module Facebook
    class GraphBatchAPI < API
      # @private
      class BatchOperation
        attr_reader :access_token, :http_options, :post_processing, :files, :batch_api, :identifier

        @identifier = 0

        def self.next_identifier
          @identifier += 1
        end

        def initialize(options = {})
          @identifier = self.class.next_identifier
          @args = (options[:args] || {}).dup # because we modify it below
          @access_token = options[:access_token]
          @http_options = (options[:http_options] || {}).dup # dup because we modify it below
          @batch_args = @http_options.delete(:batch_args) || {}
          @url = options[:url]
          @method = options[:method].to_sym
          @post_processing = options[:post_processing]

          process_binary_args

          raise AuthenticationError.new(nil, nil, "Batch operations require an access token, none provided.") unless @access_token
        end

        def to_batch_params(main_access_token, app_secret)
          # set up the arguments
          if @access_token != main_access_token
            @args[:access_token] = @access_token
            if app_secret
              @args[:appsecret_proof] = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), app_secret, @access_token)
            end
          end
          args_string = Koala.http_service.encode_params(@args)

          response = {
            :method => @method.to_s,
            :relative_url => @url,
          }

          # handle batch-level arguments, such as name, depends_on, and attached_files
          @batch_args[:attached_files] = @files.keys.join(",") if @files
          response.merge!(@batch_args) if @batch_args

          # for get and delete, we append args to the URL string
          # otherwise, they go in the body
          if args_string.length > 0
            if args_in_url?
              response[:relative_url] += (@url =~ /\?/ ? "&" : "?") + args_string if args_string.length > 0
            else
              response[:body] = args_string if args_string.length > 0
            end
          end

          response
        end

        protected

        def process_binary_args
          # collect binary files
          @args.each_pair do |key, value|
            if HTTPService::UploadableIO.binary_content?(value)
              @files ||= {}
              # we use a class-level counter to ensure unique file identifiers across multiple batch operations
              # (this is thread safe, since we just care about uniqueness)
              # so remove the file from the original hash and add it to the file store
              id = "op#{identifier}_file#{@files.keys.length}"
              @files[id] = @args.delete(key).is_a?(HTTPService::UploadableIO) ? value : HTTPService::UploadableIO.new(value)
            end
          end
        end

        def args_in_url?
          @method == :get || @method == :delete
        end
      end
    end
  end
end


text:
import { Component, Input } from '@angular/core';

import { TuneBookService, Tune } from '../../business/index';

@Component({
    moduleId: module.id,
    selector: 'etb-tune-info-list',
    templateUrl: 'tune-info-list.component.html',
    styleUrls: ['tune-info-list.component.css']
})
export class TuneInfoListComponent {
    @Input() tune: Tune;

    constructor(public tuneBookService: TuneBookService) {

    }
}


text:
'use strict';

var Klass = require('Klass'),
	Loading = require('Widgets/Loading');

var BuyButton = Klass.create({

	name: 'BuyButton',

	buttons: null,

	construct: function(buttons) {
		this.buttons = $(buttons);

		this.initLoading();

		this.bindEvents();
	},

	initLoading: function() {
		this.loading = new Loading();

		this.loading.compile();

		$(document.body).append(this.loading.compiled);

		this.loading.setFixed(true);
	},

	bindEvents: function() {
		this.buttons.on('click', this.onClick.bind(this));
	},

	doCheckout: function() {
		var me = this;

		$.ajax({
			url: '/rest/payment/checkout',
			success: function(response) {
				var url = response.url;

				me.loading.setState(false);

				window.location = url;
			},
			error: function(result) {
				me.loading.setState(false);

				alert('Desculpe, um erro ocoreu ao registrar a venda, tente novamente mais tarde!');

				console.log(result.responseJSON);
			}
		});
	},

	onClick: function () {
		this.loading.setState(true);

		this.doCheckout();
	}
});

module.exports = BuyButton;


text:
template: example.html
title: Device-Orientation example
shortdesc: Listen to DeviceOrientation events.
docs: >
  This example shows how to track changes in device orientation.
tags: "orientation, openstreetmap"
---

Device orientation example

        <input id="track" type="checkbox"/>track changes

α :

β :

γ :

heading :


text:
DISTROS=("centos6")
INITS=("/sbin/init")

# Assuming our GitHub repo / directory name is the role name
PARENT_DIR="$(dirname $(cd `dirname $0` && pwd))"
ROLE_NAME=${PARENT_DIR##*/}

# Color hints for alerts and messages
GREEN='\033[1;32m'
RED='\033[0;31m'
NC='\033[0m'

# An informational message in case a test fails
die () {
  echo ""
  printf "${RED}Tests failed!${NC}\n"
  echo ""
  printf "  ${GREEN}To clean up the testing container, run:${NC}\n"
  echo "    docker rm -f \"$(cat $1)\""
  echo ""
  printf "  ${GREEN}To clean up all system containers, run:${NC}\n"
  echo "    docker rm -f \$(docker ps -a -q)"
  echo ""

  exit 1
}

# Our tests need Docker installed
hash docker 2>/dev/null || { echo >&2 "I require Docker to be installed to run tests. Aborting."; exit 1; }

for ((INDEX = 0; INDEX < ${#DISTROS[@]}; INDEX++)); do
  DISTRO="${DISTROS[$INDEX]}"
  INIT="${INITS[$INDEX]}"

  docker pull geerlingguy/docker-${DISTRO}-ansible:latest

  CONTAINER_ID=$(mktemp)
  IDEMPOTENCE=$(mktemp)

  docker run --detach --volume="${PWD}":/etc/ansible/roles/${ROLE_NAME}:ro geerlingguy/docker-${DISTRO}-ansible:latest "${INIT}" > "${CONTAINER_ID}"
  docker exec --tty "$(cat ${CONTAINER_ID})" env TERM=xterm ansible-playbook /etc/ansible/roles/${ROLE_NAME}/tests/test.yml --syntax-check
  docker exec --tty "$(cat ${CONTAINER_ID})" env TERM=xterm sed -i -e "s/#retry_files_enabled/retry_files_enabled/g" /etc/ansible/ansible.cfg
  docker exec --tty "$(cat ${CONTAINER_ID})" env TERM=xterm ansible-playbook -v /etc/ansible/roles/${ROLE_NAME}/tests/test.yml
  docker exec "$(cat ${CONTAINER_ID})" ansible-playbook /etc/ansible/roles/${ROLE_NAME}/tests/test.yml | tee -a ${IDEMPOTENCE}
  tail ${IDEMPOTENCE} | grep -q "changed=0.*failed=0" && (echo "Idempotence test: passed" && exit 0) || (echo "Idempotence test: failed" && die "$CONTAINER_ID")

  # Tests specific to this role
  source tests/validate-results.sh "$DISTRO" "$CONTAINER_ID"

  # Some hints about what to do with the test resources
  echo ""
  echo "For further in-container testing, run:"
  echo "  docker exec -it \"$(cat ${CONTAINER_ID})\" bash"
  echo ""
  echo "To clean up the testing container, run:"
  echo "  docker rm -f \"$(cat ${CONTAINER_ID})\""
  echo ""
  echo "To clean up all system containers, run:"
  echo "  docker rm -f \$(docker ps -a -q)"
  echo ""
done


text:
/**
 * Module dependencies.
 */

var debug = require('debug')('superagent');
var formidable = require('formidable');
var FormData = require('form-data');
var Response = require('./response');
var parse = require('url').parse;
var format = require('url').format;
var methods = require('methods');
var Stream = require('stream');
var utils = require('./utils');
var extend = require('extend');
var Part = require('./part');
var mime = require('mime');
var https = require('https');
var http = require('http');
var fs = require('fs');
var qs = require('qs');
var zlib = require('zlib');
var util = require('util');
var pkg = require('../../package.json');

/**
 * Expose the request function.
 */

exports = module.exports = request;

/**
 * Expose the agent function
 */

exports.agent = require('./agent');

/**
 * Expose `Part`.
 */

exports.Part = Part;

/**
 * Noop.
 */

function noop(){};

/**
 * Expose `Response`.
 */

exports.Response = Response;

/**
 * Define "form" mime type.
 */

mime.define({
  'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data']
});

/**
 * Protocol map.
 */

exports.protocols = {
  'http:': http,
  'https:': https
};

/**
 * Check if `obj` is an object.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isObject(obj) {
  return null != obj && 'object' == typeof obj;
}

/**
 * Default serialization map.
 *
 *     superagent.serialize['application/xml'] = function(obj){
 *       return 'generated xml here';
 *     };
 *
 */

exports.serialize = {
  'application/x-www-form-urlencoded': qs.stringify,
  'application/json': JSON.stringify
};

/**
 * Default parsers.
 *
 *     superagent.parse['application/xml'] = function(res, fn){
 *       fn(null, result);
 *     };
 *
 */

exports.parse = require('./parsers');

/**
 * Initialize a new `Request` with the given `method` and `url`.
 *
 * @param {String} method
 * @param {String|Object} url
 * @api public
 */

function Request(method, url) {
  Stream.call(this);
  var self = this;
  if ('string' != typeof url) url = format(url);
  this._agent = false;
  this._formData = null;
  this.method = method;
  this.url = url;
  this.header = {};
  this.writable = true;
  this._redirects = 0;
  this.redirects(5);
  this.cookies = '';
  this.qs = {};
  this._redirectList = [];
  this.on('end', this.clearTimeout.bind(this));
  this.on('response', function(res){
    self.callback(null, res);
  });
}

/**
 * Inherit from `Stream`.
 */

util.inherits(Request, Stream);

/**
 * Write the field `name` and `val` for "multipart/form-data"
 * request bodies.
 *
 * ``` js
 * request.post('http://localhost/upload')
 *   .field('foo', 'bar')
 *   .end(callback);
 * ```
 *
 * @param {String} name
 * @param {String|Buffer|fs.ReadStream} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.field = function(name, val){
  debug('field', name, val);
  if (!this._formData) this._formData = new FormData();
  this._formData.append(name, val);
  return this;
};

/**
 * Queue the given `file` as an attachment to the specified `field`,
 * with optional `filename`.
 *
 * ``` js
 * request.post('http://localhost/upload')
 *   .attach(new Buffer('<b>Hello world</b>'), 'hello.html')
 *   .end(callback);
 * ```
 *
 * A filename may also be used:
 *
 * ``` js
 * request.post('http://localhost/upload')
 *   .attach('files', 'image.jpg')
 *   .end(callback);
 * ```
 *
 * @param {String} field
 * @param {String|fs.ReadStream|Buffer} file
 * @param {String} filename
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.attach = function(field, file, filename){
  if (!this._formData) this._formData = new FormData();
  if ('string' == typeof file) {
    filename = file;
    debug('creating `fs.ReadStream` instance for file: %s', filename);
    file = fs.createReadStream(filename);
  }
  this._formData.append(field, file, filename);
  return this;
};

/**
 * Set the max redirects to `n`.
 *
 * @param {Number} n
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.redirects = function(n){
  debug('max redirects %s', n);
  this._maxRedirects = n;
  return this;
};

/**
 * Return a new `Part` for this request.
 *
 * @return {Part}
 * @api public
 * @deprecated pass a readable stream in to `Request#attach()` instead
 */

Request.prototype.part = util.deprecate(function(){
  return new Part(this);
}, '`Request#part()` is deprecated. ' +
   'Pass a readable stream in to `Request#attach()` instead.');

/**
 * Gets/sets the `Agent` to use for this HTTP request. The default (if this
 * function is not called) is to opt out of connection pooling (`agent: false`).
 *
 * @param {http.Agent} agent
 * @return {http.Agent}
 * @api public
 */

Request.prototype.agent = function(agent){
  if (!arguments.length) return this._agent;
  this._agent = agent;
  return this;
};

/**
 * Set header `field` to `val`, or multiple fields with one object.
 *
 * Examples:
 *
 *      req.get('/')
 *        .set('Accept', 'application/json')
 *        .set('X-API-Key', 'foobar')
 *        .end(callback);
 *
 *      req.get('/')
 *        .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
 *        .end(callback);
 *
 * @param {String|Object} field
 * @param {String} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.set = function(field, val){
  if (isObject(field)) {
    for (var key in field) {
      this.set(key, field[key]);
    }
    return this;
  }

  debug('set %s "%s"', field, val);
  this.request().setHeader(field, val);
  return this;
};

/**
 * Remove header `field`.
 *
 * Example:
 *
 *      req.get('/')
 *        .unset('User-Agent')
 *        .end(callback);
 *
 * @param {String} field
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.unset = function(field){
  debug('unset %s', field);
  this.request().removeHeader(field);
  return this;
};

/**
 * Get request header `field`.
 *
 * @param {String} field
 * @return {String}
 * @api public
 */

Request.prototype.get = function(field){
  return this.request().getHeader(field);
};

/**
 * Set _Content-Type_ response header passed through `mime.lookup()`.
 *
 * Examples:
 *
 *      request.post('/')
 *        .type('xml')
 *        .send(xmlstring)
 *        .end(callback);
 *
 *      request.post('/')
 *        .type('json')
 *        .send(jsonstring)
 *        .end(callback);
 *
 *      request.post('/')
 *        .type('application/json')
 *        .send(jsonstring)
 *        .end(callback);
 *
 * @param {String} type
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.type = function(type){
  return this.set('Content-Type', ~type.indexOf('/')
    ? type
    : mime.lookup(type));
};

/**
 * Set _Accept_ response header passed through `mime.lookup()`.
 *
 * Examples:
 *
 *      superagent.types.json = 'application/json';
 *
 *      request.get('/agent')
 *        .accept('json')
 *        .end(callback);
 *
 *      request.get('/agent')
 *        .accept('application/json')
 *        .end(callback);
 *
 * @param {String} accept
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.accept = function(type){
  return this.set('Accept', ~type.indexOf('/')
    ? type
    : mime.lookup(type));
};

/**
 * Add query-string `val`.
 *
 * Examples:
 *
 *   request.get('/shoes')
 *     .query('size=10')
 *     .query({ color: 'blue' })
 *
 * @param {Object|String} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.query = function(val){
  var obj = {};

  if ('string' == typeof val) {
    var elements = val.split('&');
    for (var i = 0; i < elements.length; i++) {
      var parts = elements[i].split('=');
      obj[parts[0]] = parts[1];
    }
    return this.query(obj);
  }

  extend(this.qs, val);
  return this;
};

/**
 * Send `data`, defaulting the `.type()` to "json" when
 * an object is given.
 *
 * Examples:
 *
 *       // manual json
 *       request.post('/user')
 *         .type('json')
 *         .send('{"name":"tj"}')
 *         .end(callback)
 *
 *       // auto json
 *       request.post('/user')
 *         .send({ name: 'tj' })
 *         .end(callback)
 *
 *       // manual x-www-form-urlencoded
 *       request.post('/user')
 *         .type('form')
 *         .send('name=tj')
 *         .end(callback)
 *
 *       // auto x-www-form-urlencoded
 *       request.post('/user')
 *         .type('form')
 *         .send({ name: 'tj' })
 *         .end(callback)
 *
 *       // string defaults to x-www-form-urlencoded
 *       request.post('/user')
 *         .send('name=tj')
 *         .send('foo=bar')
 *         .send('bar=baz')
 *         .end(callback)
 *
 * @param {String|Object} data
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.send = function(data){
  var obj = isObject(data);
  var req = this.request();
  var type = req.getHeader('Content-Type');

  // merge
  if (obj && isObject(this._data)) {
    for (var key in data) {
      this._data[key] = data[key];
    }
  // string
  } else if ('string' == typeof data) {
    // default to x-www-form-urlencoded
    if (!type) this.type('form');
    type = req.getHeader('Content-Type');

    // concat &
    if ('application/x-www-form-urlencoded' == type) {
      this._data = this._data
        ? this._data + '&' + data
        : data;
    } else {
      this._data = (this._data || '') + data;
    }
  } else {
    this._data = data;
  }

  if (!obj) return this;

  // default to json
  if (!type) this.type('json');
  return this;
};

/**
 * Write raw `data` / `encoding` to the socket.
 *
 * @param {Buffer|String} data
 * @param {String} encoding
 * @return {Boolean}
 * @api public
 */

Request.prototype.write = function(data, encoding){
  return this.request().write(data, encoding);
};

/**
 * Pipe the request body to `stream`.
 *
 * @param {Stream} stream
 * @param {Object} options
 * @return {Stream}
 * @api public
 */

Request.prototype.pipe = function(stream, options){
  this.piped = true; // HACK...
  this.buffer(false);
  this.end().req.on('response', function(res){
    if (/^(deflate|gzip)$/.test(res.headers['content-encoding'])) {
      res.pipe(zlib.createUnzip()).pipe(stream, options);
    } else {
      res.pipe(stream, options);
    }
  });
  return stream;
};

/**
 * Enable / disable buffering.
 *
 * @return {Boolean} [val]
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.buffer = function(val){
  this._buffer = false === val
    ? false
    : true;
  return this;
};

/**
 * Set timeout to `ms`.
 *
 * @param {Number} ms
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.timeout = function(ms){
  this._timeout = ms;
  return this;
};

/**
 * Clear previous timeout.
 *
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.clearTimeout = function(){
  debug('clear timeout %s %s', this.method, this.url);
  this._timeout = 0;
  clearTimeout(this._timer);
  return this;
};

/**
 * Abort and clear timeout.
 *
 * @api public
 */

Request.prototype.abort = function(){
  debug('abort %s %s', this.method, this.url);
  this._aborted = true;
  this.clearTimeout();
  this.req.abort();
};

/**
 * Define the parser to be used for this response.
 *
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.parse = function(fn){
  this._parser = fn;
  return this;
};

/**
 * Redirect to `url
 *
 * @param {IncomingMessage} res
 * @return {Request} for chaining
 * @api private
 */

Request.prototype.redirect = function(res){
  var url = res.headers.location;
  debug('redirect %s -> %s', this.url, url);

  // location
  if (!~url.indexOf('://')) {
    if (0 != url.indexOf('//')) {
      url = '//' + this.host + url;
    }
    url = this.protocol + url;
  }

  // ensure the response is being consumed
  // this is required for Node v0.10+
  res.resume();

  // strip Content-* related fields
  // in case of POST etc
  var header = utils.cleanHeader(this.req._headers);
  delete this.req;

  // force GET
  this.method = 'HEAD' == this.method
    ? 'HEAD'
    : 'GET';

  // redirect
  this._data = null;
  this.url = url;
  this._redirectList.push(url);
  this.clearTimeout();
  this.emit('redirect', res);
  this.set(header);
  this.end(this._callback);
  return this;
};

/**
 * Set Authorization field value with `user` and `pass`.
 *
 * @param {String} user
 * @param {String} pass
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.auth = function(user, pass){
  if (pass) pass = ':' + pass;
  var str = new Buffer(user + (pass || '')).toString('base64');
  return this.set('Authorization', 'Basic ' + str);
};

/**
 * Set the certificate authority option for https request.
 *
 * @param {Buffer | Array} cert
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.ca = function(cert){
  this._ca = cert;
  return this;
};

/**
 * Return an http[s] request.
 *
 * @return {OutgoingMessage}
 * @api private
 */

Request.prototype.request = function(){
  if (this.req) return this.req;

  var self = this;
  var options = {};
  var data = this._data;
  var url = this.url;

  // default to http://
  if (0 != url.indexOf('http')) url = 'http://' + url;
  url = parse(url, true);

  // options
  options.method = this.method;
  options.port = url.port;
  options.path = url.pathname;
  options.host = url.hostname;
  options.ca = this._ca;
  options.agent = this._agent;

  // initiate request
  var mod = exports.protocols[url.protocol];

  // request
  var req = this.req = mod.request(options);
  if ('HEAD' != options.method) req.setHeader('Accept-Encoding', 'gzip, deflate');
  this.protocol = url.protocol;
  this.host = url.host;

  // expose events
  req.on('drain', function(){ self.emit('drain'); });

  req.on('error', function(err){
    // flag abortion here for out timeouts
    // because node will emit a faux-error "socket hang up"
    // when request is aborted before a connection is made
    if (self._aborted) return;
    self.callback(err);
  });

  // auth
  if (url.auth) {
    var auth = url.auth.split(':');
    this.auth(auth[0], auth[1]);
  }

  // query
  this.query(url.query);

  // add cookies
  req.setHeader('Cookie', this.cookies);

  // set default UA
  req.setHeader('User-Agent', 'node-superagent/' + pkg.version);

  return req;
};

/**
 * Invoke the callback with `err` and `res`
 * and handle arity check.
 *
 * @param {Error} err
 * @param {Response} res
 * @api private
 */

Request.prototype.callback = function(err, res){
  var fn = this._callback;
  this.clearTimeout();
  if (this.called) return console.warn('double callback!');
  this.called = true;
  if (2 == fn.length) return fn(err, res);
  if (err) return this.emit('error', err);
  fn(res);
};

/**
 * Initiate request, invoking callback `fn(err, res)`
 * with an instanceof `Response`.
 *
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.end = function(fn){
  var self = this;
  var data = this._data;
  var req = this.request();
  var buffer = this._buffer;
  var method = this.method;
  var timeout = this._timeout;
  debug('%s %s', this.method, this.url);

  // store callback
  this._callback = fn || noop;

  // querystring
  try {
    var querystring = qs.stringify(this.qs);
    req.path += querystring.length
      ? (~req.path.indexOf('?') ? '&' : '?') + querystring
      : '';
  } catch (e) {
    return this.callback(e);
  }

  // timeout
  if (timeout && !this._timer) {
    debug('timeout %sms %s %s', timeout, this.method, this.url);
    this._timer = setTimeout(function(){
      var err = new Error('timeout of ' + timeout + 'ms exceeded');
      err.timeout = timeout;
      self.abort();
      self.callback(err);
    }, timeout);
  }

  // body
  if ('HEAD' != method && !req._headerSent) {
    // serialize stuff
    if ('string' != typeof data) {
      var contentType = req.getHeader('Content-Type')
      // Parse out just the content type from the header (ignore the charset)
      if (contentType) contentType = contentType.split(';')[0]
      var serialize = exports.serialize[contentType];
      if (serialize) data = serialize(data);
    }

    // content-length
    if (data && !req.getHeader('Content-Length')) {
      this.set('Content-Length', Buffer.byteLength(data));
    }
  }

  // response
  req.on('response', function(res){
    debug('%s %s -> %s', self.method, self.url, res.statusCode);
    var max = self._maxRedirects;
    var mime = utils.type(res.headers['content-type'] || '');
    var len = res.headers['content-length'];
    var type = mime.split('/');
    var subtype = type[1];
    var type = type[0];
    var multipart = 'multipart' == type;
    var redirect = isRedirect(res.statusCode);
    var parser = self._parser

    if (self.piped) {
      res.on('end', function(){
        self.emit('end');
      });
      return;
    }

    // redirect
    if (redirect && self._redirects++ != max) {
      return self.redirect(res);
    }

    // zlib support
    if (/^(deflate|gzip)$/.test(res.headers['content-encoding'])) {
      utils.unzip(req, res);
    }

    // don't buffer multipart
    if (multipart) buffer = false;

    // TODO: make all parsers take callbacks
    if (!parser && multipart) {
      var form = new formidable.IncomingForm;

      form.parse(res, function(err, fields, files){


text:
//=============================================================================
/**
 *  @file   ButcherProjectMaskContainerSplit.h
 *
 *  $Id$
 *
 *  @author Rangel Reale <rreale@bol.com.br>
 *  @date   2008-02-05
 */
//=============================================================================

#include "ButcherProjectMaskContainerSplit.h"
#include "ButcherProjectMask.h"
#include "ButcherProjectLineDefault.h"
#include "ButcherProjectBaseAutoUpdate.h"
#include "ButcherFileDefs.h"

/////////////////////////////////
// CLASS
//      ButcherProjectMaskContainerSplit
/////////////////////////////////
ButcherProjectMaskContainerSplit::ButcherProjectMaskContainerSplit(ButcherProjectMask *mask,
    ButcherProjectArea::areaclass_t areaclass) :
    ButcherProjectMaskContainer(mask, areaclass)
{

}

ButcherProjectArea *ButcherProjectMaskContainerSplit::AddArea(long left, long top, long right, long bottom, BLID_t id)
{
	// prevent sending modified event until return
    ButcherProjectBaseAutoUpdate autoupdln(&lines_);
    ButcherProjectBaseAutoUpdate autoupdar(&areas_);

    ButcherProjectLine *line_left, *line_top, *line_right, *line_bottom;

    line_left   = lines_.Get(lines_.Add(new ButcherProjectLineDefault(this, NULL, NULL, ButcherProjectLine::BPL_VERTICAL, left)));
    line_top    = lines_.Get(lines_.Add(new ButcherProjectLineDefault(this, NULL, NULL, ButcherProjectLine::BPL_HORIZONTAL, top)));
    line_right  = lines_.Get(lines_.Add(new ButcherProjectLineDefault(this, NULL, NULL, ButcherProjectLine::BPL_VERTICAL, right)));
    line_bottom = lines_.Get(lines_.Add(new ButcherProjectLineDefault(this, NULL, NULL, ButcherProjectLine::BPL_HORIZONTAL, bottom)));

    line_left->start_ = line_right->start_ = line_top;
    line_left->end_ = line_right->end_ = line_bottom;

    line_top->start_ = line_bottom->start_ = line_left;
    line_top->end_ = line_bottom->end_ = line_right;

    ButcherProjectArea *area=new ButcherProjectArea(this, line_left, line_top, line_right, line_bottom);

    line_left->areas_after_.insert(area);
    line_top->areas_after_.insert(area);
    line_right->areas_before_.insert(area);
    line_bottom->areas_before_.insert(area);

    areas_.Add(area, id);

	// by default set area kind to NONE
	area->Configs().Get(ButcherProjectAreaConfigs::DEFAULT_CONFIG)->SetAreaKind(ButcherProjectAreaConfigBase::AK_NONE);

    return area;
}

void ButcherProjectMaskContainerSplit::DeleteArea(ButcherProjectArea *area)
{
    // prevent sending modified event until return
    ButcherProjectBaseAutoUpdate autoupdln(&lines_);
    ButcherProjectBaseAutoUpdate autoupdar(&areas_);

    lines_.Delete(area->GetLeft());
    lines_.Delete(area->GetTop());
    lines_.Delete(area->GetRight());
    lines_.Delete(area->GetBottom());

    areas_.Delete(area);
}

void ButcherProjectMaskContainerSplit::Clear()
{
    lines_.op_clear();
    areas_.op_clear();

    ProjectModified();
}

void ButcherProjectMaskContainerSplit::LoadMetadata(ButcherMetadataData *metadata)
{
    ButcherProjectBaseAutoUpdate autoupd(this);

    ButcherProjectMaskContainer::LoadMetadata(metadata);

    if (metadata->Exists(BFILE_MDI_AREAS) &&
        metadata->Get(BFILE_MDI_AREAS).GetMetadata().Exists(BFILE_MD_AREA))
        LoadMetadataAreas(&metadata->Get(BFILE_MDI_AREAS).GetMetadata().Get(BFILE_MD_AREA));
}

void ButcherProjectMaskContainerSplit::LoadMetadataAreas(ButcherMetadataDataList *metadatalist)
{
    ButcherMetadataData *metadata;
    ButcherProjectArea *area;
    for (unsigned long i=0; i<metadatalist->Count(); i++)
    {
        metadata=&metadatalist->Get(i);

        if ((!metadata->Exists(BFILE_MDI_ID, ButcherMetadataDataItem::DT_INTEGER)) ||
            (!metadata->Exists(BFILE_MDI_LEFT, ButcherMetadataDataItem::DT_INTEGER)) ||
            (!metadata->Exists(BFILE_MDI_TOP, ButcherMetadataDataItem::DT_INTEGER)) ||
            (!metadata->Exists(BFILE_MDI_RIGHT, ButcherMetadataDataItem::DT_INTEGER)) ||
            (!metadata->Exists(BFILE_MDI_BOTTOM, ButcherMetadataDataItem::DT_INTEGER)))
            throw ButcherException(_("Invalid metadata for area"));

        area=AddArea(
            metadata->Get(BFILE_MDI_LEFT).GetInteger(),
            metadata->Get(BFILE_MDI_TOP).GetInteger(),
            metadata->Get(BFILE_MDI_RIGHT).GetInteger(),
            metadata->Get(BFILE_MDI_BOTTOM).GetInteger(),
            metadata->Get(BFILE_MDI_ID).GetInteger());
        area->LoadMetadata(metadata);
    }
}

void ButcherProjectMaskContainerSplit::SaveMetadata(ButcherMetadataData *metadata)
{
    ButcherProjectMaskContainer::SaveMetadata(metadata);
    SaveMetadataAreas(&metadata->MultiAdd(new ButcherMetadataDataItem_Metadata(metadata, BFILE_MDI_AREAS))->Get(BFILE_MDI_AREAS).GetMetadata().Get(BFILE_MD_AREA, true));
}

void ButcherProjectMaskContainerSplit::SaveMetadataAreas(ButcherMetadataDataList *metadatalist)
{
    ButcherMetadataData *metadata;

	for (ButcherProjectAreas::iterator i=areas_.begin(); i!=areas_.end(); i++)
	{
        metadata=metadatalist->Add();

        metadata->
            MultiAdd(new ButcherMetadataDataItem_Integer(metadata, BFILE_MDI_ID, i->GetBLId()))->
            MultiAdd(new ButcherMetadataDataItem_Integer(metadata, BFILE_MDI_LEFT, i->GetLeft()->GetPosition()))->
            MultiAdd(new ButcherMetadataDataItem_Integer(metadata, BFILE_MDI_TOP, i->GetTop()->GetPosition()))->
            MultiAdd(new ButcherMetadataDataItem_Integer(metadata, BFILE_MDI_RIGHT, i->GetRight()->GetPosition()))->
            MultiAdd(new ButcherMetadataDataItem_Integer(metadata, BFILE_MDI_BOTTOM, i->GetBottom()->GetPosition()));
        i->SaveMetadata(metadata);
	}
}


text:
A vibrant, dark and obnoxiously awesome colour scheme for text editors and terminals.

Inspired by the syntax colours on [ImpactJS.com](http://www.impactjs.com). Everything in this repo is released under The MIT License; tweek, revise, publish, taste the rainbow.

# Supported Terminals & Editors #

* VIM (16 colour, 256 colour, and gVIM)
* iTerm2 (OSX)
* Coda (partial support)
* Konsole

## VIM ##

The VIM scheme uses a modified take on Al Budden's VIM colour scheme creation technique, seen in his [Bandit VIM scheme](https://sites.google.com/site/abudden/contents/Vim-Scripts/bandit-colour-scheme).

### Set Up ###

* Move ``acidcupcake.vim`` to your ``~/.vim/colors/`` directory.
* In your ``~/.vimrc`` file, add the following lines
<pre>
    syntax enable
    set background=dark
    colorscheme acidcupcake
</pre>

### Syntax Supported ###

Supported languages just have been tested with the colour scheme. Unsupported languages still have the colours, just no special care to what is coloured what.

* Javascript

## iTerm2
* Import dat preset

## Konsole ##

## Coda ##

Go to ``Coda > Preferences > Colors`` and go to ``import`` for any scheme you'd like. Made as a favour for a friend, not heavily tested!

### Syntax Supported ###

* ASP-HTML
* CSS
* Javascript
* HTML
* PHP-HTML

# To Do #

* More supported languages in VIM
* Upload Konsole scheme
* Upload images

# Author #

Jordan Santell [@jsantell](http://twitter.com/jsantell)


text:
`Boolean → Boolean → Boolean`

Fold on `Boolean`. `bool(x, y, c)` evaluates to `x` if `c` is `false` and to `y` otherwise.


text:
using CommandLine;

namespace LetsEncrypt.ACME.Simple
{
    class Options
    {
        [Option(Default = "https://acme-v01.api.letsencrypt.org/", HelpText = "The address of the ACME server to use.")]
        public string BaseUri { get; set; }

        [Option(HelpText = "Accept the terms of service.")]
        public bool AcceptTos { get; set; }

        [Option(HelpText = "Check for renewals.")]
        public bool Renew { get; set; }

        [Option(HelpText = "Overrides BaseUri setting to https://acme-staging.api.letsencrypt.org/")]
        public bool Test { get; set; }

        [Option(HelpText = "A host name to manually get a certificate for. --webroot must also be set.")]
        public string ManualHost { get; set; }

        [Option(Default = "%SystemDrive%\\inetpub\\wwwroot",
            HelpText = "A web root for the manual host name for authentication.")]
        public string WebRoot { get; set; }

        [Option(HelpText = "A script for installation of non IIS Plugin.")]
        public string Script { get; set; }

        [Option(HelpText = "Parameters for the script for installation of non IIS Plugin.")]
        public string ScriptParameters { get; set; }

        [Option(
            HelpText =
                "Path for Centralized Certificate Store (This enables Centralized SSL). Ex. \\\\storage\\central_ssl\\")
        ]
        public string CentralSslStore { get; set; }

        [Option(HelpText = "Hide sites that have existing HTTPS bindings")]
        public bool HideHttps { get; set; }

        [Option(HelpText = "Certificates per site instead of per host")]
        public bool San { get; set; }

        [Option(HelpText = "Keep existing HTTPS bindings, and certificates")]
        public bool KeepExisting { get; set; }
    }
}


text:
namespace password_manager {

namespace features {

// All features in alphabetical order. The features should be documented
// alongside the definition of their values in the .cc file.

extern const base::Feature kEnableAutomaticPasswordSaving;
extern const base::Feature kEnablePasswordChangeSupport;
extern const base::Feature kEnablePasswordForceSaving;

}  // namespace features

}  // namespace password_manager

#endif  // COMPONENTS_PASSWORD_MANAGER_CORE_COMMON_PASSWORD_MANAGER_FEATURES_H_


text:
require 'fog/rackspace/version'
require 'fog/core'
require 'fog/json'

require 'fog/rackspace/mock_data'
require 'fog/rackspace/service'
require 'fog/rackspace/errors'

module Fog
  module CDN
    autoload :Rackspace,  File.expand_path('../rackspace/cdn', __FILE__)
  end

  module Compute
    autoload :Rackspace, File.expand_path('../rackspace/compute', __FILE__)
    autoload :RackspaceV2, File.expand_path('../rackspace/compute_v2', __FILE__)
  end

  module DNS
    autoload :Rackspace, File.expand_path('../rackspace/dns', __FILE__)
  end

  module Storage
    autoload :Rackspace, File.expand_path('../rackspace/storage', __FILE__)
  end

  module Rackspace
    extend Fog::Provider

    US_AUTH_ENDPOINT = 'https://identity.api.rackspacecloud.com/v2.0' unless defined? US_AUTH_ENDPOINT
    UK_AUTH_ENDPOINT = 'https://lon.identity.api.rackspacecloud.com/v2.0' unless defined? UK_AUTH_ENDPOINT

    autoload :AutoScale, File.expand_path('../rackspace/auto_scale', __FILE__)
    autoload :BlockStorage, File.expand_path('../rackspace/block_storage', __FILE__)
    autoload :CDN, File.expand_path('../rackspace/cdn', __FILE__)
    autoload :CDNV2, File.expand_path('../rackspace/cdn_v2', __FILE__)
    autoload :Compute, File.expand_path('../rackspace/compute', __FILE__)
    autoload :ComputeV2, File.expand_path('../rackspace/compute_v2', __FILE__)
    autoload :Database, File.expand_path('../rackspace/databases', __FILE__)
    autoload :DNS, File.expand_path('../rackspace/dns', __FILE__)
    autoload :Identity, File.expand_path('../rackspace/identity', __FILE__)
    autoload :LoadBalancers, File.expand_path('../rackspace/load_balancers', __FILE__)
    autoload :Monitoring, File.expand_path('../rackspace/monitoring', __FILE__)
    autoload :Queues, File.expand_path('../rackspace/queues', __FILE__)
    autoload :Storage, File.expand_path('../rackspace/storage', __FILE__)
    autoload :Networking, File.expand_path('../rackspace/networking', __FILE__)
    autoload :Orchestration, File.expand_path('../rackspace/orchestration', __FILE__)
    autoload :NetworkingV2, File.expand_path('../rackspace/networking_v2', __FILE__)

    service(:auto_scale,       'AutoScale')
    service(:block_storage,    'BlockStorage')
    service(:cdn,              'CDN')
    service(:cdn_v2,           'CDN v2')
    service(:compute,          'Compute')
    service(:compute_v2,       'Compute v2')
    service(:dns,              'DNS')
    service(:storage,          'Storage')
    service(:load_balancers,   'LoadBalancers')
    service(:identity,         'Identity')
    service(:databases,        'Databases')
    service(:monitoring,       'Monitoring')
    service(:queues,           'Queues')
    service(:networking,       'Networking')
    service(:orchestration,    'Orchestration')
    service(:networkingV2,     'NetworkingV2')

    def self.authenticate(options, connection_options = {})
      rackspace_auth_url = options[:rackspace_auth_url]
      rackspace_auth_url ||= options[:rackspace_endpoint] == Fog::Compute::RackspaceV2::LON_ENDPOINT ? UK_AUTH_ENDPOINT : US_AUTH_ENDPOINT
      url = rackspace_auth_url.match(/^https?:/) ? \
                rackspace_auth_url : 'https://' + rackspace_auth_url
      uri = URI.parse(url)
      connection = Fog::Core::Connection.new(url, false, connection_options)
      @rackspace_api_key  = options[:rackspace_api_key]
      @rackspace_username = options[:rackspace_username]
      response = connection.request({
        :expects  => [200, 204],
        :headers  => {
          'X-Auth-Key'  => @rackspace_api_key,
          'X-Auth-User' => @rackspace_username
        },
        :method   => 'GET',
        :path     =>  (uri.path and not uri.path.empty?) ? uri.path : 'v1.0'
      })
      response.headers.reject do |key, value|
        !['X-Server-Management-Url', 'X-Storage-Url', 'X-CDN-Management-Url', 'X-Auth-Token'].include?(key)
      end
    end

    def self.json_response?(response)
      return false unless response && response.headers
      response.get_header('Content-Type') =~ %r{application/json}i ? true : false
    end

    def self.normalize_url(endpoint)
      return nil unless endpoint
      str = endpoint.chomp " "
      str = str.chomp "/"
      str.downcase
    end

    # CGI.escape, but without special treatment on spaces
    def self.escape(str,extra_exclude_chars = '')
      # '-' is a special character inside a regex class so it must be first or last.
      # Add extra excludes before the final '-' so it always remains trailing, otherwise
      # an unwanted range is created by mistake.
      str.gsub(/([^a-zA-Z0-9_.#{extra_exclude_chars}-]+)/) do
        '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  Copyright 2012 International Business Machines Corp.

  See the NOTICE file distributed with this work for additional information
  regarding copyright ownership. 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.
-->
<job id="job1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">

	<step id="step1">
		<properties>
			<property name="foo" value="bar"/>
			<property name="super" value="hero"/>
			<property name="me" value="too"/>
		</properties>
		<batchlet ref="stepLevelPropertiesPropertyValueBatchlet"/>
	</step>
</job>


text:
require File.expand_path("../../../../base", __FILE__)

require Vagrant.source_root.join("plugins/kernel_v2/config/vm")

describe Vagrant::Action::Builtin::HandleForwardedPortCollisions do
  include_context "unit"

  let(:app) { lambda { |env| } }
  let(:env) {
    { machine: machine, ui: ui, port_collision_extra_in_use: extra_in_use,
      port_collision_remap: collision_remap, port_collision_repair: collision_repair,
      port_collision_port_check: collision_port_check }
  }
  let(:extra_in_use){ nil }
  let(:collision_remap){ nil }
  let(:collision_repair){ nil }
  let(:collision_port_check){ nil }
  let(:port_check_method){ nil }

  let(:machine) do
    double("machine").tap do |machine|
      allow(machine).to receive(:config).and_return(machine_config)
      allow(machine).to receive(:env).and_return(machine_env)
    end
  end

  let(:machine_config) do
    double("machine_config").tap do |config|
      config.stub(vm: vm_config)
    end
  end

  let(:data_dir){ temporary_dir }

  let(:machine_env) do
    isolated_environment.tap do |i_env|
      allow(i_env).to receive(:data_dir).and_return(data_dir)
      allow(i_env).to receive(:lock).and_yield
    end
  end

  let(:vm_config) do
    double("machine_vm_config").tap do |config|
      allow(config).to receive(:usable_port_range).and_return(1000..2000)
      allow(config).to receive(:networks).and_return([])
    end
  end

  let(:ui) do
    double("ui").tap do |result|
      allow(result).to receive(:info)
    end
  end

  let(:instance){ described_class.new(app, env) }

  describe "#call" do
    it "should create a lock while action runs" do
      expect(machine_env).to receive(:lock).with("fpcollision").and_yield
      instance.call(env)
    end

    context "with extra ports in use provided as Array type" do
      let(:extra_in_use){ [80] }

      it "should not generate an error" do
        expect{ instance.call(env) }.not_to raise_error
      end
    end

    context "with forwarded port defined" do
      let(:port_options){ {guest: 80, host: 8080} }
      before do
        expect(vm_config).to receive(:networks).and_return([[:forwarded_port, port_options]]).twice
      end

      it "should check if host port is in use" do
        expect(instance).to receive(:is_forwarded_already).and_return false
        instance.call(env)
      end

      context "with forwarded port already in use" do
        let(:extra_in_use){ [8080] }

        it "should raise a port collision error" do
          expect{ instance.call(env) }.to raise_error(Vagrant::Errors::ForwardPortCollision)
        end

        context "with auto_correct enabled" do
          before{ port_options[:auto_correct] = true }

          it "should raise a port collision error" do
            expect{ instance.call(env) }.to raise_error(Vagrant::Errors::ForwardPortCollision)
          end

          context "with collision repair enabled" do
            let(:collision_repair){ true }

            it "should automatically correct collision" do
              expect{ instance.call(env) }.not_to raise_error
            end
          end
        end
      end

      context "with custom port_check method" do
        let(:check_result){ [] }
        let(:port_options){ {guest: 80, host: 8080, host_ip: "127.0.1.1"} }

        context "that accepts two parameters" do
          let(:collision_port_check) do
            lambda do |host_ip, host_port|
              check_result.push(host_ip)
              check_result.push(host_port)
              false
            end
          end

          it "should receive both host_ip and host_port" do
            instance.call(env)
            expect(check_result).to include(port_options[:host])
            expect(check_result).to include(port_options[:host_ip])
          end
        end

        context "that accepts one parameter" do
          let(:collision_port_check) do
            lambda do |host_port|
              check_result.push(host_port)
              false
            end
          end

          it "should receive the host_port only" do
            instance.call(env)
            expect(check_result).to eq([port_options[:host]])
          end
        end
      end
    end
  end

  describe "#recover" do
  end

  describe "#port_check" do
    let(:host_ip){ "127.0.0.1" }
    let(:host_port){ 8080 }

    it "should check if the port is open" do
      expect(instance).to receive(:is_port_open?).with(host_ip, host_port).and_return true
      instance.send(:port_check, host_ip, host_port)
    end

    context "when host_ip is not set" do
      let(:host_ip){ nil }

      it "should set host_ip to 0.0.0.0 when unset" do
        expect(instance).to receive(:is_port_open?).with("0.0.0.0", host_port).and_return true
        instance.send(:port_check, host_ip, host_port)
      end

      it "should set host_ip to 127.0.0.1 when 0.0.0.0 is not available" do
        expect(instance).to receive(:is_port_open?).with("0.0.0.0", host_port).and_raise Errno::EADDRNOTAVAIL
        expect(instance).to receive(:is_port_open?).with("127.0.0.1", host_port).and_return true
        instance.send(:port_check, host_ip, host_port)
      end
    end
  end
end