text:
from src.core.utils import Vector2
from random import random

def randscalar():
    # between -5 and 5
    return -5 + 10 * random()

def randtuple():
    return (randscalar(), randscalar())

def randvec():
    return Vector2(randscalar(), randscalar())

def repeat(times=10):
    def decorate(test_func):
        def new_test_func(*args, **kwargs):
            for _ in range(times):
                test_func(*args, **kwargs)
        return new_test_func
    return decorate


text:
package org.dartlang.analysis.server.protocol;

/**
 * An enumeration of the services provided by the server domain.
 *
 * @coverage dart.server.generated.types
 */
public class ServerService {

  public static final String LOG = "LOG";

  public static final String STATUS = "STATUS";

}

redpajama_set_name: RedPajamaGithub


text:
import threading

class SingletonMetaclass(type):
    """Singleton Metaclass.

    This metaclass is used for creating singletons.
    It changes the class __new__ method to maintain only one instance of the
    class, and tweaks the __init__ method to be executed only once (when the
    first instance of the class is created.

    Usage::

        >>> class MySingleton(object, metaclass=SingletonMetaclass):
        ...     '''Real singleton class.
        ...
        ...     You have to set the metaclass to SingletonMetaclass,
        ...     and define the __init__ function. Everything else will
        ...     be done by metaclass.
        ...     '''
        ...     def __init__(self, data):
        ...         print("Initializing")
        ...         self.data = data
        ...
        >>> # Only this actually happen
        >>> first = MySingleton("First initialization")
        Initializing
        >>> second = MySingleton("Second initialization") # This won't happen
        >>> first.data
        'First initialization'
        >>> second.data
        'First initialization'
    """

    def __init__(cls, *args, **kwargs):
        super(SingletonMetaclass, cls).__init__(*args, **kwargs)
        cls._instance = None
        cls._lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(SingletonMetaclass, cls).__call__(
                    *args, **kwargs
                )
            return cls._instance

    @property
    def instance(cls):
        with cls._lock:
            return cls._instance

class Singleton(metaclass=SingletonMetaclass):
    """Singleton class.

    Inherit from this class if you want to have a singleton class.

    Never use SingletonMetaclass!

    Usage::

        >>> class EmptySingleton(Singleton):
        ...     '''Singleton without __init__ method'''
        ...     pass
        ...
        >>> first = EmptySingleton()
        >>> second = EmptySingleton()
        >>> assert id(first) == id(second)
        >>>
        >>> class InitSingleton(Singleton):
        ...     '''Singleton with __init__ method'''
        ...     def __init__(self, data):
        ...         print("Initializing")
        ...         self.data = data
        ...
        >>> # Only this actually happen
        >>> first = InitSingleton("First initialization")
        Initializing
        >>> second = InitSingleton("Second initialization") # This won't happen
        >>> first.data
        'First initialization'
        >>> assert first.data == second.data
    """

    pass


text:
package org.apache.commons.jcs.yajcache.beans;

import org.apache.commons.jcs.yajcache.lang.annotation.*;
import org.apache.commons.jcs.yajcache.core.ICache;
/**
 *
 * @author Hanson Char
 */
@CopyRightApache
public class CachePutEvent<V> extends CacheChangeEvent<V> {
    private final @NonNullable String key;
    private final @NonNullable V value;

    public CachePutEvent(@NonNullable ICache<V> cache,
            @NonNullable String key, @NonNullable V value)
    {
        super(cache);
        this.key = key;
        this.value = value;
    }
    public @NonNullable String getKey() {
        return key;
    }
    public @NonNullable V getValue() {
        return value;
    }

    @Override
    public boolean dispatch(@NonNullable ICacheChangeHandler<V> handler) {
        return handler.handlePut(
                super.getCache().getName(), this.key, this.value);
    }
}


text:
import Q = require('q');
import assert = require('assert');
import trm = require('../../lib/taskRunner');
import psm = require('../../lib/psRunner');
import path = require('path');
import os = require('os');
import mockHelper = require('../../lib/mockHelper');
import fs = require('fs');
import shell = require('shelljs');
import uuid = require('node-uuid');
var ps = shell.which('powershell.exe');
var psr = null;
const tmpFileName = path.join(os.tmpdir(), uuid.v1() + ".json");
const testDllPath = path.join(__dirname, "data", "testDlls");
const sysVstestLocation = "\\vs\\IDE\\CommonExtensions\\Microsoft\\TestWindow\\vstest.console.exe";

function setResponseFile(name: string, vstestCmd?: string, isPass?: boolean) {
    let fileName = path.join(__dirname, name);
    if (typeof vstestCmd !== "undefined") {
        if (typeof isPass === "undefined") {
            isPass = true;
        }
        let fileContent: string = fs.readFileSync(fileName, 'utf8');
        let fileJson = JSON.parse(fileContent);
        let errCode: number = isPass ? 0 : 1;
        let stdErr: string = isPass ? "" : "Error string";

        fileJson.exec[vstestCmd] = { "code": errCode, "stdout": "vstest", "stderr": stdErr };
        fs.writeFileSync(tmpFileName, JSON.stringify(fileJson));
        fileName = tmpFileName;
    }
    process.env['MOCK_RESPONSES'] = fileName;
}

function posixFormat(p: string): string {
    let path_regex = /\/\//;
    p = p.replace(/\\/g, '/');
    while (p.match(path_regex)) {
        p = p.replace(path_regex, '/');
    }
    return p;
}

function getTestDllString(testDlls: string[]): string {
    let dllString: string = "";
    testDlls.forEach(function (part, index) {
        testDlls[index] = posixFormat(path.join(testDllPath, testDlls[index]));
    });
    return testDlls.join(" ");
}

describe('VsTest Suite', function () {
    this.timeout(20000);

    before((done) => {
        if (ps) {
            psr = new psm.PSRunner();
            psr.start();
        }

        done();
    });

    after(function () {
        psr.kill();
        fs.unlink(tmpFileName, function (err) {
            if (err) {
                console.log("Error encountered deleting temp file: " + err);
            }
        });
    });

    if (ps) {
        it('(VsTest-NoTestAssemblies) throws if no test assemblies provided as input', (done) => {
            psr.run(path.join(__dirname, 'ThrowsIfAssembliesNotProvided.ps1'), done);
        })
        it('(VsTest-NoSourceDirectory) throws if no source directory is found', (done) => {
            psr.run(path.join(__dirname, 'ThrowsIfNoSourceDirectoryFound.ps1'), done);
        })
        it('(2015U1Check.ReturnsTrueIfTaefFileIsFound) returns true if taef file is found', (done) => {
            psr.run(path.join(__dirname, '2015U1Check.ReturnsTrueIfTaefFileIsFound.ps1'), done);
        })
        it('(2015U1Check.ReturnsFalseForOlderVSTestVersion.ps1) returns false if vstest version less than 14', (done) => {
            psr.run(path.join(__dirname, '2015U1Check.ReturnsFalseForOlderVSTestVersion.ps1'), done);
        })
        it('(2015U1Check.ReturnsTrueForLaterVSTestVersion) returns true if vstest version greater than 14', (done) => {
            psr.run(path.join(__dirname, '2015U1Check.ReturnsTrueForLaterVSTestVersion.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsSameFileIfParallelIsFalse) returns same file if parallel flag is false', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsSameFileIfParallelIsFalse.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameEmpty) returns new file if parallel flag is true and no runsettings file is provided', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameEmpty.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsSameFileIfParallelIsTrueAndFileNameNotEmpty) returns same but updated file if parallel flag is true and a runsettings file is provided', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsSameFileIfParallelIsTrueAndFileNameNotEmpty.ps1'), done);
        })
        it('(NoResultsFile.PrintsWarning) prints a warning if no results file is found', (done) => {
            psr.run(path.join(__dirname, 'NoResultsFile.PrintsWarning.ps1'), done);
        })
        it('(NoTestAssemblies.PrintsWarning) prints a warning if no test assemblies are found', (done) => {
            psr.run(path.join(__dirname, 'NoTestAssemblies.PrintsWarning.ps1'), done);
        })
        it('(Compat.OptOutOfPublishNotInCmdlet.ProvidedByTask) does not throw if publishattachments is not found in the cmdlet', (done) => {
            psr.run(path.join(__dirname, 'Compat.OptOutOfPublishNotInCmdlet.ProvidedByTask.ps1'), done);
        })
        it('(Compat.TestRunTitleNotInCmdlet.ProvidedByTask) does not throw if testrun title is not found in the cmdlet', (done) => {
            psr.run(path.join(__dirname, 'Compat.TestRunTitleNotInCmdlet.ProvidedByTask.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameIsADirectory) returns new file if parallel flag is true and runsettings input is a directory', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameIsADirectory.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameIsANonRunsettingsNonTestSettingsFile) returns new file if parallel flag is true and runsettings input is not a runsettings or testsettings file', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsNewFileIfParallelIsTrueAndFileNameIsANonRunsettingsNonTestSettingsFile.ps1'), done);
        })
        it('ValidateTestAssembliesAreSplit) tests if the input test assembiles are properly passed to cmdlet', (done) => {
            psr.run(path.join(__dirname, 'ValidateTestAssembliesAreSplit.ps1'), done);
        })
        it('ValidateTestAssembliesAreSplit) tests if the input test assembiles are properly passed to cmdlet', (done) => {
            psr.run(path.join(__dirname, 'ValidateTestAssembliesAreNotSplit.ps1'), done);
        })
        it('(RunSettingsForParallel.ReturnsSameFileIfParallelIsTrueAndFileNameIsTestSettingsFile) returns same file if parallel flag is true and runsettings input is a testsettings file', (done) => {
            psr.run(path.join(__dirname, 'RunSettingsForParallel.ReturnsSameFileIfParallelIsTrueAndFileNameIsTestSettingsFile.ps1'), done);
        })

        it('(GetResultsLocationReturnsPathFromRunsettings) returns the custom results location from runsettings', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsPathFromRunsettings.ps1'), done);
        })

        it('(GetResultsLocationReturnsPathFromRunsettingsForRelativePaths) returns the custom results location from runsettings for relative paths', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsPathFromRunsettingsForRelativePaths.ps1'), done);
        })

        it('(GetResultsLocationReturnsNullForRunsettingsWithoutResultsDirectory) returns null if there is no results location in runsettings', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsNullForRunsettingsWithoutResultsDirectory.ps1'), done);
        })

        it('(GetResultsLocationReturnsPathForTmpFile) returns the custom results location for tmp file extension', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsPathForTmpFile.ps1'), done);
        })

        it('(GetResultsReturnsNullForTestsettings) returns null for any other file type', (done) => {
            psr.run(path.join(__dirname, 'GetResultsReturnsNullForTestsettings.ps1'), done);
        })

        it('(GetResultsLocationReturnsNullForDirectory) returns the null for directory specified as runsettings', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsNullForDirectory.ps1'), done);
        })

        it('(GetResultsLocationReturnsNullForEmptyPath) returns null for empty directory specified as runsettings', (done) => {
            psr.run(path.join(__dirname, 'GetResultsLocationReturnsNullForEmptyPath.ps1'), done);
        })

        it('(TestResultsDirectoryVariableIsUsedIfnorunsettings) vstest invoked with  default test results directory if no settings is specified', (done) => {
            psr.run(path.join(__dirname, 'TestResultsDirectoryVariableIsUsedIfnorunsettings.ps1'), done);
        })

        it('(TestResultsDirectoryVariableIsUsedIfOverrideParamsAreUsed) vstest invoked with  default test results directory if override run parameters is used', (done) => {
            psr.run(path.join(__dirname, 'TestResultsDirectoryVariableIsUsedIfOverrideParamsAreUsed.ps1'), done);
        })

        it('Latest option chosen with VS 15 Willow installed', (done) => {
            psr.run(path.join(__dirname, 'LatestSelectedwithVS15Installed.ps1'), done);
        })

        it('v14 option chosen with VS 15 Willow installed', (done) => {
            psr.run(path.join(__dirname, 'V14SelectedwithVS15Installed.ps1'), done);
        })
    }

    if (!os.type().match(/^Win/)) {
        console.log("Skipping vstest tests. Vstest tests run only on windows.")
        return;
    }
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.cloud.core.implementation.credential.descriptor;

import com.azure.core.credential.AzureSasCredential;
import com.azure.spring.cloud.core.credential.AzureCredentialResolver;
import com.azure.spring.cloud.core.implementation.credential.resolver.AzureSasCredentialResolver;

import java.util.function.Consumer;

/**
 * A descriptor describes the SAS authentication.
 */
public final class SasAuthenticationDescriptor implements AuthenticationDescriptor<AzureSasCredential> {

    private final Consumer<AzureSasCredential> consumer;

    /**
     * Create a {@link SasAuthenticationDescriptor} instance with the consumer to consume the resolved credential.
     * @param consumer The consumer to consume the resolved credential.
     */
    public SasAuthenticationDescriptor(Consumer<AzureSasCredential> consumer) {
        this.consumer = consumer;
    }

    @Override
    public Class<AzureSasCredential> getAzureCredentialType() {
        return AzureSasCredential.class;
    }

    @Override
    public AzureCredentialResolver<AzureSasCredential> getAzureCredentialResolver() {
        return new AzureSasCredentialResolver();
    }

    @Override
    public Consumer<AzureSasCredential> getConsumer() {
        return consumer;
    }
}


text:
class InfoBarService;

class ProtectedMediaIdentifierInfoBarDelegateAndroid
    : public PermissionInfobarDelegate {
 public:
  // Creates a protected media identifier infobar and delegate and adds the
  // infobar to |infobar_service|.  Returns the infobar if it was successfully
  // added.
  static infobars::InfoBar* Create(InfoBarService* infobar_service,
                                   const GURL& requesting_frame,
                                   const std::string& display_languages,
                                   const PermissionSetCallback& callback);

 protected:
  ProtectedMediaIdentifierInfoBarDelegateAndroid(
      const GURL& requesting_frame,
      const std::string& display_languages,
      const PermissionSetCallback& callback);
  ~ProtectedMediaIdentifierInfoBarDelegateAndroid() override;

 private:
  // ConfirmInfoBarDelegate:
  int GetIconId() const override;
  base::string16 GetMessageText() const override;
  base::string16 GetLinkText() const override;
  GURL GetLinkURL() const override;

  GURL requesting_frame_;
  std::string display_languages_;

  DISALLOW_COPY_AND_ASSIGN(ProtectedMediaIdentifierInfoBarDelegateAndroid);
};

#endif  // CHROME_BROWSER_MEDIA_PROTECTED_MEDIA_IDENTIFIER_INFOBAR_DELEGATE_ANDROID_H_


text:
from django.contrib import admin

from geocoder.models import Zipcode

class ZipcodeAdmin(admin.ModelAdmin):

    list_display = ('postal_code', 'place_name', 'admin_name1', 'latitude', 'longitude')
    search_fields = ('postal_code',)

admin.site.register(Zipcode, ZipcodeAdmin)


text:
const Repeat = require("./repeat");
const strftime = require("strftime");

class Clock extends Repeat {
    constructor(format) {
        super(1000);
        this.format = format;
    }

    update() {
        this.setText(strftime(this.format, new Date()));
    }
}

module.exports = Clock;


text:
export default class CollaboratorListController {
  constructor($scope, CollaboratorService) {
    this.$scope = $scope;
    this.$scope.tournamentId = this.$scope.$parent.tournamentId;
    this.$scope.toast = this.$scope.$parent.toast;
    this.CollaboratorService = CollaboratorService;
    this.collaborators = this.CollaboratorService.collaborators;

    this.CollaboratorService.getCollaborators(this.$scope.tournamentId);
  }

  toggleAdmin(collaborator) {
    this.CollaboratorService.toggleCollaboratorPermissions(this.$scope.tournamentId, collaborator)
      .catch(() => {
        this.$scope.toast({
          message: `Could not update ${collaborator.username}'s permissions.`,
          success: false,
        });
      });
  }

  removeCollaborator(username) {
    this.CollaboratorService.removeCollaborator(this.$scope.tournamentId, username)
      .catch(() => {
        this.$scope.toast({
          message: `Could not remove ${username} from the tournament.`,
          success: false,
        });
      });
  }
}

CollaboratorListController.$inject = ['$scope', 'CollaboratorService'];


text:
var provinceModel = __MODEL.Province,
    cityModel = __MODEL.City,
    areaModel = __MODEL.Area,
    menuModel = __MODEL.Menu,
    userModel = __MODEL.User,
    customerModel = __MODEL.Customer,
    roleModel = __MODEL.Role,
    paramsModel = __MODEL.Params,
    orderModel = __MODEL.Order,
    msgModel = __MODEL.Msg,
    async = require('async'),
    qs = require('querystring'),
    formidable = require('formidable'),
    excel = require('node-xlsx'),
    http = require('http'),
    msg = require("../../other/msg"),
    config = require("../../other/config"),
    then = require("thenjs"),
    fs=require('fs'),
    crypto = require('crypto');

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodemailer.createTransport(smtpTransport({
    host: 'smtp.exmail.qq.com',
    port: 25,
    auth: {
        user: 'service@brother-express.com',
        pass: 'brother2015'
    }
}));

exports.checkCustomer = function(req, res) {
    var customer = {
        loginId: req.body.loginId
    };

    customerModel.findOne(customer).exec(function(err, doc) {
        if (err) {
            __logger.error("用户校验失败[" + err.message + "]")
            res.status(400).send(err.message);
            return;
        }
        if (doc) {
            res.status(400).send(msg.USER.loginIdExist);
            return;
        }
        res.json("success");
    });
}

exports.addCustomer = function(req, res) {
    then(function (cont) {
        var customer = {
            loginId: req.body.loginId
        };
        __logger.info("又一个土豪来注册了,注册邮箱[" + customer.loginId + "]")

        customerModel.findOne(customer).exec(function(err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            if (doc) {
                cont(new Error(msg.USER.loginIdExist));
                return;
            }
            cont(null, doc);
        });
    }).then(function(cont, doc) {
        paramsModel.findOne({paramsId:'0B001'}).exec(function (err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            cont(null, doc);
        });
    }).then(function(cont, doc){
        var customer = new customerModel({
            loginId: req.body.loginId,
            nickname: req.body.nickname,
            name: req.body.name,
            password: req.body.password,
            img: req.body.img,
            idNoImgA: req.body.idNoImgA,
            idNoImgB: req.body.idNoImgB,
            sex: req.body.sex,
            idNo: req.body.idNo,
            birthday: req.body.birthday,
            zipCode: req.body.zipCode||"",
            phone: req.body.phone,
            address: req.body.address,
            status: req.body.status||1,
            balance: doc.paramsValue||0
        });

        customer.save(function (err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            cont(null, doc);
        });
    }).then(function(cont, doc) {
        customerModel.findOne(doc).exec(function(err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            __logger.info("土豪注册成功了,撒花欢迎[" + doc.loginId + "]")
            res.json(doc);
        });
    }).fail(function (cont, error) {
        __logger.error("又一个土豪[" + req.body.loginId + "]注册失败了[" + error.message + "]")
        res.status(400).send(error.message);
    });

};

exports.upload = function (req, res) {
    var form = new formidable.IncomingForm();

    var type = req.query.type;
    var fileName = req.query.file;
    form.uploadDir = config.basic.UPLOAD_PATH;
    form.keepExtensions = true;
    form.maxFieldsSize = 20 * 1024 * 1024;

    form.on('progress', function(bytesReceived, bytesExpected ,ending){
        if(bytesReceived > form.maxFieldsSize){
            req.socket.destroy();
        }
    });

    form.parse(req, function(err, fields, files) {
        var newPath;
        if(fileName!=undefined){
            if(type==1){    //若为身份证上传
                newPath = config.basic.UPLOAD_IDNO_PATH + fileName + ".jpg";
            }else if(type==2){  //若为批量订单上传
                newPath = config.basic.UPLOAD_PATH + fileName + ".xlsx";
            }
            if(files.file && files.file.path){
                fs.rename(files.file.path, newPath, function(err){
                    if(!err){
                        files.file.path = newPath;
                        __logger.info("文件上传成功:" + newPath);
                        res.json(files);
                    }else{
                        __logger.error("文件上传失败:" + err);
                        res.status(400).send(err.message);
                    }
                });
            }else{
                __logger.error("文件上传失败:" + err);
                res.status(400).send("文件上传失败");
            }
        }
    });
}

exports.listMenus = function (req, res) {
    menuModel.find({level: '0'}).populate('subMenu').exec(function (err, doc) {
        if (err) {
            __logger.error("我去,拉个菜单列表都能失败,不想活了[" + err.message + "]")
            res.status(400).send(err.message);
            return;
        }
        res.json(doc);
    });
};

exports.listManagerMenus = function (req, res) {
    if(req.session.user){
        roleModel.findById(req.session.user.role._id).exec(function (err, doc) {
            if (err) {
                __logger.error("我去,拉个菜单列表都能失败,不想活了[" + err.message + "]")
                res.status(400).send(err.message);
                return;
            }
            res.json(doc.menu);
        });
    }else{
        __REST.fail(res, new Error("登录状态已失效,请重新登录后操作"))
    }
};

exports.queryOrder = function (req, res) {
    var id = req.body.id
    var order = {id : id}
    var random = Math.floor(Math.random() * 1000)
    __logger.info("某个土豪(" + random + ")又开始查询订单啦,订单编号[" + order.id + "]")

    //2016.04.13 增加多笔订单查询
    var CHAR_SPLIT = ','

    var orders = []
    if(id.indexOf(CHAR_SPLIT) != -1){
        orders = id.split(CHAR_SPLIT)
    }

    if(orders.length > 0){
        orderModel.find({id:{$in:orders}}).exec(function(err, doc) {
            if (err) {
                __logger.error("这丫的(" + random + ")批量订单查询失败[" + err.message + "]")
                res.status(400).send(err.message);
                return;
            }
            if (!doc){
                res.status(400).send(msg.ORDER.orderIdNotExist);
                return;
            }
            res.json(doc);
        });
    }else{
        orderModel.findOne(order).exec(function(err, doc) {
            if (err) {
                __logger.error("这丫的(" + random + ")订单查询失败[" + err.message + "]")
                res.status(400).send(err.message);
                return;
            }
            if (!doc){
                res.status(400).send(msg.ORDER.orderIdNotExist);
                return;
            }
            res.json(doc);
        });
    }

};

//深圳清关轨迹查询
exports.thirdPath = function(req, res) {

    var data = {
        cno: req.body.orderId,   //610291500140161
        cp: "65001"
    };

    var content = qs.stringify(data);

    var options = {
        hostname: config.basic.EXPRESS_API_HOST,
        port: config.basic.EXPRESS_API_PORT,
        path: config.basic.EXPRESS_API_PATH + req.body.orderId,
        method: config.basic.EXPRESS_API_METHOD
    };

    var body = "";

    var request = http.request(options, function (response) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            body+=chunk;
        }).on('end', function(){
            console.log(body)
            res.send(body);
        });
    }).on('error', function (err) {
        __logger.error("注意啦!清关接口又调用失败啦,什么破系统[" + err.message + "]")
        res.status(400).json(msg.ORDER.orderPathSyncError);
    })

    request.end();
};

//天津宜信清关轨迹查询
exports.thirdTJPath = function(req, res) {

    var data = {
        no: req.body.orderId,   //610291500140161
        //cc: "zhongliang"
        cc:"ZHONGLIANG"
    };

    var content = qs.stringify(data);

    var options = {
        hostname: config.basic.EXPRESS_TJ_API_HOST,
        port: config.basic.EXPRESS_TJ_API_PORT,
        path: config.basic.EXPRESS_TJ_API_PATH + content,
        method: config.basic.EXPRESS_TJ_API_METHOD
    };

    var body = "";

    var request = http.request(options, function (response) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            body+=chunk;
        }).on('end', function(){
            res.send(body);
        });
    }).on('error', function (err) {
        __logger.error("注意啦!天津宜信清关接口又调用失败啦,什么破系统[" + err.message + "]")
        res.status(400).json(msg.ORDER.orderPathSyncError);
    })

    request.end();
};

/**
 * 全轨迹查询,包括第三方清关轨迹
 * @param req
 * @param res
 */
exports.fullPath = function(req, res) {

    var order = {id : req.body.id}

    then(function(cont){
        //TODO 增加关联查询
        orderModel.findOne(order, {updateInfo: 1}).exec(function(err, doc) {
            if (!doc){
                cont(new Error(msg.ORDER.orderIdNotExist));
            }else{
                cont(err, doc.updateInfo);
            }
        })
    }).then(function(cont, globalPath){
        var data = {
            cno: req.body.id,   //610291500140161
            cp: "65001"
        };

        var content = qs.stringify(data);

        var options = {
            hostname: config.basic.EXPRESS_API_HOST,
            port: config.basic.EXPRESS_API_PORT,
            path: config.basic.EXPRESS_API_PATH + content,
            method: config.basic.EXPRESS_API_METHOD
        };

        var body = "";
        var request = http.request(options, function (response) {
            response.setEncoding('utf8');
            response.on('data', function (chunk) {
                body+=chunk;
            }).on('end', function(){
                var data = JSON.parse(body)
                var localPath = [];
                if(data.trackingEventList){
                    data.trackingEventList.forEach(function(each){
                        var node = {};
                        node.time = each.date;
                        node.gisText = each.place;
                        node.status = "";
                        node.remark = each.details;
                        localPath.push(node);
                    })
                }
                var path = globalPath.concat(localPath);
                cont(null, path)
            });
        }).on('error', function (err) {
            __logger.error("注意啦!清关接口又调用失败啦,什么破系统[" + err.message + "]")
            cont(new Error(msg.ORDER.orderPathSyncError));
        })
        request.end();
    }).then(function(cont, path){
        res.send(path);
    }).fail(function (cont, error) {
        res.status(400).send(error);
    });
};

exports.listSettings = function(req, res) {
    var queryString = {};
    if(req.body.paramsGroup){
        queryString.paramsGroup = req.body.paramsGroup
    }

    paramsModel.find(queryString).exec(function (err, doc) {
        if (err) {
            res.status(400).send(err.message);
            return;
        }
        res.json(doc);
    });
}

exports.getSettings = function(req, res) {
    var queryString = {};
    if(req.body.paramsId){
        queryString.paramsId = req.body.paramsId
    }

    paramsModel.findOne(queryString).exec(function (err, doc) {
        if (err) {
            res.status(400).send(err.message);
            return;
        }
        res.json(doc);
    });
}

exports.updateSettings = function(req, res) {
    var settings = [];
    if(req.body.settings){
        settings = req.body.settings;
    }

    var random = Math.floor(Math.random() * 1000)
    __logger.info("某个高层人员(" + random + ")开始更新参数配置")
    async.eachSeries(settings, function(param, callback) {
        var queryString = {paramsId: param.paramsId};
        var updateString = {
            paramsName: param.paramsName,
            paramsValue: param.paramsValue
        }
        paramsModel.update(queryString, updateString).exec(function (err, doc) {
            callback(err, doc);
        });
    },function(err, result){
        // if any of the file processing produced an error, err would equal that error
        if( err ) {
            __logger.error("某个高层人员(" + random + ")更新参数配置失败了[" + err.message + "]")
            res.status(400).send(err.message);
        }else{
            res.json("success")
        }
    });
}

//游客新建订单
exports.createOrder = function (req, res) {
    var random = Math.floor(Math.random() * 1000)
    then(function (cont) {
        var order = {
            id: req.body.id
        };
        __logger.info("某个注册都懒得做的家伙(" + random + ")开始下单了,订单编号[" + order.id + "]")

        orderModel.findOne(order).exec(function(err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            if (doc) {
                cont(new Error(msg.ORDER.orderIdExist));
                return;
            }
            cont(null, doc);
        });
    }).then(function(cont, doc) {
        var order = new orderModel({
            id: req.body.id,
            type: 3,                //游客订单
            payStatus: 0,                //未支付
            amount: req.body.amount,
            name: req.body.name,
            creater: req.body.creater,
            gateMode: req.body.gateMode || 0,
            idNoImgA: req.body.idAUrl || "",
            idNoImgB: req.body.idBUrl || "",
            worldTransId:  req.body.worldTransId,
            worldTransName:  req.body.worldTransName,
            chinaTransId:  req.body.chinaTransId,
            chinaTransName:  req.body.chinaTransName,
            payerName: req.body.payerName,
            payerPhone: req.body.payerPhone,
            payerIdType: req.body.payerIdType,
            payerIdNo: req.body.payerIdNo,
            payerAddress: req.body.payerAddress,
            payerZipCode: req.body.payerZipCode,
            sendName: req.body.sendName,
            sendAddress: req.body.sendAddress,
            sendPhone: req.body.sendPhone,
            receiveName: req.body.receiveName,
            receiveProvince: req.body.receiveProvince,
            receiveProvinceName: req.body.receiveProvinceName||"",
            receiveCity: req.body.receiveCity,
            receiveCityName: req.body.receiveCityName,
            receiveAddress: req.body.receiveAddress,
            receivePhone: req.body.receivePhone,
            receiveZipCode: req.body.receiveZipCode,
            productName: req.body.productName,
            productNum: req.body.productNum,
            productAmount: req.body.productAmount,
            productWeight: req.body.productWeight,
            products: req.body.products,
            transportAmount: req.body.transportAmount,
            taxAmount: req.body.taxAmount,
            safeAmount: req.body.safeAmount,
            otherAmount: req.body.otherAmount,
            isFixed: req.body.isFixed||0,
            isFast: req.body.isFast||0,
            isProtected: req.body.isProtected||0,
            flagBox: req.body.flagBox||0,
            flagDetailProduct: req.body.flagDetailProduct||0,
            flagElec: req.body.flagElec||0,
            flagRemovePages: req.body.flagRemovePages||0,
            flagReturnProduct: req.body.flagReturnProduct||0,
            flagStore: req.body.flagStore||0
        });

        order.save(function (err, doc) {
            if (err) {
                cont(new Error(err));
                return;
            }
            cont(null, doc);
        });
    }).then(function(cont, doc) {
        __logger.info("某个注册都懒得做的家伙(" + random + ")下单成功")
        res.json("success");
    }).fail(function (cont, error) {
        __logger.error("某个注册都懒得做的家伙(" + random + ")果然下单失败了[" + error.message + "]")
        res.status(400).send(error.message);
    });

};

//上传证件照
exports.updateOrderIdno = function(req, res) {
    var _id = req.body.id;
    var orderId = req.body.orderId;
    var idA = req.body.idAUrl;
    var idB = req.body.idBUrl;

    __logger.info("(" + orderId + ")订单的主人/非主人正在更新证件照")

    then(function (cont) {
        orderModel.findByIdAndUpdate(_id, {idNoImgA:idA, idNoImgB:idB}, null, function(err, doc){
            if (err) {
                cont(new Error(msg.ORDER.orderUpdateFail));
                return;
            }
            __logger.info("(" + orderId + ")订单更新证件照成功")
            res.json("success");
        })
    }).fail(function (cont, error) {
        __logger.error("(" + orderId + ")订单更新证件照失败,错误信息[" + error.message + "]")
        res.status(400).send(error.message);
    })
};

//微信、外部渠道更新订单信息
exports.updateOrder = function(req, res) {
    var loginId = req.body.loginId;
    var orderId = req.body.orderId; //db id
    var status = req.body.status;

    __logger.info("咱们的人(" + loginId + ")开始更新订单信息,订单编号[" + orderId + "]")

    then(function (cont) {
        if(!loginId){
            cont(new Error(msg.USER.loginIdErr));
            return;
        }
        userModel.findOne({loginId: loginId, status: 1}).exec(function(err, doc){
            if(err || !doc){
                cont(new Error(msg.USER.userNone));
                return;
            }
            cont(err, doc);
        });
    }).then(function(cont, user){
        orderModel.findByIdAndUpdate(orderId, {status:status}, null, function(err, doc){
            if (err) {
                cont(new Error(msg.ORDER.orderUpdateFail));
                return;
            }
            cont(err, user);
        })
    }).then(function(cont, user){
        var updater = {
            updater: loginId,
            gis: req.body.gis||"",
            gisText: req.body.gisText||"",
            status: status,
            remark: req.body.remark||""
        }

        orderModel.update({_id: orderId}, {'$addToSet':{updateInfo:updater}}, function (err, doc) {
            if (err) {
                cont(new Error(msg.ORDER.orderUpdateFail));
                return;
            }
            __logger.info("咱们的人(" + loginId + ")更新订单信息成功,订单编号[" + orderId + "]")
            res.json("success");
        })
    }).fail(function (cont, error) {
        __logger.error("咱们的人(" + loginId + ")更新订单信息失败,订单编号[" + orderId + "],错误信息[" + error.message + "]")
        res.status(400).send(error.message);
    })
};

/*{
    from: 'zhanghuan@annlover.com',
        to: 'm13818239270@163.com',
    subject: 'hello',
    text: 'hello world!'
}*/
exports.sendMail = function(req, res){
    var toEmail = req.body.loginId;
    var token = Math.ceil(Math.random()*10000000);
    req.session.token = token;

    html = "
您好:
 " +
    "
我们收到您在仲良速递的注册申请,请点击下面的链接激活帐户:
" +
    "" + "请点击本链接激活帐号"

    var mail = {
        from: '仲良速递<service@brother-express.com>',
        to: toEmail,
        subject: '仲良速递注册验证',
        html: html
    }
    transporter.sendMail(mail, function(err, info){
        if(err){
            __logger.error("账号注册邮件(" + toEmail + "),随机数(" + token + ")发送失败:" + err.message)
            res.status(400).send(err.message);
        }else{
            __logger.info("账号注册邮件(" + toEmail + "),随机数(" + token + ")发送成功")
            res.json("success");
        }
    });
    //res.json("success");
}

//校验邮箱验证
exports.validateEmail = function(req, res){
    var token = req.query.token;
    var sessionToken = req.session.token;
    res.status(302);
    if(token && sessionToken && token == sessionToken){
        req.session.token = null;
        req.session.emailCheck = true;
        __logger.info("邮箱校验成功(" + token + ")")
        res.setHeader("Location", "/email.html");
    }else{
        __logger.error("邮箱校验失败(" + token + ")")
        res.setHeader("Location", "/error.html");
    }
    res.end();
}

//检查邮箱验证状态
exports.checkValidateEmail = function(req, res){
    if(req.session.emailCheck){
        req.session.emailCheck = false;
        res.json("success");
    }else{
        res.status(400).send(msg.MAIN.validateEmail);
    }
}

exports.forgetPassword = function(req, res){
    var toEmail = req.body.loginId;

    var customer = {
        loginId: toEmail
    };

    customerModel.findOne(customer).exec(function(err, doc) {
        if (err) {
            res.status(400).send(err);
            return;
        }
        if (!doc) {
            res.status(400).send(msg.USER.loginIdNone);
            return;
        }else{
            var token = Math.ceil(Math.random()*10000000);
            req.session.token = token;
            req.session.loginId = toEmail;

            html = "
您好:
 " +
            "
我们收到您在仲良速递的密码重置申请,请于10分钟内点击下面的链接完成密码重置操作:
" +
            "" + "请点击本链接进行密码重置"

            var mail = {
                from: '仲良速递<service@brother-express.com>',
                to: toEmail,
                subject: '仲良速递账户密码重置',
                html: html
            }
            transporter.sendMail(mail, function(err, info){
                if(err){
                    __logger.error("密码重置邮件(" + toEmail + "),随机数(" + token + ")发送失败:" + err.message)
                    res.status(400).send(err);
                }else{
                    __logger.info("密码重置邮件(" + toEmail + "),随机数(" + token + ")发送成功")
                    res.json("success");
                }
            });
        }
    });

}

//密码重置
exports.resetPassword = function(req, res){
    var token = req.body.token;
    var loginId = req.session.loginId;
    var password = req.body.password;
    var sessionToken = req.session.token;
    if(token && sessionToken && token == sessionToken && loginId){
        req.session.token = null;
        req.session.loginId = null;
        customerModel.findOneAndUpdate({loginId: loginId}, {password: password}, function (err, doc) {
            if (err) {
                __logger.error("密码重置(" + loginId +")失败:" + err.message)
                res.status(400).send(err.message);
                return;
            }
            __logger.error("密码重置(" + loginId +")成功")
            res.json("success");
        });
    }else{
        __logger.error("密码重置(" + loginId +")失败")
        res.status(400).send("error");
    }
}

//查询订单支付状态
exports.queryPayStatus = function (req, res) {
    orderModel.findOne({id: req.body.orderId}).exec(function(err, doc) {
        if (err) {
            __logger.info("订单(" + req.body.orderId + ")状态获取失败:" + err);
            res.status(400).send(err);
            return;
        }
        if (!doc) {
            __logger.info("查询订单状态,订单(" + req.body.orderId + ")不存在");
            res.status(400).send(msg.USER.userNone);
            return;
        }
        return res.json({payStatus: doc.payStatus});
    });
};

//发送站内信
exports.sendWebMail = function (req, res) {

    then(function (cont) {
        msgModel.findOne({id: req.body.id}).exec(function(err, doc) {
            cont(err, doc)
        })
    }).then(function(cont, doc){
        if (!doc) {
            var newMsg = new msgModel({
                id: req.body.id,
                title: req.body.title,
                from: req.body.from,
                to: req.body.to,
                details: [req.body.details]
            })
            newMsg.save(function(err, doc){
                cont(err, doc);
            })
        }else{
            msgModel.update({id: doc.id}, {'$addToSet': {details: req.body.details}}, function (err, doc) {
                cont(err, doc);
            })
        }
    }).then(function(cont, doc) {
        res.json("success");
    }).fail(function (cont, error) {
        res.status(400).send(error.message);
    });

}

//查询站内信
exports.listWebMail = function (req, res) {
    var query = {
        from : req.body.from,
        to: req.body.to
    }

    //__logger.info(query)

    msgModel.find(query).exec(function(err, doc){
        if(err){
            res.status(400).send()
            return
        }
        res.json(doc)
    })
}


text:
package at.int32.sweaty.ui.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

public class ImageUtils {

	public static Image getImageFromResources(String path) {
		return new Image(null, ClassLoader.getSystemResourceAsStream(path));
	}

	public static Image getImageFromBase64(String base64) throws UnsupportedEncodingException {
		return new Image(Display.getCurrent(), new ByteArrayInputStream(Base64.decode(base64)));
	}

	public static Image getImageFromBase64(String base64, int width, int height)
			throws UnsupportedEncodingException {

		Display display = Display.getCurrent();
		Image img = new Image(display, new ByteArrayInputStream(Base64.decode(base64)));
		return resize(img, width, height);
	}

	public static Image getImageFromPath(String path, int width, int height)
			throws UnsupportedEncodingException {
		return new Image(null, ResourceLoader.image(path));
	}

	public static Image getImageFromPathExternal(String path, int width, int height)
			throws UnsupportedEncodingException {

		return new Image(Display.getCurrent(), path);
	}

	public static Image getImage(byte[] data, int width, int height)
			throws UnsupportedEncodingException {

		Display display = Display.getCurrent();
		Image img = new Image(display, new ByteArrayInputStream(data));
		return resize(img, width, height);
	}

	public static Image getRoundedImage(String base64, int width, int height)
			throws UnsupportedEncodingException {
		return getImageFromBase64(base64, width, height);
	}

	private static Image resize(Image image, int width, int height) {
		Image scaled = new Image(Display.getDefault(), width, height);
		GC gc = new GC(scaled);
		gc.setAntialias(SWT.ON);
		gc.setInterpolation(SWT.HIGH);
		gc.drawImage(image, 0, 0, image.getBounds().width,
				image.getBounds().height, 0, 0, width, height);
		gc.dispose();
		image.dispose(); // don't forget about me!
		return scaled;
	}

	public static String getBase64FromPath(String path, int width, int height) {
		File file = new File(path);

		byte[] data;
		try {
			BufferedImage img = ImageIO.read(file);
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			ImageIO.write(img, "png", stream);
			return Base64.encode(stream.toByteArray());

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		return "";
	}
}


text:
package com.netflix.spinnaker.clouddriver.kubernetes.security;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.netflix.spinnaker.clouddriver.kubernetes.caching.KubernetesProvider;
import com.netflix.spinnaker.clouddriver.kubernetes.caching.agent.KubernetesCachingAgent;
import com.netflix.spinnaker.clouddriver.kubernetes.caching.agent.KubernetesCachingAgentDispatcher;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

@RunWith(JUnitPlatform.class)
public class KubernetesCredentialsLifecycleHandlerTest {

  @Test
  public void testAddCredentials() {
    KubernetesProvider provider = new KubernetesProvider();
    KubernetesCachingAgentDispatcher cachingAgentDispatcher =
        mock(KubernetesCachingAgentDispatcher.class);
    when(cachingAgentDispatcher.buildAllCachingAgents(ArgumentMatchers.any()))
        .thenAnswer(d -> Collections.singleton(mock(KubernetesCachingAgent.class)));
    KubernetesCredentialsLifecycleHandler handler =
        new KubernetesCredentialsLifecycleHandler(provider, cachingAgentDispatcher);

    // Check we start with no agents
    assertThat(provider.getAgents()).isEmpty();

    KubernetesNamedAccountCredentials namedCredentials =
        Mockito.mock(KubernetesNamedAccountCredentials.class);
    when(namedCredentials.getCredentials()).thenReturn(mock(KubernetesCredentials.class));

    handler.credentialsAdded(namedCredentials);
    // We should have added an agent
    assertThat(provider.getAgents()).hasSize(1);

    handler.credentialsAdded(namedCredentials);
    // We should have yet another one
    assertThat(provider.getAgents()).hasSize(2);
  }

  @Test
  public void testRemoveCredentials() {
    String ACCOUNT1 = "account1";
    String ACCOUNT2 = "account2";
    KubernetesProvider provider = new KubernetesProvider();

    KubernetesCachingAgent agent1 = mock(KubernetesCachingAgent.class);
    when(agent1.handlesAccount(ACCOUNT1)).thenReturn(true);

    KubernetesCachingAgent agent2 = mock(KubernetesCachingAgent.class);
    when(agent1.handlesAccount(ACCOUNT2)).thenReturn(true);

    provider.addAgents(List.of(agent1, agent2));

    KubernetesCredentialsLifecycleHandler handler =
        new KubernetesCredentialsLifecycleHandler(provider, null);

    assertThat(provider.getAgents()).hasSize(2);

    KubernetesNamedAccountCredentials cred1 = mock(KubernetesNamedAccountCredentials.class);
    when(cred1.getName()).thenReturn(ACCOUNT1);
    handler.credentialsDeleted(cred1);

    // We removed account1 so only agent2 should remain
    assertThat(provider.getAgents()).hasSize(1);
    assertThat(provider.getAgents()).contains(agent2);
  }
}


text:
module Janky
  class Commit < ActiveRecord::Base
    belongs_to :repository
    has_many :builds

    def last_build
      builds.last
    end

    def build!(user, room_id = nil, compare = nil)
      compare = repository.github_url("compare/#{sha1}^...#{sha1}")

      if room_id.nil? || room_id.zero?
        room_id = repository.room_id
      end

      builds.create!(
        :compare   => compare,
        :user      => user,
        :commit    => self,
        :room_id   => room_id,
        :branch_id => repository.branch_for('master').id
      )
    end
  end
end


text:
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | yaml conversion');

test('yaml conversion of translations has worked', function(assert) {

  visit('/');

  andThen(() => {
    assert.equal(find('h1#title').text(), 'Application Title');
  });
});


text:
@interface HNFeedBackViewController : UIViewController

@end


text:
self.MonacoEnvironment = {
  baseUrl: '/* @echo MONACO_BASE *//'
};

importScripts('/* @echo MONACO_LOCATION *//base/worker/workerMain.js');


text:
/**
 * Takes user's input and if they are
 * validated, it sends them to the
 * CheckInputServlet for editing.
 */
function checkInputIfExists(input) {
	if (acceptInput(input)) {
		$.getJSON($SCRIPT_ROOT + '/_check_user', {
			value: $('#' + input).val(),
			inputType: input
		}, function(data) {
			$('#accept' + input).text(data);
		});
		return false;
	}
}

/**
 * Takes user's input and validates them
 */
function acceptInput(input) {
	var accepted = true;
	if(input == "username") {
		if($("#" + input).val().length < 3) {
			$("#accept" + input).text("Username must contain at least 3 characters");
			accepted = false;
		}
	} else {
		var words = $("#" + input).val().split("@");
		if(words.length == 1 || words.length > 2) {
			$('#accept' + input).text("Given value is not accepted.");
			accepted = false;
		} else {
			var words2 = words[1].split(".");
			if(words2.length == 1 || words2.length > 2) {
				$('#accept' + input).text("Given value is not accepted.");
				accepted = false;
			}
		}
	}

	return accepted;
}

/**
 * Checks if the two passwords are same and have more
 * than 6 characters. If not it doesn't accept them.
 */
function verifyPasswords() {
	var password1 = $('#pswrd1').val();
	var password2 = $('#pswrd2').val();
	var accepted = false;
	if(password1 == password2)
		if(password1.length >= 6) {
			$('#acceptPswrd').text("Passwords match.");
			accepted = true;
		} else
			$('#acceptPswrd').text("Password must contain at least 6 characters");
	else
	if(password1 == "")
		$('#acceptPswrd').text("Give a password. This field is required.");
	else
		$('#acceptPswrd').text("Passwords do not match.");
	return accepted;
}

/**
 *  Takes user's credentials it validates them
 *  and if they are, it sends them to the User class
 *  for creating a new user.
 */
function createAccount() {
	var firstName = $('#firstName').val();
	var surname = $('#surname').val();
	checkInputIfExists('username');
	checkInputIfExists('email');
	var usernameAccepted = $('#acceptusername').text();
	var emailAccepted = $('#acceptemail').text();
	var passwordAccepted = verifyPasswords();
	if(firstName == "" || surname == ""
		|| usernameAccepted != "Your username is accepted!"
		|| emailAccepted != "Your email is accepted!"
		|| !passwordAccepted) {

		alert("Your registration cannot be completed! Please, check again fields");
	} else {
		$.getJSON($SCRIPT_ROOT + '/_new_account', {
			name: firstName,
			lastName: surname,
			username: $('#username').val(),
			email: $('#email').val(),
			password: $('#pswrd1').val()
		}, function(data) {
			alert(data);
			window.location.reload(true);
        });
	}
}


text:
// +build !providerless

package azure_file

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"testing"

	"github.com/Azure/go-autorest/autorest/to"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/kubernetes/fake"
	fakecloud "k8s.io/cloud-provider/fake"
	"k8s.io/utils/mount"

	"k8s.io/kubernetes/pkg/volume"
	volumetest "k8s.io/kubernetes/pkg/volume/testing"
	"k8s.io/legacy-cloud-providers/azure"
)

func TestCanSupport(t *testing.T) {
	tmpDir, err := ioutil.TempDir(os.TempDir(), "azureFileTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPluginByName("kubernetes.io/azure-file")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	if plug.GetPluginName() != "kubernetes.io/azure-file" {
		t.Errorf("Wrong name: %s", plug.GetPluginName())
	}
	if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{AzureFile: &v1.AzureFileVolumeSource{}}}}) {
		t.Errorf("Expected true")
	}
	if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{AzureFile: &v1.AzureFilePersistentVolumeSource{}}}}}) {
		t.Errorf("Expected true")
	}
}

func TestGetAccessModes(t *testing.T) {
	tmpDir, err := ioutil.TempDir(os.TempDir(), "azureFileTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/azure-file")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	if !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteOnce) || !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadOnlyMany) || !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteMany) {
		t.Errorf("Expected three AccessModeTypes:  %s, %s, and %s", v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany)
	}
}

func getAzureTestCloud(t *testing.T) *azure.Cloud {
	config := `{
                "aadClientId": "--aad-client-id--",
                "aadClientSecret": "--aad-client-secret--"
        }`
	configReader := strings.NewReader(config)
	azureCloud, err := azure.NewCloudWithoutFeatureGates(configReader)
	if err != nil {
		t.Error(err)
	}
	return azureCloud
}

func getTestTempDir(t *testing.T) string {
	tmpDir, err := ioutil.TempDir(os.TempDir(), "azurefileTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	return tmpDir
}

func TestPluginAzureCloudProvider(t *testing.T) {
	tmpDir := getTestTempDir(t)
	defer os.RemoveAll(tmpDir)
	testPlugin(t, tmpDir, volumetest.NewFakeVolumeHostWithCloudProvider(tmpDir, nil, nil, getAzureTestCloud(t)))
}

func TestPluginWithoutCloudProvider(t *testing.T) {
	tmpDir := getTestTempDir(t)
	defer os.RemoveAll(tmpDir)
	testPlugin(t, tmpDir, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))
}

func TestPluginWithOtherCloudProvider(t *testing.T) {
	tmpDir := getTestTempDir(t)
	defer os.RemoveAll(tmpDir)
	cloud := &fakecloud.Cloud{}
	testPlugin(t, tmpDir, volumetest.NewFakeVolumeHostWithCloudProvider(tmpDir, nil, nil, cloud))
}

func testPlugin(t *testing.T, tmpDir string, volumeHost volume.VolumeHost) {
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumeHost)

	plug, err := plugMgr.FindPluginByName("kubernetes.io/azure-file")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	spec := &v1.Volume{
		Name: "vol1",
		VolumeSource: v1.VolumeSource{
			AzureFile: &v1.AzureFileVolumeSource{
				SecretName: "secret",
				ShareName:  "share",
			},
		},
	}
	fake := mount.NewFakeMounter(nil)
	pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("poduid")}}
	mounter, err := plug.(*azureFilePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), pod, &fakeAzureSvc{}, fake)
	if err != nil {
		t.Errorf("Failed to make a new Mounter: %v", err)
	}
	if mounter == nil {
		t.Errorf("Got a nil Mounter")
	}
	volPath := filepath.Join(tmpDir, "pods/poduid/volumes/kubernetes.io~azure-file/vol1")
	path := mounter.GetPath()
	if path != volPath {
		t.Errorf("Got unexpected path: %s", path)
	}

	if err := mounter.SetUp(volume.MounterArgs{}); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			t.Errorf("SetUp() failed, volume path not created: %s", path)
		} else {
			t.Errorf("SetUp() failed: %v", err)
		}
	}

	unmounter, err := plug.(*azureFilePlugin).newUnmounterInternal("vol1", types.UID("poduid"), mount.NewFakeMounter(nil))
	if err != nil {
		t.Errorf("Failed to make a new Unmounter: %v", err)
	}
	if unmounter == nil {
		t.Errorf("Got a nil Unmounter")
	}

	if err := unmounter.TearDown(); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}
	if _, err := os.Stat(path); err == nil {
		t.Errorf("TearDown() failed, volume path still exists: %s", path)
	} else if !os.IsNotExist(err) {
		t.Errorf("TearDown() failed: %v", err)
	}
}

func TestPersistentClaimReadOnlyFlag(t *testing.T) {
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: "pvA",
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeSource: v1.PersistentVolumeSource{
				AzureFile: &v1.AzureFilePersistentVolumeSource{},
			},
			ClaimRef: &v1.ObjectReference{
				Name: "claimA",
			},
		},
	}

	claim := &v1.PersistentVolumeClaim{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "claimA",
			Namespace: "nsA",
		},
		Spec: v1.PersistentVolumeClaimSpec{
			VolumeName: "pvA",
		},
		Status: v1.PersistentVolumeClaimStatus{
			Phase: v1.ClaimBound,
		},
	}

	client := fake.NewSimpleClientset(pv, claim)

	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost("/tmp/fake", client, nil))
	plug, _ := plugMgr.FindPluginByName(azureFilePluginName)

	// readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes
	spec := volume.NewSpecFromPersistentVolume(pv, true)
	pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("poduid")}}
	mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{})
	if mounter == nil {
		t.Fatalf("Got a nil Mounter")
	}

	if !mounter.GetAttributes().ReadOnly {
		t.Errorf("Expected true for mounter.IsReadOnly")
	}
}

type fakeAzureSvc struct{}

func (s *fakeAzureSvc) GetAzureCredentials(host volume.VolumeHost, nameSpace, secretName string) (string, string, error) {
	return "name", "key", nil
}
func (s *fakeAzureSvc) SetAzureCredentials(host volume.VolumeHost, nameSpace, accountName, accountKey string) (string, error) {
	return "secret", nil
}

func TestMounterAndUnmounterTypeAssert(t *testing.T) {
	tmpDir, err := ioutil.TempDir(os.TempDir(), "azurefileTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPluginByName("kubernetes.io/azure-file")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	spec := &v1.Volume{
		Name: "vol1",
		VolumeSource: v1.VolumeSource{
			AzureFile: &v1.AzureFileVolumeSource{
				SecretName: "secret",
				ShareName:  "share",
			},
		},
	}
	fake := mount.NewFakeMounter(nil)
	pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("poduid")}}
	mounter, err := plug.(*azureFilePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), pod, &fakeAzureSvc{}, fake)
	if err != nil {
		t.Errorf("MounterInternal() failed: %v", err)
	}
	if _, ok := mounter.(volume.Unmounter); ok {
		t.Errorf("Volume Mounter can be type-assert to Unmounter")
	}

	unmounter, err := plug.(*azureFilePlugin).newUnmounterInternal("vol1", types.UID("poduid"), mount.NewFakeMounter(nil))
	if err != nil {
		t.Errorf("MounterInternal() failed: %v", err)
	}
	if _, ok := unmounter.(volume.Mounter); ok {
		t.Errorf("Volume Unmounter can be type-assert to Mounter")
	}
}

type testcase struct {
	name      string
	defaultNs string
	spec      *volume.Spec
	// Expected return of the test
	expectedName  string
	expectedNs    string
	expectedError error
}

func TestGetSecretNameAndNamespaceForPV(t *testing.T) {
	secretNs := "ns"
	tests := []testcase{
		{
			name:      "persistent volume source",
			defaultNs: "default",
			spec: &volume.Spec{
				PersistentVolume: &v1.PersistentVolume{
					Spec: v1.PersistentVolumeSpec{
						PersistentVolumeSource: v1.PersistentVolumeSource{
							AzureFile: &v1.AzureFilePersistentVolumeSource{
								ShareName:       "share",
								SecretName:      "name",
								SecretNamespace: &secretNs,
							},
						},
					},
				},
			},
			expectedName:  "name",
			expectedNs:    "ns",
			expectedError: nil,
		},
		{
			name:      "persistent volume source without namespace",
			defaultNs: "default",
			spec: &volume.Spec{
				PersistentVolume: &v1.PersistentVolume{
					Spec: v1.PersistentVolumeSpec{
						PersistentVolumeSource: v1.PersistentVolumeSource{
							AzureFile: &v1.AzureFilePersistentVolumeSource{
								ShareName:  "share",
								SecretName: "name",
							},
						},
					},
				},
			},
			expectedName:  "name",
			expectedNs:    "default",
			expectedError: nil,
		},
		{
			name:      "pod volume source",
			defaultNs: "default",
			spec: &volume.Spec{
				Volume: &v1.Volume{
					VolumeSource: v1.VolumeSource{
						AzureFile: &v1.AzureFileVolumeSource{
							ShareName:  "share",
							SecretName: "name",
						},
					},
				},
			},
			expectedName:  "name",
			expectedNs:    "default",
			expectedError: nil,
		},
	}
	for _, testcase := range tests {
		resultName, resultNs, err := getSecretNameAndNamespace(testcase.spec, testcase.defaultNs)
		if err != testcase.expectedError || resultName != testcase.expectedName || resultNs != testcase.expectedNs {
			t.Errorf("%s failed: expected err=%v ns=%q name=%q, got %v/%q/%q", testcase.name, testcase.expectedError, testcase.expectedNs, testcase.expectedName,
				err, resultNs, resultName)
		}
	}

}

func TestAppendDefaultMountOptions(t *testing.T) {
	tests := []struct {
		options  []string
		fsGroup  *int64
		expected []string
	}{
		{
			options: []string{"dir_mode=0777"},
			fsGroup: nil,
			expected: []string{"dir_mode=0777",
				fmt.Sprintf("%s=%s", fileMode, defaultFileMode),
				fmt.Sprintf("%s=%s", vers, defaultVers)},
		},
		{
			options: []string{"file_mode=0777"},
			fsGroup: to.Int64Ptr(0),
			expected: []string{"file_mode=0777",
				fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
				fmt.Sprintf("%s=%s", vers, defaultVers),
				fmt.Sprintf("%s=0", gid)},
		},
		{
			options: []string{"vers=2.1"},
			fsGroup: to.Int64Ptr(1000),
			expected: []string{"vers=2.1",
				fmt.Sprintf("%s=%s", fileMode, defaultFileMode),
				fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
				fmt.Sprintf("%s=1000", gid)},
		},
		{
			options: []string{""},
			expected: []string{"", fmt.Sprintf("%s=%s",
				fileMode, defaultFileMode),
				fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
				fmt.Sprintf("%s=%s", vers, defaultVers)},
		},
		{
			options:  []string{"file_mode=0777", "dir_mode=0777"},
			expected: []string{"file_mode=0777", "dir_mode=0777", fmt.Sprintf("%s=%s", vers, defaultVers)},
		},
		{
			options: []string{"gid=2000"},
			fsGroup: to.Int64Ptr(1000),
			expected: []string{"gid=2000",
				fmt.Sprintf("%s=%s", fileMode, defaultFileMode),
				fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
				"vers=3.0"},
		},
	}

	for _, test := range tests {
		result := appendDefaultMountOptions(test.options, test.fsGroup)
		if !reflect.DeepEqual(result, test.expected) {
			t.Errorf("input: %q, appendDefaultMountOptions result: %q, expected: %q", test.options, result, test.expected)
		}
	}
}


text:
/**
 * Currently in beta stage. Changes can and will be made to the core mechanic
 * making this not backwards compatible.
 *
 * Github: https://github.com/Need4Speed402/tessellator
 */

Tessellator.Model.prototype.setDirectionalLight = function (){
    return this.add(Tessellator.new.apply(Tessellator.DirectionalLight, arguments));
};

Tessellator.DirectionalLight = function (){
    if (arguments.length === 1){
        this.vec = arguments[0];
    }else if (arguments.length === 3){
        this.vec = Tessellator.vec3(arguments);
    }else{
        throw "invalid arguments in Tessellator.DirectionalLight";
    };

    this.type = Tessellator.LIGHTING_DIRECTIONAL;
    this.subtype = Tessellator.LIGHTING;

    this.render = true;
};

Tessellator.DirectionalLight.prototype.set = function (lighting, index, matrix){
    if (this.color.tween) this.color.tween.update();

    lighting[0 + index] = 2;
    lighting.set(this.color.xyz.multiply(this.color.w), 1 + index);
    lighting.set(this.vec.clone().rotate(matrix).normalize(), 4 + index);

    if (this.shadowMap){
        lighting[12 + index] = 1;
        lighting[13 + index] = this.shadowRenderer.x;
        lighting[14 + index] = this.shadowRenderer.y;
        lighting[15 + index] = this.shadowRenderer.z;
    }else{
        lighting[12 + index] = 0;
    };
};

Tessellator.DirectionalLight.prototype.applyLighting = function (mat, matrix, index, renderer){
    if (this.render){
        this.set(renderer.lightingTexture.data, index[0] * 4 * 4, mat);

        if (index[0]++ * 4 * 4 >= renderer.lightingTexture.data.length){
            throw "too many lights!";
        };
    };
};

Tessellator.DirectionalLight.prototype.init = function (interpreter){
    this.tessellator = interpreter.tessellator;
    this.color = interpreter.get("color");

    if (this.shadowMap){
        this.createShadow.apply(this, this.shadowMap);
    };
};

Tessellator.DirectionalLight.prototype.apply = function (matrix){
    if (this.shadowMap){
        matrix.set("shadowMap", this.shadowMap);
    };
};

Tessellator.DirectionalLight.prototype.createShadow = function (model, x, y, z, resolution){
    if (this.tessellator){
        this.shadowRenderer = new Tessellator.DirectionalLightingShadowMapRenderer(Tessellator.DEPTH_MAP_ORTHOGRAPHIC_SHADER.create(this.tessellator), x, y, z, this);

        this.shadowMap = new Tessellator.TextureModel(this.tessellator, resolution * x / y, resolution * y / x, [
            new Tessellator.TextureModel.AttachmentColor(),
            new Tessellator.TextureModel.AttachmentDepth(),
            new Tessellator.TextureModel.AttachmentRenderer(this.shadowRenderer, model)
        ]);
    }else{
        this.shadowMap = arguments;
    };
};


text:
package com.netflix.simianarmy.chaos;

import java.io.IOException;
import com.netflix.simianarmy.MonkeyConfiguration;

/**
 * Adds entries to /etc/hosts so that EC2 API endpoints are unreachable.
 */
public class FailEc2ChaosType extends ScriptChaosType {
    /**
     * Constructor.
     *
     * @param config
     *            Configuration to use
     * @throws IOException
     */
    public FailEc2ChaosType(MonkeyConfiguration config) {
        super(config, "FailEc2");
    }
}


text:
module Plex
  class Video

    ATTRIBUTES = %w(ratingKey key studio type title titleSort contentRating summary
                    rating viewCount year tagline thumb art duration
                    originallyAvailableAt updatedAt)

    attr_reader :medias, :genres, :writers, :directors, :roles, :attribute_hash

    # @param [Nokogiri::XML::Element] nokogiri element that represents this
    #   Video
    def initialize(node)
      @attribute_hash = {}
      node.attributes.each do |method, val|
        @attribute_hash[Plex.underscore(method)] = val.value
        define_singleton_method(Plex.underscore(method).to_sym) do
          val.value
        end
      end

      @medias     = node.search('Media').map    { |m| Plex::Media.new(m)    }
      @genres     = node.search('Genre').map    { |m| Plex::Genre.new(m)    }
      @writers    = node.search('Writer').map   { |m| Plex::Writer.new(m)   }
      @directors  = node.search('Director').map { |m| Plex::Director.new(m) }
      @roles      = node.search('Role').map     { |m| Plex::Role.new(m)     }
    end

    def ==(other)
      if other.is_a? Video
        key == other.key
      else
        super
      end
    end

  end
end


text:
#ifndef ASM_ARM_ARCH_OMAP_OMAP_PM_H
#define ASM_ARM_ARCH_OMAP_OMAP_PM_H

#include <linux/device.h>
#include <linux/cpufreq.h>
#include <linux/clk.h>
#include <linux/pm_opp.h>

/*
 * agent_id values for use with omap_pm_set_min_bus_tput():
 *
 * OCP_INITIATOR_AGENT is only valid for devices that can act as
 * initiators -- it represents the device's L3 interconnect
 * connection.  OCP_TARGET_AGENT represents the device's L4
 * interconnect connection.
 */
#define OCP_TARGET_AGENT		1
#define OCP_INITIATOR_AGENT		2

/**
 * omap_pm_if_early_init - OMAP PM init code called before clock fw init
 * @mpu_opp_table: array ptr to struct omap_opp for MPU
 * @dsp_opp_table: array ptr to struct omap_opp for DSP
 * @l3_opp_table : array ptr to struct omap_opp for CORE
 *
 * Initialize anything that must be configured before the clock
 * framework starts.  The "_if_" is to avoid name collisions with the
 * PM idle-loop code.
 */
int __init omap_pm_if_early_init(void);

/**
 * omap_pm_if_init - OMAP PM init code called after clock fw init
 *
 * The main initialization code.  OPP tables are passed in here.  The
 * "_if_" is to avoid name collisions with the PM idle-loop code.
 */
int __init omap_pm_if_init(void);

/*
 * Device-driver-originated constraints (via board-*.c files, platform_data)
 */

/**
 * omap_pm_set_max_mpu_wakeup_lat - set the maximum MPU wakeup latency
 * @dev: struct device * requesting the constraint
 * @t: maximum MPU wakeup latency in microseconds
 *
 * Request that the maximum interrupt latency for the MPU to be no
 * greater than @t microseconds. "Interrupt latency" in this case is
 * defined as the elapsed time from the occurrence of a hardware or
 * timer interrupt to the time when the device driver's interrupt
 * service routine has been entered by the MPU.
 *
 * It is intended that underlying PM code will use this information to
 * determine what power state to put the MPU powerdomain into, and
 * possibly the CORE powerdomain as well, since interrupt handling
 * code currently runs from SDRAM.  Advanced PM or board*.c code may
 * also configure interrupt controller priorities, OCP bus priorities,
 * CPU speed(s), etc.
 *
 * This function will not affect device wakeup latency, e.g., time
 * elapsed from when a device driver enables a hardware device with
 * clk_enable(), to when the device is ready for register access or
 * other use.  To control this device wakeup latency, use
 * omap_pm_set_max_dev_wakeup_lat()
 *
 * Multiple calls to omap_pm_set_max_mpu_wakeup_lat() will replace the
 * previous t value.  To remove the latency target for the MPU, call
 * with t = -1.
 *
 * XXX This constraint will be deprecated soon in favor of the more
 * general omap_pm_set_max_dev_wakeup_lat()
 *
 * Returns -EINVAL for an invalid argument, -ERANGE if the constraint
 * is not satisfiable, or 0 upon success.
 */
int omap_pm_set_max_mpu_wakeup_lat(struct device *dev, long t);

/**
 * omap_pm_set_min_bus_tput - set minimum bus throughput needed by device
 * @dev: struct device * requesting the constraint
 * @tbus_id: interconnect to operate on (OCP_{INITIATOR,TARGET}_AGENT)
 * @r: minimum throughput (in KiB/s)
 *
 * Request that the minimum data throughput on the OCP interconnect
 * attached to device @dev interconnect agent @tbus_id be no less
 * than @r KiB/s.
 *
 * It is expected that the OMAP PM or bus code will use this
 * information to set the interconnect clock to run at the lowest
 * possible speed that satisfies all current system users.  The PM or
 * bus code will adjust the estimate based on its model of the bus, so
 * device driver authors should attempt to specify an accurate
 * quantity for their device use case, and let the PM or bus code
 * overestimate the numbers as necessary to handle request/response
 * latency, other competing users on the system, etc.  On OMAP2/3, if
 * a driver requests a minimum L4 interconnect speed constraint, the
 * code will also need to add an minimum L3 interconnect speed
 * constraint,
 *
 * Multiple calls to omap_pm_set_min_bus_tput() will replace the
 * previous rate value for this device.  To remove the interconnect
 * throughput restriction for this device, call with r = 0.
 *
 * Returns -EINVAL for an invalid argument, -ERANGE if the constraint
 * is not satisfiable, or 0 upon success.
 */
int omap_pm_set_min_bus_tput(struct device *dev, u8 agent_id, unsigned long r);

/*
 * CPUFreq-originated constraint
 *
 * In the future, this should be handled by custom OPP clocktype
 * functions.
 */

/*
 * Device context loss tracking
 */

/**
 * omap_pm_get_dev_context_loss_count - return count of times dev has lost ctx
 * @dev: struct device *
 *
 * This function returns the number of times that the device @dev has
 * lost its internal context.  This generally occurs on a powerdomain
 * transition to OFF.  Drivers use this as an optimization to avoid restoring
 * context if the device hasn't lost it.  To use, drivers should initially
 * call this in their context save functions and store the result.  Early in
 * the driver's context restore function, the driver should call this function
 * again, and compare the result to the stored counter.  If they differ, the
 * driver must restore device context.   If the number of context losses
 * exceeds the maximum positive integer, the function will wrap to 0 and
 * continue counting.  Returns the number of context losses for this device,
 * or negative value upon error.
 */
int omap_pm_get_dev_context_loss_count(struct device *dev);

void omap_pm_enable_off_mode(void);
void omap_pm_disable_off_mode(void);

#endif


text:
import Ember from 'ember';
import Sortable from 'ui/mixins/sortable';

export default Ember.Controller.extend(Sortable, {
  sortableContent: Ember.computed.alias('model'),
  sortBy: 'name',
  sorts: {
    state:        ['stateSort','name','id'],
    name:         ['name','id'],
    services:     ['services.length','name','id'],
  },
});


text:
package gnu.classpath.jdwp.event.filters;

import gnu.classpath.jdwp.event.Event;
import gnu.classpath.jdwp.exception.NotImplementedException;

/**
 * An event filter which allows expression conditionals.
 * Note that in JDWP 1.4, this class is marked "for the
 * future".
 *
 * @author Keith Seitz  (keiths@redhat.com)
 */
public class ConditionalFilter
  implements IEventFilter
{
  // private ConditionalId _exprId;

  /**
   * Constructs a new ConditionalFilter with the
   * given conditional.
   *
   *
NOTE: This filter is marked "for the future",
   * i.e, there is no way to actually use this yet.
   *
   * @param  conditional  the conditional expression
   * @throws NotImplementedException if used
   */
  public ConditionalFilter (Object conditional)
    throws NotImplementedException
  {
    throw new NotImplementedException ("conditional filters");
  }

  /**
   * Does the given event match the filter?
   *
   * @param event  the Event to scrutinize
   */
  public boolean matches (Event event)
  {
    return false;
  }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%email_history}}".
 *
 * @property integer $id
 * @property string $email_id
 * @property integer $event_id
 * @property integer $status
 * @property integer $mail_method
 * @property string $subject
 * @property string $body
 * @property string $attachment
 * @property integer $attempts
 * @property string $sender_email
 * @property string $sent_on
 *
 * @property Lookups $status0
 */
class EmailHistory extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return "{{%email_history}}";
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email_id', 'status', 'mail_method', 'subject', 'body', 'attempts', 'sender_email', 'sent_on'], 'required'],
            [['event_id', 'status', 'mail_method', 'attempts'], 'integer'],
            [['body'], 'string'],
            [['sent_on'], 'safe'],
            [['email_id', 'attachment', 'sender_email'], 'string', 'max' => 255],
            [['subject'], 'string', 'max' => 500]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email_id' => 'Email ID',
            'event_id' => 'Event ID',
            'status' => 'Status',
            'mail_method' => 'Mail Method',
            'subject' => 'Subject',
            'body' => 'Body',
            'attachment' => 'Attachment',
            'attempts' => 'Attempts',
            'sender_email' => 'Sender Email',
            'sent_on' => 'Sent On',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStatus0()
    {
        return $this->hasOne(Lookups::className(), ['id' => 'status']);
    }
}


text:
package org.apache.commons.vfs2.provider.ftp;

import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.GenericFileName;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

/**
 * A provider for FTP file systems.
 */
public class FtpFileProvider extends AbstractOriginatingFileProvider {

    /**
     * Authenticator types.
     */
    public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]{
            UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD};

    static final Collection<Capability> capabilities =
            Collections.unmodifiableCollection(Arrays.asList(Capability.CREATE, Capability.DELETE, Capability.RENAME,
                                                             Capability.GET_TYPE, Capability.LIST_CHILDREN,
                                                             Capability.READ_CONTENT, Capability.GET_LAST_MODIFIED,
                                                             Capability.URI, Capability.WRITE_CONTENT,
                                                             Capability.APPEND_CONTENT, Capability.RANDOM_ACCESS_READ));

    /**
     * Constructs a new provider.
     */
    public FtpFileProvider() {
        super();
        setFileNameParser(FtpFileNameParser.getInstance());
    }

    /**
     * Creates the filesystem.
     */
    @Override
    protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
            throws FileSystemException {

        final GenericFileName rootName = (GenericFileName) name;
        ClientWrapperFactory clientWrapperFactory = new FtpClientWrapperFactory(rootName, fileSystemOptions,
                                                                                defaultTimeout);
        return new FtpFileSystem(rootName, clientWrapperFactory, fileSystemOptions);
    }

    @Override
    public FileSystemConfigBuilder getConfigBuilder() {
        return FtpFileSystemConfigBuilder.getInstance();
    }

    @Override
    public Collection<Capability> getCapabilities() {
        return capabilities;
    }
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding field 'UserProfile.is_autovouched'
        db.add_column('profile', 'is_autovouched', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False)

    def backwards(self, orm):

        # Deleting field 'UserProfile.is_autovouched'
        db.delete_column('profile', 'is_autovouched')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'groups.group': {
            'Meta': {'object_name': 'Group', 'db_table': "'group'"},
            'always_auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
            'system': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})
        },
        'users.userprofile': {
            'Meta': {'object_name': 'UserProfile', 'db_table': "'profile'"},
            'bio': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'confirmation_code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}),
            'display_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['groups.Group']", 'symmetrical': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'ircname': ('django.db.models.fields.CharField', [], {'max_length': '63', 'blank': 'True'}),
            'is_autovouched': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_vouched': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'photo': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}),
            'vouched_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.UserProfile']", 'null': 'True'}),
            'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['users']


text:
package extracells.integration.opencomputers

import appeng.api.AEApi
import appeng.api.config.Actionable
import appeng.api.implementations.tiles.IWirelessAccessPoint
import appeng.api.networking.{IGrid, IGridHost, IGridNode, IMachineSet}
import appeng.api.networking.security.IActionHost
import appeng.api.networking.storage.IStorageGrid
import appeng.api.storage.IMEMonitor
import appeng.api.storage.data.{IAEFluidStack, IAEItemStack}
import appeng.api.util.{AEPartLocation, WorldCoord}
import extracells.registries.ItemEnum
import extracells.util.{FluidHelper, MachineSource, StorageChannels}
import li.cil.oc.api.Network
import li.cil.oc.api.internal.{Agent, Database, Drone, Robot}
import li.cil.oc.api.machine.{Arguments, Callback, Context}
import li.cil.oc.api.network._
import li.cil.oc.api.prefab.AbstractManagedEnvironment
import li.cil.oc.server.network.Component
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraftforge.fluids.Fluid

import scala.collection.JavaConversions._

trait NetworkControl[AETile >: Null <: TileEntity with IActionHost with IGridHost] extends AbstractManagedEnvironment{

  def tile: AETile

  def host: EnvironmentHost

  val robot: Robot =
    if (host.isInstanceOf[Robot])
      host.asInstanceOf[Robot]
    else
      null

  val drone: Drone =
    if (host.isInstanceOf[Drone])
      host.asInstanceOf[Drone]
    else
      null
  var isActive = false

  val agent: Agent = host.asInstanceOf[Agent]

  def getComponent: ItemStack = {
    if (robot != null)
      return robot.getStackInSlot(robot.componentSlot(node.address))
    else if(drone != null){
      val i = drone.internalComponents.iterator
      while (i.hasNext){
        val item = i.next
        if(item != null && item.getItem == ItemEnum.OCUPGRADE.getItem)
          return item
      }
    }
    null
  }

  def getSecurity: IGridHost = {
    if (host.world.isRemote) return null
    val component = getComponent
    val sec = AEApi.instance.registries.locatable.getLocatableBy(getAEKey(component)).asInstanceOf[IGridHost]
    if(checkRange(component, sec))
      sec
    else
      null
  }
  def checkRange(stack: ItemStack, sec: IGridHost): Boolean = {
    if (sec == null) return false
    val gridNode: IGridNode = sec.getGridNode(AEPartLocation.INTERNAL)
    if (gridNode == null) return false
    val grid = gridNode.getGrid
    if(grid == null) return false
    stack.getItemDamage match{
      case 0 =>
        grid.getMachines(AEApi.instance.definitions.blocks.wirelessAccessPoint().maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]]).iterator.hasNext
      case 1 =>
        val gridBlock = gridNode.getGridBlock
        if (gridBlock == null) return false
        val loc = gridBlock.getLocation
        if (loc == null) return false
        for (node: IGridNode <- grid.getMachines(AEApi.instance.definitions.blocks.wirelessAccessPoint().maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]])) {
          val accessPoint: IWirelessAccessPoint = node.asInstanceOf[IWirelessAccessPoint]
          val distance: WorldCoord = accessPoint.getLocation.subtract(agent.xPosition.toInt, agent.yPosition.toInt, agent.zPosition.toInt)
          val squaredDistance: Int = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z
          val range = accessPoint.getRange
          if (squaredDistance <= range * range) return true
        }
        false
      case _ =>
        val gridBlock = gridNode.getGridBlock
        if (gridBlock == null) return false
        val loc = gridBlock.getLocation
        if (loc == null) return false
        for (node: IGridNode <- grid.getMachines(AEApi.instance.definitions.blocks.wirelessAccessPoint().maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]])) {
          val accessPoint: IWirelessAccessPoint = node.asInstanceOf[IWirelessAccessPoint]
          val distance: WorldCoord = accessPoint.getLocation.subtract(agent.xPosition.toInt, agent.yPosition.toInt, agent.zPosition.toInt)
          val squaredDistance: Int = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z
          val range = accessPoint.getRange / 2
          if (squaredDistance <= range * range) return true
        }
        false
    }
  }

  def getGrid: IGrid = {
    if (host.world.isRemote) return null
    val securityTerminal = getSecurity
    if (securityTerminal == null) return null
    val gridNode: IGridNode = securityTerminal.getGridNode(AEPartLocation.INTERNAL)
    if (gridNode == null) return null
    gridNode.getGrid
  }

  def getAEKey(stack: ItemStack): Long = {
    try {
      return WirelessHandlerUpgradeAE.getEncryptionKey(stack).toLong
    }
    catch {
      case ignored: Throwable => {
      }
    }
    0L
  }

  def getFluidInventory: IMEMonitor[IAEFluidStack] = {
    val grid = getGrid
    if (grid == null) return null
    val storage: IStorageGrid = grid.getCache(classOf[IStorageGrid])
    if (storage == null) return null
    storage.getInventory(StorageChannels.FLUID)
  }

  def getItemInventory: IMEMonitor[IAEItemStack] = {
    val grid = getGrid
    if (grid == null) return null
    val storage: IStorageGrid = grid.getCache(classOf[IStorageGrid])
    if (storage == null) return null
    storage.getInventory(StorageChannels.ITEM)
  }

  @Callback(doc = "function([number:amount]):number -- Transfer selected items to your ae system.")
  def sendItems(context: Context, args: Arguments): Array[AnyRef] = {
    val selected = agent.selectedSlot
    val invRobot = agent.mainInventory
    if (invRobot.getSizeInventory <= 0) return Array(0.underlying.asInstanceOf[AnyRef])
    val stack = invRobot.getStackInSlot(selected)
    val inv = getItemInventory
    if (stack == null || stack.isEmpty || inv == null) return Array(0.underlying.asInstanceOf[AnyRef])
    val amount = Math.min(args.optInteger(0, 64), stack.getCount)
    val stack2 = stack.copy
    stack2.setCount(amount)
    val notInjectet = inv.injectItems(StorageChannels.ITEM.createStack(stack2), Actionable.MODULATE, new MachineSource(tile))
    if (notInjectet == null){
      stack.setCount(stack.getCount - amount)
      if (stack.getCount <= 0)
        invRobot.setInventorySlotContents(selected, ItemStack.EMPTY)
      else
        invRobot.setInventorySlotContents(selected, stack)
      return Array(amount.underlying.asInstanceOf[AnyRef])
    }else{
      stack.setCount(stack.getCount - amount + notInjectet.getStackSize.toInt)
      if (stack.getCount <= 0)
        invRobot.setInventorySlotContents(selected, ItemStack.EMPTY)
      else
        invRobot.setInventorySlotContents(selected, stack)
      return Array((stack2.getCount - notInjectet.getStackSize).underlying.asInstanceOf[AnyRef])
    }
  }

  @Callback(doc = "function(database:address, entry:number[, number:amount]):number -- Get items from your ae system.")
  def requestItems(context: Context, args: Arguments): Array[AnyRef] = {

    val address = args.checkString(0)
    val entry = args.checkInteger(1)
    val amount = args.optInteger(2, 64)
    val selected = agent.selectedSlot
    val invRobot = agent.mainInventory
    if (invRobot.getSizeInventory <= 0) return Array(0.underlying.asInstanceOf[AnyRef])
    val inv = getItemInventory
    if (inv == null) return Array(0.underlying.asInstanceOf[AnyRef])
    val n: Node = node.network.node(address)
    if (n == null) throw new IllegalArgumentException("no such component")
    if (!(n.isInstanceOf[Component])) throw new IllegalArgumentException("no such component")
    val component: Component = n.asInstanceOf[Component]
    val env: Environment = n.host
    if (!(env.isInstanceOf[Database])) throw new IllegalArgumentException("not a database")
    val database: Database = env.asInstanceOf[Database]
    val sel = invRobot.getStackInSlot(selected)
    val inSlot =
      if (sel == null)
        0
      else
        sel.getCount
    val maxSize =
      if (sel == null)
        64
      else
        sel.getMaxStackSize
    val stack = database.getStackInSlot(entry - 1)
    if(stack == null) return Array(0.underlying.asInstanceOf[AnyRef])
    stack.setCount(Math.min(amount, maxSize - inSlot))
    val stack2 = stack.copy
    stack2.setCount(1)
    val sel2 =
      if (sel != null) {
        val sel3 = sel.copy
        sel3.setCount(1)
        sel3
      }else
        null
    if(sel != null && !ItemStack.areItemStacksEqual(sel2, stack2) && !sel2.isEmpty) return Array(0.underlying.asInstanceOf[AnyRef])
    val extracted = inv.extractItems(StorageChannels.ITEM.createStack(stack), Actionable.MODULATE, new MachineSource(tile))
    if(extracted == null) return Array(0.underlying.asInstanceOf[AnyRef])
    val ext = extracted.getStackSize.toInt
    stack.setCount(inSlot + ext)
    invRobot.setInventorySlotContents(selected, stack)
    Array(ext.underlying.asInstanceOf[AnyRef])
  }

  @Callback(doc = "function([number:amount]):number -- Transfer selecte fluid to your ae system.")
  def sendFluids(context: Context, args: Arguments): Array[AnyRef] = {
    val selected = agent.selectedTank
    val tanks = agent.tank
    if (tanks.tankCount <= 0) return Array(0.underlying.asInstanceOf[AnyRef])
    val tank = tanks.getFluidTank(selected)
    val inv = getFluidInventory
    if (tank == null || inv == null || tank.getFluid == null) return Array(0.underlying.asInstanceOf[AnyRef])
    val amount = Math.min(args.optInteger(0, tank.getCapacity), tank.getFluidAmount)
    val fluid = tank.getFluid
    val fluid2 = fluid.copy
    fluid2.amount = amount
    val notInjectet = inv.injectItems(StorageChannels.FLUID.createStack(fluid2), Actionable.MODULATE, new MachineSource(tile))
    if (notInjectet == null){
      tank.drain(amount, true)
      Array(amount.underlying.asInstanceOf[AnyRef])
    }else{
      tank.drain(amount - notInjectet.getStackSize.toInt, true)
      Array((amount - notInjectet.getStackSize).underlying.asInstanceOf[AnyRef])
    }
  }

  @Callback(doc = "function(database:address, entry:number[, number:amount]):number -- Get fluid from your ae system.")
  def requestFluids(context: Context, args: Arguments): Array[AnyRef] = {
    val address = args.checkString(0)
    val entry = args.checkInteger(1)
    val amount = args.optInteger(2, Fluid.BUCKET_VOLUME)
    val tanks = agent.tank
    val selected = agent.selectedTank
    if (tanks.tankCount <= 0) return Array(0.underlying.asInstanceOf[AnyRef])
    val tank = tanks.getFluidTank(selected)
    val inv = getFluidInventory
    if (tank == null || inv == null) return Array(0.underlying.asInstanceOf[AnyRef])
    val n: Node = node.network.node(address)
    if (n == null) throw new IllegalArgumentException("no such component")
    if (!(n.isInstanceOf[Component])) throw new IllegalArgumentException("no such component")
    val component: Component = n.asInstanceOf[Component]
    val env: Environment = n.host
    if (!(env.isInstanceOf[Database])) throw new IllegalArgumentException("not a database")
    val database: Database = env.asInstanceOf[Database]
    val fluid = FluidHelper.getFluidFromContainer(database.getStackInSlot(entry - 1))
    fluid.amount = amount
    val fluid2 = fluid.copy()
    fluid2.amount = tank.fill(fluid, false)
    if (fluid2.amount == 0) return Array(0.underlying.asInstanceOf[AnyRef])
    val extracted = inv.extractItems(StorageChannels.FLUID.createStack(fluid2), Actionable.MODULATE, new MachineSource(tile))
    if (extracted == 0) return Array(0.underlying.asInstanceOf[AnyRef])
    Array(tank.fill(extracted.getFluidStack, true).underlying.asInstanceOf[AnyRef])
  }

  @Callback(doc = "function():boolean -- Return true if the card is linket to your ae network.")
  def isLinked(context: Context, args: Arguments): Array[AnyRef] = {
    val isLinked = getGrid != null
    Array(boolean2Boolean(isLinked))
  }

  override def update() {
    super.update()
    if (host.world.getTotalWorldTime % 10 == 0 && isActive) {
      if (!node.asInstanceOf[Connector].tryChangeBuffer(-getEnergy)) {
        isActive = false
      }
    }
  }

  def getEnergy  = {
    val c = getComponent
    if (c == null)
      .0
    else
      c.getItemDamage match{
        case 0 => .6
        case 1 => .3
        case _ => .05
      }
  }

  override def onMessage(message: Message) {
    super.onMessage(message)
    if (message.name == "computer.stopped") {
      isActive = false
    }
    else if (message.name == "computer.started") {
      isActive = true
    }
  }

}


text:
package util

import (
	"time"
)

type DurationValue time.Duration

func (d *DurationValue) String() string {
	return (*time.Duration)(d).String()
}

func (d *DurationValue) Set(value string) error {
	duration, err := time.ParseDuration(value)

	if err != nil {
		return err
	}

	*d = DurationValue(duration)

	return nil
}

func (d *DurationValue) Value() time.Duration {
	return time.Duration(*d)
}


text:
using DotVVM.Framework.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotVVM.Framework.Runtime.Filters
{
    public interface IViewModelActionFilter : IActionFilter
    {
        /// <summary>
        /// Called after the viewmodel object is created.
        /// </summary>
        Task OnViewModelCreatedAsync(IDotvvmRequestContext context);

        /// <summary>
        /// Called after the viewmodel is deserialized on postback.
        /// </summary>
        Task OnViewModelDeserializedAsync(IDotvvmRequestContext context);

        /// <summary>
        /// Called before the viewmodel is serialized.
        /// </summary>
        Task OnViewModelSerializingAsync(IDotvvmRequestContext context);

    }
}