repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
AllBecomesGood/Share-UpdateHolograms
ShareAndKeepSynced/Assets/HoloToolKit/Input/Tests/Scripts/FocusedObjectMessageSender.cs
883
using UnityEngine; namespace HoloToolkit.Unity.InputModule.Tests { /// <summary> /// FocusedObjectMessageSender class sends Unity message to object currently focused on by GazeManager. /// Focused object messages can be triggered using voice commands, so keyword responses /// need to be registered in KeywordManager. /// </summary> public class FocusedObjectMessageSender : MonoBehaviour { /// <summary> /// Sends message to the object currently focused on by GazeManager. /// </summary> /// <param name="message">Message to send</param> public void SendMessageToFocusedObject(string message) { if (GazeManager.Instance.HitObject != null) { GazeManager.Instance.HitObject.SendMessage(message, SendMessageOptions.DontRequireReceiver); } } } }
mit
grimpows/SonataPageBundle
Model/TransformerInterface.php
1010
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\PageBundle\Model; /** * @author Thomas Rabaix <thomas.rabaix@sonata-project.org> */ interface TransformerInterface { /** * @param SnapshotInterface $snapshot * * @return PageInterface */ public function load(SnapshotInterface $snapshot); /** * @param PageInterface $page * * @return SnapshotInterface */ public function create(PageInterface $page); /** * @param PageInterface $page * * @return array */ public function getChildren(PageInterface $page); /** * @param array $content * @param PageInterface $page * * @return BlockInterface */ public function loadBlock(array $content, PageInterface $page); }
mit
karan/dotfiles
.vscode/extensions/redhat.vscode-yaml-0.7.2/node_modules/vscode-languageserver/lib/resolve.js
804
/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; process.on('message', (message) => { if (message.command === 'exit') { process.exit(0); } else if (message.command === 'resolve') { try { let result = require.resolve(message.args); process.send({ command: 'resolve', success: true, result: result }); } catch (err) { process.send({ command: 'resolve', success: false }); } } });
mit
stachon/XChange
xchange-kraken/src/main/java/org/knowm/xchange/kraken/service/KrakenBaseService.java
5981
package org.knowm.xchange.kraken.service; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.knowm.xchange.Exchange; import org.knowm.xchange.client.ExchangeRestProxyBuilder; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.IOrderFlags; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.ExchangeUnavailableException; import org.knowm.xchange.exceptions.FrequencyLimitExceededException; import org.knowm.xchange.exceptions.FundsExceededException; import org.knowm.xchange.exceptions.NonceException; import org.knowm.xchange.exceptions.RateLimitExceededException; import org.knowm.xchange.instrument.Instrument; import org.knowm.xchange.kraken.KrakenAuthenticated; import org.knowm.xchange.kraken.KrakenUtils; import org.knowm.xchange.kraken.dto.KrakenResult; import org.knowm.xchange.kraken.dto.marketdata.KrakenAssetPair; import org.knowm.xchange.kraken.dto.marketdata.KrakenAssets; import org.knowm.xchange.kraken.dto.marketdata.KrakenServerTime; import org.knowm.xchange.kraken.dto.marketdata.results.KrakenAssetsResult; import org.knowm.xchange.kraken.dto.marketdata.results.KrakenServerTimeResult; import org.knowm.xchange.kraken.dto.trade.KrakenOrderFlags; import org.knowm.xchange.service.BaseExchangeService; import org.knowm.xchange.service.BaseService; import si.mazi.rescu.ParamsDigest; public class KrakenBaseService extends BaseExchangeService implements BaseService { protected KrakenAuthenticated kraken; protected ParamsDigest signatureCreator; /** * Constructor * * @param exchange */ public KrakenBaseService(Exchange exchange) { super(exchange); kraken = ExchangeRestProxyBuilder.forInterface( KrakenAuthenticated.class, exchange.getExchangeSpecification()) .build(); signatureCreator = KrakenDigest.createInstance(exchange.getExchangeSpecification().getSecretKey()); } public KrakenServerTime getServerTime() throws IOException { KrakenServerTimeResult timeResult = kraken.getServerTime(); return checkResult(timeResult); } public KrakenAssets getKrakenAssets(Currency... assets) throws IOException { KrakenAssetsResult assetPairsResult = kraken.getAssets(null, delimitAssets(assets)); return new KrakenAssets(checkResult(assetPairsResult)); } /** * For more info on each error codes * * <p>https://support.kraken.com/hc/en-us/articles/360001491786-API-Error-Codes */ public <R> R checkResult(KrakenResult<R> krakenResult) { if (!krakenResult.isSuccess()) { String[] errors = krakenResult.getError(); if (errors.length == 0 || errors[0] == null) { throw new ExchangeException("Missing error message"); } String error = errors[0]; switch (error) { case "EAPI:Invalid nonce": throw new NonceException(error); case "EGeneral:Temporary lockout": throw new FrequencyLimitExceededException(error); case "EOrder:Insufficient funds": throw new FundsExceededException(error); case "EAPI:Rate limit exceeded": case "EOrder:Rate limit exceeded": throw new RateLimitExceededException(error); case "EService:Unavailable": case "EService:Busy": throw new ExchangeUnavailableException(error); } throw new ExchangeException(Arrays.toString(errors)); } return krakenResult.getResult(); } protected String createDelimitedString(String[] items) { StringBuilder commaDelimitedString = null; if (items != null) { for (String item : items) { if (commaDelimitedString == null) { commaDelimitedString = new StringBuilder(item); } else { commaDelimitedString.append(",").append(item); } } } return (commaDelimitedString == null) ? null : commaDelimitedString.toString(); } protected String delimitAssets(Currency[] assets) throws IOException { StringBuilder commaDelimitedAssets = new StringBuilder(); if (assets != null && assets.length > 0) { boolean started = false; for (Currency asset : assets) { commaDelimitedAssets .append((started) ? "," : "") .append(KrakenUtils.getKrakenCurrencyCode(asset)); started = true; } return commaDelimitedAssets.toString(); } return null; } protected String delimitAssetPairs(CurrencyPair[] currencyPairs) throws IOException { return currencyPairs != null && currencyPairs.length > 0 ? Arrays.stream(currencyPairs) .map(KrakenUtils::createKrakenCurrencyPair) .filter(Objects::nonNull) .collect(Collectors.joining(",")) : null; } protected String delimitSet(Set<IOrderFlags> items) { String delimitedSetString = null; if (items != null && !items.isEmpty()) { StringBuilder delimitStringBuilder = null; for (Object item : items) { if (item instanceof KrakenOrderFlags) { if (delimitStringBuilder == null) { delimitStringBuilder = new StringBuilder(item.toString()); } else { delimitStringBuilder.append(",").append(item.toString()); } } } if (delimitStringBuilder != null) { delimitedSetString = delimitStringBuilder.toString(); } } return delimitedSetString; } protected int getAssetPairScale(Instrument instrument) throws IOException { // get decimal precision scale CurrencyPair cp = (CurrencyPair) instrument; Map<String, KrakenAssetPair> assetPairMap = kraken.getAssetPairs(cp.toString()).getResult(); KrakenAssetPair assetPair = assetPairMap.get(cp.toString()); int scale = assetPair.getPairScale(); return scale; } }
mit
umasteeringgroup/UMA
UMAProject/Assets/UMA/Examples/Physics Examples/Scripts/CursorLock.cs
320
using UnityEngine; using System.Collections; namespace UMA.Dynamics.Examples { public class CursorLock : MonoBehaviour { void OnApplicationFocus(bool hasFocus ) { if( hasFocus ) LockMouse (); } void LockMouse() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } }
mit
TradeMe/PlayMe
PlayMe.Server/Helpers/VetoHelperRules/AlreadyVetoedTrackVetoRule.cs
428
using System.Linq; using PlayMe.Common.Model; using PlayMe.Server.Helpers.Interfaces; using PlayMe.Server.Helpers.VetoHelperRules.Interfaces; namespace PlayMe.Server.Helpers.VetoHelperRules { public class AlreadyVetoedTrackVetoRule : IVetoRule { public bool CantVetoTrack(string vetoedByUser, QueuedTrack track) { return track.Vetoes.Any(v => v.ByUser == vetoedByUser); } } }
mit
SWE574-Groupago/heritago
Heritandroid/app/src/main/java/com/heritago/heritandroid/fragments/LoginFragment.java
2075
package com.heritago.heritandroid.fragments; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import com.heritago.heritandroid.R; import com.heritago.heritandroid.bus.BusProvider; import com.heritago.heritandroid.bus.DidLoginEvent; import static android.content.Context.INPUT_METHOD_SERVICE; /** * Created by onurtokoglu on 14/05/2017. */ public class LoginFragment extends Fragment { EditText username_field; EditText password_field; Button login_button; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_login, container, false); username_field = (EditText) view.findViewById(R.id.username); password_field = (EditText) view.findViewById(R.id.password); login_button = (Button) view.findViewById(R.id.login_button); login_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginClicked(); } }); return view; } public void loginClicked(){ String username = username_field.getText().toString(); String password = password_field.getText().toString(); if (username.equals("") || password.equals("")){ return; } //TODO: check login InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); BusProvider.getInstance().post(new DidLoginEvent()); } }
mit
develar/electron-builder
packages/builder-util-runtime/src/uuid.ts
5393
import { createHash, randomBytes } from "crypto" import { newError } from "./index" const invalidName = "options.name must be either a string or a Buffer" // Node ID according to rfc4122#section-4.5 const randomHost = randomBytes(16) randomHost[0] = randomHost[0] | 0x01 // lookup table hex to byte const hex2byte: any = {} // lookup table byte to hex const byte2hex: Array<string> = [] // populate lookup tables for (let i = 0; i < 256; i++) { const hex = (i + 0x100).toString(16).substr(1) hex2byte[hex] = i byte2hex[i] = hex } // UUID class export class UUID { private ascii: string | null = null private readonly binary: Buffer | null = null private readonly version: number // from rfc4122#appendix-C static readonly OID = UUID.parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8") constructor(uuid: Buffer | string) { const check = UUID.check(uuid) if (!check) { throw new Error("not a UUID") } this.version = check.version! if (check.format === "ascii") { this.ascii = uuid as string } else { this.binary = uuid as Buffer } } static v5(name: string | Buffer, namespace: Buffer) { return uuidNamed(name, "sha1", 0x50, namespace) } toString() { if (this.ascii == null) { this.ascii = stringify(this.binary!) } return this.ascii } inspect() { return `UUID v${this.version} ${this.toString()}` } static check(uuid: Buffer | string, offset = 0) { if (typeof uuid === "string") { uuid = uuid.toLowerCase() if (!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-([a-f0-9]{12})$/.test(uuid)) { return false } if (uuid === "00000000-0000-0000-0000-000000000000") { return { version: undefined, variant: "nil", format: "ascii" } } return { version: (hex2byte[uuid[14] + uuid[15]] & 0xf0) >> 4, variant: getVariant((hex2byte[uuid[19] + uuid[20]] & 0xe0) >> 5), format: "ascii", } } if (Buffer.isBuffer(uuid)) { if (uuid.length < offset + 16) { return false } let i = 0 for (; i < 16; i++) { if (uuid[offset + i] !== 0) { break } } if (i === 16) { return { version: undefined, variant: "nil", format: "binary" } } return { version: (uuid[offset + 6] & 0xf0) >> 4, variant: getVariant((uuid[offset + 8] & 0xe0) >> 5), format: "binary", } } throw newError("Unknown type of uuid", "ERR_UNKNOWN_UUID_TYPE") } // read stringified uuid into a Buffer static parse(input: string) { const buffer = Buffer.allocUnsafe(16) let j = 0 for (let i = 0; i < 16; i++) { buffer[i] = hex2byte[input[j++] + input[j++]] if (i === 3 || i === 5 || i === 7 || i === 9) { j += 1 } } return buffer } } // according to rfc4122#section-4.1.1 function getVariant(bits: number) { switch (bits) { case 0: case 1: case 3: return "ncs" case 4: case 5: return "rfc4122" case 6: return "microsoft" default: return "future" } } enum UuidEncoding { ASCII, BINARY, OBJECT, } // v3 + v5 function uuidNamed(name: string | Buffer, hashMethod: string, version: number, namespace: Buffer, encoding: UuidEncoding = UuidEncoding.ASCII) { const hash = createHash(hashMethod) const nameIsNotAString = typeof name !== "string" if (nameIsNotAString && !Buffer.isBuffer(name)) { throw newError(invalidName, "ERR_INVALID_UUID_NAME") } hash.update(namespace) hash.update(name) const buffer = hash.digest() let result: any switch (encoding) { case UuidEncoding.BINARY: buffer[6] = (buffer[6] & 0x0f) | version buffer[8] = (buffer[8] & 0x3f) | 0x80 result = buffer break case UuidEncoding.OBJECT: buffer[6] = (buffer[6] & 0x0f) | version buffer[8] = (buffer[8] & 0x3f) | 0x80 result = new UUID(buffer) break default: result = byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[(buffer[6] & 0x0f) | version] + byte2hex[buffer[7]] + "-" + byte2hex[(buffer[8] & 0x3f) | 0x80] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]] break } return result } function stringify(buffer: Buffer) { return ( byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[buffer[6]] + byte2hex[buffer[7]] + "-" + byte2hex[buffer[8]] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]] ) } // according to rfc4122#section-4.1.7 export const nil = new UUID("00000000-0000-0000-0000-000000000000") // UUID.v4 = uuidRandom // UUID.v4fast = uuidRandomFast // UUID.v3 = function(options, callback) { // return uuidNamed("md5", 0x30, options, callback) // }
mit
kaw3939/Open-Vote
node_modules/mongoose/test/types.array.test.js
19603
/** * Module dependencies. */ var start = require('./common') , should = require('should') , mongoose = require('./common').mongoose , Schema = mongoose.Schema , random = require('../lib/utils').random , MongooseArray = mongoose.Types.Array; var User = new Schema({ name: String , pets: [Schema.ObjectId] }); mongoose.model('User', User); var Pet = new Schema({ name: String }); mongoose.model('Pet', Pet); /** * Test. */ module.exports = { 'test that a mongoose array behaves and quacks like an array': function(){ var a = new MongooseArray; a.should.be.an.instanceof(Array); a.should.be.an.instanceof(MongooseArray); Array.isArray(a).should.be.true; ;(a._atomics.constructor).should.eql(Object); }, 'doAtomics does not throw': function () { var b = new MongooseArray([12,3,4,5]).filter(Boolean); var threw = false; try { b.doAtomics } catch (_) { threw = true; } threw.should.be.false; var a = new MongooseArray([67,8]).filter(Boolean); try { a.push(3,4); } catch (_) { console.error(_); threw = true; } threw.should.be.false; }, 'test indexOf()': function(){ var db = start() , User = db.model('User', 'users_' + random()) , Pet = db.model('Pet', 'pets' + random()); var tj = new User({ name: 'tj' }) , tobi = new Pet({ name: 'tobi' }) , loki = new Pet({ name: 'loki' }) , jane = new Pet({ name: 'jane' }) , pets = []; tj.pets.push(tobi); tj.pets.push(loki); tj.pets.push(jane); var pending = 3; ;[tobi, loki, jane].forEach(function(pet){ pet.save(function(){ --pending || done(); }); }); function done() { Pet.find({}, function(err, pets){ tj.save(function(err){ User.findOne({ name: 'tj' }, function(err, user){ db.close(); should.equal(null, err, 'error in callback'); user.pets.should.have.length(3); user.pets.indexOf(tobi.id).should.equal(0); user.pets.indexOf(loki.id).should.equal(1); user.pets.indexOf(jane.id).should.equal(2); user.pets.indexOf(tobi._id).should.equal(0); user.pets.indexOf(loki._id).should.equal(1); user.pets.indexOf(jane._id).should.equal(2); }); }); }); } }, 'test #splice() with numbers': function () { var collection = 'splicetest-number' + random(); var db = start() , schema = new Schema({ numbers: Array }) , A = db.model('splicetestNumber', schema, collection); var a = new A({ numbers: [4,5,6,7] }); a.save(function (err) { should.equal(null, err, 'could not save splice test'); A.findById(a._id, function (err, doc) { should.equal(null, err, 'error finding splice doc'); var removed = doc.numbers.splice(1, 1); removed.should.eql([5]); doc.numbers.toObject().should.eql([4,6,7]); doc.save(function (err) { should.equal(null, err, 'could not save splice test'); A.findById(a._id, function (err, doc) { should.equal(null, err, 'error finding splice doc'); doc.numbers.toObject().should.eql([4,6,7]); A.collection.drop(function (err) { db.close(); should.strictEqual(err, null); }); }); }); }); }); }, 'test #splice() on embedded docs': function () { var collection = 'splicetest-embeddeddocs' + random(); var db = start() , schema = new Schema({ types: [new Schema({ type: String }) ]}) , A = db.model('splicetestEmbeddedDoc', schema, collection); var a = new A({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] }); a.save(function (err) { should.equal(null, err, 'could not save splice test'); A.findById(a._id, function (err, doc) { should.equal(null, err, 'error finding splice doc'); var removed = doc.types.splice(1, 1); removed.length.should.eql(1); removed[0].type.should.eql('boy'); var obj = doc.types.toObject(); obj[0].type.should.eql('bird'); obj[1].type.should.eql('frog'); obj[2].type.should.eql('cloud'); doc.save(function (err) { should.equal(null, err, 'could not save splice test'); A.findById(a._id, function (err, doc) { should.equal(null, err, 'error finding splice doc'); var obj = doc.types.toObject(); obj[0].type.should.eql('bird'); obj[1].type.should.eql('frog'); obj[2].type.should.eql('cloud'); A.collection.drop(function (err) { db.close(); should.strictEqual(err, null); }); }); }); }); }); }, '#unshift': function () { var db = start() , schema = new Schema({ types: [new Schema({ type: String })] , nums: [Number] , strs: [String] }) , A = db.model('unshift', schema, 'unshift'+random()); var a = new A({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] , nums: [1,2,3] , strs: 'one two three'.split(' ') }); a.save(function (err) { should.equal(null, err); A.findById(a._id, function (err, doc) { should.equal(null, err); var tlen = doc.types.unshift({type:'tree'}); var nlen = doc.nums.unshift(0); var slen = doc.strs.unshift('zero'); tlen.should.equal(5); nlen.should.equal(4); slen.should.equal(4); var obj = doc.types.toObject(); obj[0].type.should.eql('tree'); obj[1].type.should.eql('bird'); obj[2].type.should.eql('boy'); obj[3].type.should.eql('frog'); obj[4].type.should.eql('cloud'); obj = doc.nums.toObject(); obj[0].valueOf().should.equal(0); obj[1].valueOf().should.equal(1); obj[2].valueOf().should.equal(2); obj[3].valueOf().should.equal(3); obj = doc.strs.toObject(); obj[0].should.equal('zero'); obj[1].should.equal('one'); obj[2].should.equal('two'); obj[3].should.equal('three'); doc.save(function (err) { should.equal(null, err); A.findById(a._id, function (err, doc) { should.equal(null, err); var obj = doc.types.toObject(); obj[0].type.should.eql('tree'); obj[1].type.should.eql('bird'); obj[2].type.should.eql('boy'); obj[3].type.should.eql('frog'); obj[4].type.should.eql('cloud'); obj = doc.nums.toObject(); obj[0].valueOf().should.equal(0); obj[1].valueOf().should.equal(1); obj[2].valueOf().should.equal(2); obj[3].valueOf().should.equal(3); obj = doc.strs.toObject(); obj[0].should.equal('zero'); obj[1].should.equal('one'); obj[2].should.equal('two'); obj[3].should.equal('three'); A.collection.drop(function (err) { db.close(); should.strictEqual(err, null); }); }); }); }); }); }, '#pull': function () { var db= start(); var catschema = new Schema({ name: String }) var Cat = db.model('Cat', catschema); var schema = new Schema({ a: [{ type: Schema.ObjectId, ref: 'Cat' }] }); var A = db.model('TestPull', schema); var cat = new Cat({ name: 'peanut' }); cat.save(function (err) { should.strictEqual(null, err); var a = new A({ a: [cat._id] }); a.save(function (err) { should.strictEqual(null, err); A.findById(a, function (err, doc) { db.close(); should.strictEqual(null, err); doc.a.length.should.equal(1); doc.a.pull(cat.id); doc.a.length.should.equal(0); }); }); }); }, '#addToSet': function () { var db = start() , e = new Schema({ name: String, arr: [] }) , schema = new Schema({ num: [Number] , str: [String] , doc: [e] , date: [Date] , id: [Schema.ObjectId] }); var M = db.model('testAddToSet', schema); var m = new M; m.num.push(1,2,3); m.str.push('one','two','tres'); m.doc.push({ name: 'Dubstep', arr: [1] }, { name: 'Polka', arr: [{ x: 3 }]}); var d1 = new Date; var d2 = new Date( +d1 + 60000); var d3 = new Date( +d1 + 30000); var d4 = new Date( +d1 + 20000); var d5 = new Date( +d1 + 90000); var d6 = new Date( +d1 + 10000); m.date.push(d1, d2); var id1 = new mongoose.Types.ObjectId; var id2 = new mongoose.Types.ObjectId; var id3 = new mongoose.Types.ObjectId; var id4 = new mongoose.Types.ObjectId; var id5 = new mongoose.Types.ObjectId; var id6 = new mongoose.Types.ObjectId; m.id.push(id1, id2); m.num.addToSet(3,4,5); m.num.length.should.equal(5); m.str.$addToSet('four', 'five', 'two'); m.str.length.should.equal(5); m.id.addToSet(id2, id3); m.id.length.should.equal(3); m.doc.$addToSet(m.doc[0]); m.doc.length.should.equal(2); m.doc.$addToSet({ name: 'Waltz', arr: [1] }, m.doc[0]); m.doc.length.should.equal(3); m.date.length.should.equal(2); m.date.$addToSet(d1); m.date.length.should.equal(2); m.date.addToSet(d3); m.date.length.should.equal(3); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { should.strictEqual(null, err); m.num.length.should.equal(5); (~m.num.indexOf(1)).should.be.ok; (~m.num.indexOf(2)).should.be.ok; (~m.num.indexOf(3)).should.be.ok; (~m.num.indexOf(4)).should.be.ok; (~m.num.indexOf(5)).should.be.ok; m.str.length.should.equal(5); (~m.str.indexOf('one')).should.be.ok; (~m.str.indexOf('two')).should.be.ok; (~m.str.indexOf('tres')).should.be.ok; (~m.str.indexOf('four')).should.be.ok; (~m.str.indexOf('five')).should.be.ok; m.id.length.should.equal(3); (~m.id.indexOf(id1)).should.be.ok; (~m.id.indexOf(id2)).should.be.ok; (~m.id.indexOf(id3)).should.be.ok; m.date.length.should.equal(3); (~m.date.indexOf(d1.toString())).should.be.ok; (~m.date.indexOf(d2.toString())).should.be.ok; (~m.date.indexOf(d3.toString())).should.be.ok; m.doc.length.should.equal(3); m.doc.some(function(v){return v.name === 'Waltz'}).should.be.ok m.doc.some(function(v){return v.name === 'Dubstep'}).should.be.ok m.doc.some(function(v){return v.name === 'Polka'}).should.be.ok // test single $addToSet m.num.addToSet(3,4,5,6); m.num.length.should.equal(6); m.str.$addToSet('four', 'five', 'two', 'six'); m.str.length.should.equal(6); m.id.addToSet(id2, id3, id4); m.id.length.should.equal(4); m.date.$addToSet(d1, d3, d4); m.date.length.should.equal(4); m.doc.$addToSet(m.doc[0], { name: '8bit' }); m.doc.length.should.equal(4); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { should.strictEqual(null, err); m.num.length.should.equal(6); (~m.num.indexOf(1)).should.be.ok; (~m.num.indexOf(2)).should.be.ok; (~m.num.indexOf(3)).should.be.ok; (~m.num.indexOf(4)).should.be.ok; (~m.num.indexOf(5)).should.be.ok; (~m.num.indexOf(6)).should.be.ok; m.str.length.should.equal(6); (~m.str.indexOf('one')).should.be.ok; (~m.str.indexOf('two')).should.be.ok; (~m.str.indexOf('tres')).should.be.ok; (~m.str.indexOf('four')).should.be.ok; (~m.str.indexOf('five')).should.be.ok; (~m.str.indexOf('six')).should.be.ok; m.id.length.should.equal(4); (~m.id.indexOf(id1)).should.be.ok; (~m.id.indexOf(id2)).should.be.ok; (~m.id.indexOf(id3)).should.be.ok; (~m.id.indexOf(id4)).should.be.ok; m.date.length.should.equal(4); (~m.date.indexOf(d1.toString())).should.be.ok; (~m.date.indexOf(d2.toString())).should.be.ok; (~m.date.indexOf(d3.toString())).should.be.ok; (~m.date.indexOf(d4.toString())).should.be.ok; m.doc.length.should.equal(4); m.doc.some(function(v){return v.name === 'Waltz'}).should.be.ok m.doc.some(function(v){return v.name === 'Dubstep'}).should.be.ok m.doc.some(function(v){return v.name === 'Polka'}).should.be.ok m.doc.some(function(v){return v.name === '8bit'}).should.be.ok // test multiple $addToSet m.num.addToSet(7,8); m.num.length.should.equal(8); m.str.$addToSet('seven', 'eight'); m.str.length.should.equal(8); m.id.addToSet(id5, id6); m.id.length.should.equal(6); m.date.$addToSet(d5, d6); m.date.length.should.equal(6); m.doc.$addToSet(m.doc[1], { name: 'BigBeat' }, { name: 'Funk' }); m.doc.length.should.equal(6); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { db.close(); should.strictEqual(null, err); m.num.length.should.equal(8); (~m.num.indexOf(1)).should.be.ok; (~m.num.indexOf(2)).should.be.ok; (~m.num.indexOf(3)).should.be.ok; (~m.num.indexOf(4)).should.be.ok; (~m.num.indexOf(5)).should.be.ok; (~m.num.indexOf(6)).should.be.ok; (~m.num.indexOf(7)).should.be.ok; (~m.num.indexOf(8)).should.be.ok; m.str.length.should.equal(8); (~m.str.indexOf('one')).should.be.ok; (~m.str.indexOf('two')).should.be.ok; (~m.str.indexOf('tres')).should.be.ok; (~m.str.indexOf('four')).should.be.ok; (~m.str.indexOf('five')).should.be.ok; (~m.str.indexOf('six')).should.be.ok; (~m.str.indexOf('seven')).should.be.ok; (~m.str.indexOf('eight')).should.be.ok; m.id.length.should.equal(6); (~m.id.indexOf(id1)).should.be.ok; (~m.id.indexOf(id2)).should.be.ok; (~m.id.indexOf(id3)).should.be.ok; (~m.id.indexOf(id4)).should.be.ok; (~m.id.indexOf(id5)).should.be.ok; (~m.id.indexOf(id6)).should.be.ok; m.date.length.should.equal(6); (~m.date.indexOf(d1.toString())).should.be.ok; (~m.date.indexOf(d2.toString())).should.be.ok; (~m.date.indexOf(d3.toString())).should.be.ok; (~m.date.indexOf(d4.toString())).should.be.ok; (~m.date.indexOf(d5.toString())).should.be.ok; (~m.date.indexOf(d6.toString())).should.be.ok; m.doc.length.should.equal(6); m.doc.some(function(v){return v.name === 'Waltz'}).should.be.ok m.doc.some(function(v){return v.name === 'Dubstep'}).should.be.ok m.doc.some(function(v){return v.name === 'Polka'}).should.be.ok m.doc.some(function(v){return v.name === '8bit'}).should.be.ok m.doc.some(function(v){return v.name === 'BigBeat'}).should.be.ok m.doc.some(function(v){return v.name === 'Funk'}).should.be.ok }); }); }); }); }); }); }, 'setting doc array should adjust path positions': function () { var db = start(); var D = db.model('subDocPositions', new Schema({ em1: [new Schema({ name: String })] })); var d = new D({ em1: [ { name: 'pos0' } , { name: 'pos1' } , { name: 'pos2' } ] }); d.save(function (err) { should.strictEqual(null, err); D.findById(d, function (err, d) { should.strictEqual(null, err); var n = d.em1.slice(); n[2].name = 'position two'; var x = []; x[1] = n[2]; x[2] = n[1]; x = x.filter(Boolean); d.em1 = x; d.save(function (err) { should.strictEqual(null, err); D.findById(d, function (err, d) { db.close(); should.strictEqual(null, err); d.em1[0].name.should.eql('position two'); d.em1[1].name.should.eql('pos1'); }); }); }); }); }, 'paths with similar names should be saved': function () { var db = start(); var D = db.model('similarPathNames', new Schema({ account: { role: String , roles: [String] } , em: [new Schema({ name: String })] })); var d = new D({ account: { role: 'teacher', roles: ['teacher', 'admin'] } , em: [{ name: 'bob' }] }); d.save(function (err) { should.strictEqual(null, err); D.findById(d, function (err, d) { should.strictEqual(null, err); d.account.role = 'president'; d.account.roles = ['president', 'janitor']; d.em[0].name = 'memorable'; d.em = [{ name: 'frida' }]; d.save(function (err) { should.strictEqual(null, err); D.findById(d, function (err, d) { db.close(); should.strictEqual(null, err); d.account.role.should.equal('president'); d.account.roles.length.should.equal(2); d.account.roles[0].should.equal('president'); d.account.roles[1].should.equal('janitor'); d.em.length.should.equal(1); d.em[0].name.should.equal('frida'); }); }); }); }); }, // gh-842 'modifying sub-doc properties and manipulating the array works': function () { var db= start(); var schema = new Schema({ em: [new Schema({ username: String })]}); var M = db.model('modifyingSubDocAndPushing', schema); var m = new M({ em: [ { username: 'Arrietty' }]}); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { should.strictEqual(null, err); m.em[0].username.should.eql('Arrietty'); m.em[0].username = 'Shawn'; m.em.push({ username: 'Homily' }); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { should.strictEqual(null, err); m.em.length.should.equal(2); m.em[0].username.should.eql('Shawn'); m.em[1].username.should.eql('Homily'); m.em[0].username = 'Arrietty'; m.em[1].remove(); m.save(function (err) { should.strictEqual(null, err); M.findById(m, function (err, m) { db.close(); should.strictEqual(null, err); m.em.length.should.equal(1); m.em[0].username.should.eql('Arrietty'); }); }); }); }); }); }); } };
mit
crummel/dotnet_core-setup
src/test/Assets/TestProjects/RuntimeProperties/Program.cs
473
using System; namespace RuntimeProperties { public static class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.WriteLine(string.Join(Environment.NewLine, args)); foreach (string propertyName in args) { Console.WriteLine($"AppContext.GetData({propertyName}) = {System.AppContext.GetData(propertyName)}"); } } } }
mit
shelsonjava/datawrapper
test/api.test.py
4574
# # test script for Datawrapper API # import requests import os import json from random import randint import yaml config = yaml.load(open('../config.yaml').read()) domain = 'http://' + config['domain'] if 'DATAWRAPPER_DOMAIN' in os.environ: domain = os.environ['DATAWRAPPER_DOMAIN'] endpoint = domain + '/api/' import unittest print 'testing on ' + domain ns = { 'chartId': None, 'session': requests.Session() } # create new chart class TestDatawrapperAPI(unittest.TestCase): def checkRes(self, r): self.assertIsInstance(r.json(), dict) self.assertEqual(r.json()['status'], 'ok') if r.json()['status'] == 'error': print r.json()['message'] def test_01_create_new_chart(self): global ns r = ns['session'].post(endpoint + 'charts') self.checkRes(r) ns['chartId'] = r.json()['data'][0]['id'] def test_02_set_chart_data(self): data = 'some,data,to,send\nanother,row,to,send\n' url = endpoint + 'charts/%s/data' % ns['chartId'] r = ns['session'].put(url, data=data) self.checkRes(r) # check that data was set correctly r = ns['session'].get(url) self.assertEqual(r.text, data) def test_03_upload_chart_data(self): files = {'qqfile': ( 'report.csv', 'other,data,to,send\nanother,row,to,send\n')} url = endpoint + 'charts/%s/data' % ns['chartId'] r = ns['session'].post(url, files=files) self.checkRes(r) # check that data was set correctly r = ns['session'].get(url) self.assertEqual(r.text, files['qqfile'][1]) def test_04_get_chart_meta(self): url = endpoint + 'charts/%s' % ns['chartId'] r = ns['session'].get(url) self.checkRes(r) gallery_default = False if 'defaults' in config and 'show_in_gallery' in config['defaults']: gallery_default = config['defaults']['show_in_gallery'] self.assertEqual(r.json()['data']['showInGallery'], gallery_default) def test_05_saveMetadata(self): url = endpoint + 'charts/%s' % ns['chartId'] r = ns['session'].get(url) self.checkRes(r) data = r.json()['data'] data['title'] = 'My cool new chart' data['metadata']['describe']['source-name'] = 'Example Data Source' data['metadata']['describe']['source-url'] = 'http://example.org' r = ns['session'].put(url, data=json.dumps(data)) self.checkRes(r) # self.assertEqual(r.json()['data']['showInGallery'], False) def test_06_gallery(self): url = endpoint + 'gallery' r = ns['session'].get(url) self.checkRes(r) def test_06_visualizations(self): url = endpoint + 'visualizations' r = ns['session'].get(url) self.checkRes(r) self.assertIsInstance(r.json()['data'], list) def test_07_bar_chart(self): url = endpoint + 'visualizations/bar-chart' r = ns['session'].get(url) self.checkRes(r) self.assertIsInstance(r.json()['data'], dict) def test_08_account(self): url = endpoint + 'account' r = ns['session'].get(url) self.checkRes(r) self.assertIn('user', r.json()['data']) self.assertIsInstance(r.json()['data']['user'], dict) def test_09_set_lang_to_fr(self): url = endpoint + 'account/lang' r = ns['session'].put(url, data=json.dumps(dict(lang='fr'))) self.checkRes(r) def test_10_check_lang_is_fr(self): url = endpoint + 'account/lang' r = ns['session'].get(url) self.checkRes(r) self.assertEqual(r.json()['data'], 'fr') def test_11_charts(self): url = endpoint + 'charts' r = ns['session'].get(url) self.checkRes(r) self.assertEqual(len(r.json()['data']), 1) def test_11a_charts_sorted(self): url = endpoint + 'charts?order=theme' r = ns['session'].get(url) self.checkRes(r) self.assertEqual(len(r.json()['data']), 1) def test_12_estimate_job(self): url = endpoint + 'jobs/export/estimate' r = ns['session'].get(url) self.checkRes(r) def test_13_create_user(self): url = endpoint + '/users' password = '1234' body = dict(pwd=password, pwd2=password, email=('test-%d@' + config['domain']) % randint(10000, 99999)) r = ns['session'].post(url, data=json.dumps(body)) self.checkRes(r) if __name__ == '__main__': unittest.main()
mit
msimerson/Haraka
tests/fixtures/vm_harness.js
1742
const fs = require('fs'); const path = require('path'); const vm = require('vm'); function dot_files (element) { return element.match(/^\./) == null; } exports.sandbox_require = id => { if (id[0] == '.' && id[1] != '.') { let override; try { override = path.join(__dirname, `${id}.js`); fs.statSync(override); id = override; } catch (e) { try { override = path.join(__dirname, '..', '..', 'outbound', `${id.replace(/^[./]*/, '')}.js`); fs.statSync(override); id = override; } catch (err) { id = `../../${ id.replace(/^[./]*/, '')}`; } } } else if (id[0] == '.' && id[1] == '.') { id = `../../${ id.replace(/^[./]*/, '')}`; } return require(id); } function make_test (module_path, test_path, additional_sandbox) { return test => { let code = fs.readFileSync(module_path); code += fs.readFileSync(test_path); const sandbox = { require: exports.sandbox_require, console, Buffer, exports: {}, test }; Object.keys(additional_sandbox).forEach(k => { sandbox[k] = additional_sandbox[k]; }); vm.runInNewContext(code, sandbox); }; } exports.add_tests = (module_path, tests_path, test_exports, add_to_sandbox) => { const additional_sandbox = add_to_sandbox || {}; const tests = fs.readdirSync(tests_path).filter(dot_files); for (let x = 0; x < tests.length; x++) { test_exports[tests[x]] = make_test(module_path, tests_path + tests[x], additional_sandbox); } }
mit
megawac/ramda
test/substringFrom.js
409
var assert = require('assert'); var R = require('..'); describe('substringFrom', function() { it('returns the trailing substring of a string', function() { assert.strictEqual(R.substringFrom(8, 'abcdefghijklm'), 'ijklm'); }); it('is automatically curried', function() { var after8 = R.substringFrom(8); assert.strictEqual(after8('abcdefghijklm'), 'ijklm'); }); });
mit
PreserveLafayette/PreserveLafayette
themes/amnhedu/views/Splash/splash_html.php
9129
<div id="splashBrowsePanel" class="browseSelectPanel" style="z-index:1000;"> <a href="#" onclick="caUIBrowsePanel.hideBrowsePanel()" class="browseSelectPanelButton"></a> <div id="splashBrowsePanelContent"> </div> </div> <script type="text/javascript"> var caUIBrowsePanel = caUI.initBrowsePanel({ facetUrl: '<?php print caNavUrl($this->request, '', 'Browse', 'getFacet'); ?>'}); </script> <div id="hpText"> <?php print $this->render('Splash/splash_intro_text_html.php'); ?> <div class="hpRss"><?php print caNavLink($this->request, '<img src="'.$this->request->getThemeUrlPath(true).'/graphics/feed.gif" border="0" title="'._t('Get alerted to newly added items by RSS').'" width="14" height="14"/> '._t('Get alerted to newly added items by RSS'), 'caption', '', 'Feed', 'recentlyAdded'); ?></div> </div> <div id="hpFeatured"> <div class="title"><?php print _t("Natural History"); ?></div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"> <div id="hpSlider"> <?php print caNavLink($this->request, $this->getVar("featured_content_widesplash"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("featured_content_id"))); ?> </div> <div id="naturalBrowse"> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/171/mod_id/0">Birds</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/172/mod_id/0">Mammals</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/173/mod_id/0">Fish</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/174/mod_id/0">Marine Invertebrates</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/175/mod_id/0">Insects</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/176/mod_id/0">Reptiles</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/177/mod_id/0">Rocks and Minerals</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/178/mod_id/0">Soils</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/179/mod_id/0">Meteorites</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/184/mod_id/0">Plants</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/181/mod_id/0">Plant Fossils</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/182/mod_id/0">Animal Fossils</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/183/mod_id/0">Trace Fossils</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/180/mod_id/0">Skeletons</a> </div> </td></tr></table> </div> <div id="hpFeatured2"> <div class="title"><?php print _t("Cultural History"); ?></div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"> <div id="hpSlider2"> <?php print caNavLink($this->request, $this->getVar("culture_content_widesplash"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("culture_content_id"))); ?> </div> <div id="naturalBrowse" style='height:77px;'> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/196/mod_id/0">Jewelry</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/198/mod_id/0">Art</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/191/mod_id/0">Clothing</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/199/mod_id/0">Games</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/189/mod_id/0">Tools</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/190/mod_id/0">Weapons</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/194/mod_id/0">Floral Remains</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/193/mod_id/0">Seeds</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/192/mod_id/0">Shells</a> <a href="/index.php/Browse/modifyCriteria/facet/spec_cat_facet/id/195/mod_id/0">Soil Remains</a> </div> </td></tr></table> </div> <div style="clear:both; height:50px;"></div> <div id="quickLinkItems"> <div class="quickLinkItem"> <div class="title"><?php print _t("Recently Viewed"); ?>:</div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><?php print caNavLink($this->request, $this->getVar("recently_viewed_widepreview"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("recently_viewed_id"))); ?></td></tr></table> <div style="float:right; margin-top:4px;"><?php print caNavLink($this->request, _t("More Items &gt;"), "more", "", "Favorites", "Index"); ?></div> </div> <div class="quickLinkItem"> <div class="title"><?php print _t("Current Temporary Exhibit"); ?>:</div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><?php print caNavLink($this->request, $this->getVar("temp_content_widepreview"), '', 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("temp_set_id"))); ?></td></tr></table> <div style="float:right; margin-top:4px;"><?php print caNavLink($this->request, _t("View Collection &gt;"), "more", 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("temp_set_id"))); ?></div> </div> <div class="quickLinkItem" style="margin-right:0px;"> <div class="title"><?php print _t("Featured Permanent Exhibit"); ?>:</div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><?php print caNavLink($this->request, $this->getVar("perm_content_widepreview"), '', 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("perm_set_id"))); ?></td></tr></table> <div style="float:right; margin-top:4px;"><?php print caNavLink($this->request, _t("View Collection &gt;"), "more", 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("perm_set_id"))); ?></div> </div> <div class="quickLinkItem" style="margin-right:0px;"> <div class="title"><?php print _t("Upcoming Exhibit"); ?>:</div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><?php print caNavLink($this->request, $this->getVar("upcoming_content_widepreview"), '', 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("upcoming_set_id"))); ?></td></tr></table> <div style="float:right; margin-top:4px;"><?php print caNavLink($this->request, _t("View Collection &gt;"), "more", 'simpleGallery', 'Show', 'displaySet', array('set_id' => $this->getVar("upcoming_set_id"))); ?></div> </div> <div class="quickLinkItem" style="margin-right:0px;"> <div class="title"><?php print _t("Recently Added"); ?>:</div> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><?php print caNavLink($this->request, $this->getVar("recently_added_widepreview"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("recently_added_id"))); ?></td></tr></table> <div style="float:right; margin-top:4px;"><?php print caNavLink($this->request, _t("More Items &gt;"), "more", "", "Favorites", "Index"); ?></div> </div> <!-- <div id="hpBrowse"> <div><b><?php print _t("Quickly browse by"); ?>:</b></div> <div style="margin-top:10px;"> <?php $va_facets = $this->getVar('available_facets'); foreach($va_facets as $vs_facet_name => $va_facet_info) { ?> <a href="#" onclick='caUIBrowsePanel.showBrowsePanel("<?php print $vs_facet_name; ?>")'><?php print $va_facet_info['label_plural']; ?></a><br/> <?php } ?> </div> <div style="margin-top:10px;" class="caption"> <?php print _t("Or click \"Browse\" in the navigation bar to do a refined browse"); ?> </div> </div> --> </div><!-- end quickLinkItems --> <?php JavascriptLoadManager::register('cycle'); $t_slider = new ca_sets(); $t_slider->load(array('set_code' => 'siteFeatured')); //$va_items = $t_slider->getItems(array('thumbnailVersions' => array('medium', 'mediumlarge'), 'checkAccess' => $va_access_values)); $va_images = $t_slider->getRepresentationTags('widesplash', array('checkAccess' => $va_access_values, 'quote' => true)); $t_slider = new ca_sets(); $t_slider->load(array('set_code' => 'cultureFeatured')); //$va_items = $t_slider->getItems(array('thumbnailVersions' => array('medium', 'mediumlarge'), 'checkAccess' => $va_access_values)); $va_images2 = $t_slider->getRepresentationTags('widesplash', array('checkAccess' => $va_access_values, 'quote' => true)); ?> <script type="text/javascript"> caUI.initCycle('#hpSlider', { fx: 'fade', imageList: [ <?php print join(",\n", $va_images); ?> ], duration: 30000, rewindDuration: 30000, delay: -1500, repetitions: 5 }); </script> <script type="text/javascript"> caUI.initCycle('#hpSlider2', { fx: 'fade', imageList: [ <?php print join(",\n", $va_images2); ?> ], duration: 30000, rewindDuration: 30000, repetitions: 5 }); </script>
mit
magul/volontulo
backend/volontulo_org/settings/dev_local.py
174
""" Development Settings Module """ from .dev import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } }
mit
Ubuntu-Solutions-Engineering/conjure
conjureup/controllers/base/spellpicker/gui.py
2128
import os from conjureup import controllers, utils from conjureup.app_config import app from conjureup.download import EndpointType, download_local from conjureup.models.addon import AddonModel from conjureup.models.step import StepModel from conjureup.ui.views.spellpicker import SpellPickerView class SpellPickerController: def finish(self, spellname): if spellname != app.config.get('spell'): utils.set_terminal_title("conjure-up {}".format(spellname)) utils.set_chosen_spell(spellname, os.path.join(app.conjurefile['cache-dir'], spellname)) download_local(os.path.join(app.config['spells-dir'], spellname), app.config['spell-dir']) utils.set_spell_metadata() StepModel.load_spell_steps() AddonModel.load_spell_addons() controllers.setup_metadata_controller() return controllers.use('addons').render() def render(self): spells = [] if app.endpoint_type is None: spells += utils.find_spells() elif app.endpoint_type == EndpointType.LOCAL_SEARCH: spells = utils.find_spells_matching(app.conjurefile['spell']) else: raise Exception("Unexpected endpoint type {}".format( app.endpoint_type)) # add subdir of spells-dir to spell dict for bundle readme view: for category, spell in spells: spell['spell-dir'] = os.path.join(app.config['spells-dir'], spell['key']) def spellcatsorter(t): cat = t[0] name = t[1]['name'] if cat == '_unassigned_spells': return ('z', name) return (cat, name) view = SpellPickerView(app, sorted(spells, key=spellcatsorter), self.finish) view.show() _controller_class = SpellPickerController
mit
brandonsilver/jekyll-polymer
app/_plugins/to_gravatar.rb
707
# Automatically pull Gravatar images using an author's email address # Taken from: https://blog.sorryapp.com/blogging-with-jekyll/2014/02/13/add-author-gravatars-to-your-jekyll-site.html require 'digest/md5' module Jekyll module GravatarFilter def to_gravatar(input, size=32) def_img = Jekyll.configuration({})['url'] + Jekyll.configuration({})['baseurl'] + '/images/default-gravatar.png' "//www.gravatar.com/avatar/#{hash(input)}?s=#{size}&default=" + def_img end private :hash def hash(email) email_address = email ? email.downcase.strip : '' Digest::MD5.hexdigest(email_address) end end end Liquid::Template.register_filter(Jekyll::GravatarFilter)
mit
sandman8654/OpenStudent
db/migrate/20160204001545_add_permissions_fields_for_educators.rb
290
class AddPermissionsFieldsForEducators < ActiveRecord::Migration def change add_column :educators, :schoolwide_access, :boolean, default: false add_column :educators, :grade_level_access, :string, array: true add_index :educators, :grade_level_access, using: 'gin' end end
mit
jeraldfeller/jbenterprises
google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201609/cm/AdServingOptimizationStatus.php
394
<?php namespace Google\AdsApi\AdWords\v201609\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class AdServingOptimizationStatus { const OPTIMIZE = 'OPTIMIZE'; const CONVERSION_OPTIMIZE = 'CONVERSION_OPTIMIZE'; const ROTATE = 'ROTATE'; const ROTATE_INDEFINITELY = 'ROTATE_INDEFINITELY'; const UNAVAILABLE = 'UNAVAILABLE'; const UNKNOWN = 'UNKNOWN'; }
mit
deliberryeng/elcodi
src/Elcodi/Component/Zone/Factory/ZoneFactory.php
1060
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Component\Zone\Factory; use Elcodi\Component\Core\Factory\Abstracts\AbstractFactory; use Elcodi\Component\Zone\Entity\Zone; /** * Factory for Zone entities */ class ZoneFactory extends AbstractFactory { /** * Creates an Zone instance * * @return Zone New Zone entity */ public function create() { /** * @var Zone $zone */ $classNamespace = $this->getEntityNamespace(); $zone = new $classNamespace(); $zone ->setLocations([]) ->setEnabled(true) ->setCreatedAt($this->now()); return $zone; } }
mit
Moult/usydarchexhibition-cavis
spec/Cavis/Core/Usecase/Image/View/Interactor.php
725
<?php namespace spec\Cavis\Core\Usecase\Image\View; use PHPSpec2\ObjectBehavior; class Interactor extends ObjectBehavior { /** * @param Cavis\Core\Data\Image $image * @param Cavis\Core\Usecase\Image\View\Repository $repository */ function let($image, $repository) { $image->id = 42; $this->beConstructedWith($image, $repository); } function it_should_be_initializable() { $this->shouldHaveType('Cavis\Core\Usecase\Image\View\Interactor'); } function it_should_fetch_single_image_data($image, $repository) { $repository->get_all_image_data(42)->shouldBeCalled()->willReturn('foo'); $this->interact()->shouldReturn('foo'); } }
mit
bx5974/sikuli
sikuli-ide/src/main/java/org/sikuli/ide/sikuli_test/TestRunContext.java
533
/* * Copyright 2010-2011, Sikuli.org * Released under the MIT License. * */ package org.sikuli.ide.sikuli_test; import javax.swing.ListModel; import junit.framework.Test; /** * The interface for accessing the Test run context. Test run views * should use this interface rather than accessing the TestRunner * directly. */ public interface TestRunContext { /** * Handles the selection of a Test. */ public void handleTestSelected(Test test); /** * Returns the failure model */ public ListModel getFailures(); }
mit
okyereadugyamfi/softlogik
Backup/SoftLogic.Core/Win/UI/Controls/OutlookStyleNavigateBar/NavigateBarHelper.cs
3220
/* * Project : Outlook 2003 Style Navigation Pane * * Author : Muhammed ŞAHİN * eMail : muhammed.sahin@gmail.com * * Description : NavigateBar helper methods * */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace SoftLogik.Win.UI.Controls.OutlookStyleNavigateBar { class NavigateBarHelper { #region PaintGradientControl /// <summary> /// Paint gradient /// </summary> /// <param name="tControl">Painting control</param> /// <param name="tLightColor">Light Color</param> /// <param name="tDarkColor">Dark Color</param> public static void PaintGradientControl(Control tControl, Color tLightColor, Color tDarkColor) { NavigateBarHelper.PaintGradientControl(tControl, tLightColor, tDarkColor, NavigateBar.BUTTON_PAINT_ANGLE); } #endregion #region PaintGradientControl /// <summary> /// Paint gradient /// </summary> /// <param name="tControl">Painting control</param> /// <param name="tLightColor">Light Color</param> /// <param name="tDarkColor">Dark Color</param> /// <param name="tAngle">Angle for painting</param> public static void PaintGradientControl(Control tControl, Color tLightColor, Color tDarkColor, float tAngle) { Rectangle r = tControl.ClientRectangle; if (r.Width == 0 || r.Height == 0) return; Graphics g = tControl.CreateGraphics(); using (LinearGradientBrush lgb = new LinearGradientBrush(r, tLightColor, tDarkColor, tAngle)) { g.FillRectangle(lgb, r); } g.Dispose(); } #endregion #region ConvertToGrayscale /// <summary> /// Convert image gray style /// </summary> /// <param name="tSourceBitmap">Bitmap source</param> /// <returns></returns> public static Bitmap ConvertToGrayscale(Bitmap tSourceBitmap) { Bitmap bitmap = new Bitmap(tSourceBitmap.Width, tSourceBitmap.Height); for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { Color color = tSourceBitmap.GetPixel(x, y); int luma = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); bitmap.SetPixel(x, y, Color.FromArgb(luma, luma, luma)); } } bitmap.MakeTransparent(); // Convert transparent return bitmap; } #endregion #region GetVerticalText /// <summary> /// Text ifadeyi dikey konuma getirir. /// </summary> /// <param name="tString">Text</param> /// <returns></returns> public static string GetVerticalText(string tString) { string vertText = ""; foreach (char ch in tString) vertText += ch + "\n\r"; return vertText; } #endregion } }
mit
kidaa/eol
spec/features/communities_spec.rb
10775
require "spec_helper" describe "Communities" do before(:all) do # so this part of the before :all runs only once unless User.find_by_username('communities_scenario') truncate_all_tables load_scenario_with_caching(:communities) @test_data = EOL::TestInfo.load('communities') @collection = Collection.gen @collection.add(User.gen) end end shared_examples_for 'communities all users' do context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } subject { body } it 'should have rel canonical link tag' do should have_tag("link[rel=canonical][href$='#{community_newsfeed_path(@test_data[:community])}']") end it 'should have rel prev and next link tags when appropriate' it 'should show the community name and description' do should have_tag('h1', text: @test_data[:community].name) should have_tag('#page_heading', text: @test_data[:community].description) end it 'should show the collections the community is focused upon' do body.should have_tag('#sidebar') do @test_data[:community].collections.each do |focus| with_tag("a[href='#{collection_path(focus.id)}']", text: /#{focus.name}/) end end end end context 'visiting community members' do before(:each) { visit community_members_path(@test_data[:community]) } subject { body } it 'should have rel canonical link tag' do should have_tag("link[rel=canonical][href$='#{community_members_path(@test_data[:community])}']") end it 'should link to all of the community members' end end shared_examples_for 'communities logged in user' do # Make sure you are logged in prior to calling this shared example group it_should_behave_like 'communities all users' context 'visiting create community' do before(:each) { visit new_community_path(collection_id: @collection.id) } it 'should ask for the new community name and description' do body.should have_tag("input#community_name") body.should have_tag("textarea#community_description") end it 'should create a community, add the user, and redirect to community default view' do new_name = FactoryGirl.generate(:string) new_col_name = FactoryGirl.generate(:string) fill_in('community_name', with: new_name) fill_in('community_description', with: 'This is a long description.') click_button('Create community') new_comm = Community.last new_comm.name.should == new_name new_comm.description.should == 'This is a long description.' current_path.should match /#{community_path(new_comm)}/ end end end shared_examples_for 'community member' do # Make sure you are logged in prior to calling this shared example group it_should_behave_like 'communities logged in user' context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } subject { body } it 'should not show join community link' it 'should show leave community link' end end describe 'anonymous user' do before(:each) do visit logout_path end it_should_behave_like 'communities all users' context 'visiting create community' do it 'should require login' do # TODO - this is wrong; you can't use capybara to test that a CONTROLLER is raising an exception. Move this test to a # controller spec. # lambda { get new_community_path(collection_id: @collection.id) }.should raise_error(EOL::Exceptions::MustBeLoggedIn) pending end end context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } it 'should show a link to join the community' do body.should have_tag("#page_heading") do with_tag("a[href='#{join_community_path(@test_data[:community].id)}']") end end end end describe 'non member' do before(:each) { login_as @test_data[:user_non_member] } it_should_behave_like 'communities logged in user' context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } subject { body } it 'should not show edit community links' do should_not have_tag("a[href='#{edit_community_path(@test_data[:community])}']") end it 'should not show delete community links' do should_not have_tag("a[href='#{community_path(@test_data[:community])}']", text: I18n.t(:delete_community)) end it 'should allow user to join community' do @test_data[:user_non_member].is_member_of?(@test_data[:community]).should_not be_true # href="/communities/2/join?return_to=%2Fcommunities%2F2" should have_tag("a[href='#{join_community_path(@test_data[:community].id)}']") visit(join_community_path(@test_data[:community].id)) @test_data[:user_non_member].reload @test_data[:user_non_member].is_member_of?(@test_data[:community]).should be_true # Clean up - we have tested that a non member can join, we now make them leave @test_data[:user_non_member].leave_community(@test_data[:community]) @test_data[:user_non_member].is_member_of?(@test_data[:community]).should_not be_true end it "should not have a share collection button" do body.should_not have_tag("a[href='#{choose_editor_target_collections_path(community_id: @test_data[:community].id)}']", text: 'Share a collection') end end context 'visiting edit community' do it 'should not be allowed' do lambda { get edit_community_path(@test_data[:community]) }.should raise_error(EOL::Exceptions::SecurityViolation) end end end describe 'community member without community administration privileges' do before(:each) { login_as @test_data[:user_community_member] } it_should_behave_like 'community member' context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } subject { body } it 'should not show an edit community link' do should_not have_tag("a[href='#{edit_community_path(@test_data[:community])}']") end it 'should not show a delete community link' do should_not have_tag("a[href='#{community_path(@test_data[:community])}']", text: I18n.t(:delete_community)) end it 'should not show edit membership links' do should_not have_tag("a[href='#{community_member_path(@test_data[:community], @test_data[:community_member])}']", text: /edit/i) end it 'should not show remove membership links' do should_not have_tag("a[href='#{community_member_path(@test_data[:community], @test_data[:community_member])}']", text: /remove/i) end it 'should allow member to leave community and return to show community' do @test_data[:user_community_member].is_member_of?(@test_data[:community]).should be_true visit(leave_community_path(@test_data[:community].id)) @test_data[:user_community_member].reload @test_data[:user_community_member].is_member_of?(@test_data[:community]).should_not be_true # Clean up - we have tested that a member can leave a community, now we make them join back @test_data[:user_community_member].join_community(@test_data[:community]) @test_data[:user_community_member].is_member_of?(@test_data[:community]).should be_true end it "should not have a share collection button" do body.should_not have_tag("a[href='#{choose_editor_target_collections_path(community_id: @test_data[:community].id)}']", text: 'Share a collection') end end end describe 'community member with community administration privileges' do before(:each) { login_as @test_data[:user_community_administrator] } it_should_behave_like 'community member' context 'visiting show community' do before(:each) { visit community_path(@test_data[:community]) } subject { body } # TODO - we could test a few things here. it "should have a share collection button" do body.should have_tag("a[href='#{choose_editor_target_collections_path(community_id: @test_data[:community].id)}']", text: 'Share a collection') end it "should do allow sharing" do # Give the user a new collection to share: collection = Collection.gen collection.users = [@test_data[:user_community_administrator]] collection.save click_link 'Share a collection' body.should include("Allow #{@test_data[:community].name} to manage the following collections") body.should have_tag("input[type=submit][value='Share a collection']") end end context 'visiting edit community' do before(:each) { visit edit_community_path(@test_data[:community]) } subject { body } it 'should allow editing of name and description' do should have_tag("input#community_name") should have_tag("textarea#community_description") end it 'should allow inviting non-members to join community' do non_member = @test_data[:user_non_member] should have_tag(".edit_community fieldset") do with_tag("dt label", text: "Invite Members") with_tag("input#invitations") fill_in 'invitations', with: non_member.username click_button "save" should include("Community was successfully updated. An invitation was sent to") end end end end # Disabling these in order to be green... can't figure out what causes the login to fail: it 'should flash a link to become a curator, when a non-curator joins the curator community' # do # user = User.gen(curator_level_id: nil) # # TODO - for some odd reason, though the login works, the visit throws a "must be logged in" error. ...Perhaps # # the session is clearing? # login_as user # visit(join_community_url(CuratorCommunity.get)) # page.should have_tag("a[href$='#{curation_privileges_user_path(user)}']") # end it 'should not allow editing the name of the curator community' # do # manager = Member.create(user: User.gen, community: CuratorCommunity.get, manager: true) # # TODO - for some odd reason, though the login works, the visit throws a "must be logged in" error. ...Perhaps # # the session is clearing? # login_as manager.user # visit(edit_community_url(CuratorCommunity.get)) # page.should have_tag("input#community_name[disabled=disabled]") # end end
mit
pg707284828/movie_trailer
movies.py
1497
# Movie class class Movie(): def __init__(self, title, genres, rating, director, actors, poster_image_url, trailer_youtube_url): """Create a new instance of a movie. title: Movie title. genres: List of genres as strings. rating: Rating out of 10. director: Person instance representing the director. actors: List of Person instances representing the actors. poster_image_url: URL of the movie poster. trailer_youtube_url: URL of the trailer on YouTube. """ self.title = title self.genres = genres self.rating = rating self.director = director self.actors = actors self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url def genres_list(self): """Get a comma separated string of genres.""" list = "" for genre in self.genres: list += genre + ", " return list.rstrip(", ") def actors_list(self): """Get a comma separated string of actors.""" list = "" for actor in self.actors: list += actor.name + ", " return list.rstrip(", ") class Person(): def __init__(self, name, dob, image_url): """Create a new person instance. name: Name of the person. dob: Date of birth. image_url: URL of the person image. """ self.name = name self.dob = dob self.image_url = image_url
mit
tkrille/osiam-osiam
src/main/java/org/osiam/resources/scim/Im.java
6312
/** * The MIT License (MIT) * * Copyright (C) 2013-2016 tarent solutions GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.osiam.resources.scim; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotBlank; import java.io.Serializable; /** * This class represents a Im attribute. * <p/> * <p> * For more detailed information please look at the <a * href="http://tools.ietf.org/html/draft-ietf-scim-core-schema-02#section-3.2">SCIM core schema 2.0, section 3.2</a> * </p> */ public final class Im extends MultiValuedAttribute implements Serializable { private static final long serialVersionUID = -6629213491428871065L; private final Type type; /** * Constructor for deserialization, it is not intended for general use. */ @JsonCreator private Im(@JsonProperty("operation") String operation, @JsonProperty("value") String value, @JsonProperty("display") String display, @JsonProperty("primary") boolean primary, @JsonProperty("$ref") String reference, @JsonProperty("type") Type type) { super(operation, value, display, primary, reference); this.type = type; } private Im(Builder builder) { super(builder); this.type = builder.type; } @Override public String getOperation() { return super.getOperation(); } @Override @NotBlank(message = "Multi-Valued attributes may not have empty values") public String getValue() { return super.getValue(); } @Override public String getDisplay() { return super.getDisplay(); } @Override public boolean isPrimary() { return super.isPrimary(); } /** * Gets the type of the attribute. * <p> * For more detailed information please look at the <a href= * "http://tools.ietf.org/html/draft-ietf-scim-core-schema-02#section-3.2" >SCIM core schema 2.0, section 3.2</a> * </p> * * @return the actual type */ public Type getType() { return type; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Im other = (Im) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } @Override public String toString() { return "Im [value=" + getValue() + ", type=" + type + ", primary=" + isPrimary() + ", operation=" + getOperation() + "]"; } /** * Builder class that is used to build {@link Im} instances */ public static class Builder extends MultiValuedAttribute.Builder { private Type type; public Builder() { } /** * builds an Builder based of the given Attribute * * @param im existing Attribute */ public Builder(Im im) { super(im); type = im.type; } @Override public Builder setOperation(String operation) { super.setOperation(operation); return this; } @Override public Builder setDisplay(String display) { super.setDisplay(display); return this; } @Override public Builder setValue(String value) { super.setValue(value); return this; } /** * Sets the label indicating the attribute's function (See {@link Im#getType()}). * * @param type the type of the attribute * @return the builder itself */ public Builder setType(Type type) { this.type = type; return this; } @Override public Builder setPrimary(boolean primary) { super.setPrimary(primary); return this; } @Override public Im build() { return new Im(this); } } /** * Represents an IM type. Canonical values are available as static constants. */ public static class Type extends MultiValuedAttributeType { public static final Type AIM = new Type("aim"); public static final Type GTALK = new Type("gtalk"); public static final Type ICQ = new Type("icq"); public static final Type XMPP = new Type("xmpp"); public static final Type MSN = new Type("msn"); public static final Type SKYPE = new Type("skype"); public static final Type QQ = new Type("qq"); public static final Type YAHOO = new Type("yahoo"); public Type(String value) { super(value); } } }
mit
urukalo/unfinished
application/packages/Admin/tests/Factory/View/Helper/WebAdminUserHelperFactoryTest.php
926
<?php declare(strict_types=1); namespace Admin\Test\Factory\View\Helper; class WebAdminUserHelperFactoryTest extends \PHPUnit_Framework_TestCase { public function testInvokingWebUserHelperShouldReturnWebAdminUserHelper() { $adminUserService = $this->getMockBuilder(\Admin\Service\AdminUserService::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $container = $this->getMockBuilder(\Interop\Container\ContainerInterface::class) ->setMethods(['get']) ->getMockForAbstractClass(); $container->expects(static::at(0)) ->method('get') ->will(static::returnValue($adminUserService)); $webUserHelperFactory = new \Admin\Factory\View\Helper\WebAdminUserHelperFactory(); static::assertInstanceOf(\Admin\View\Helper\WebAdminUserHelper::class, $webUserHelperFactory($container, 'test')); } }
mit
skuid/changelog
vendor/github.com/skuid/spec/selector_set.go
1250
package spec import ( "strings" ) // SelectorSet is a custom flag that takes key-value pairs joined by equal // signs and separated by commas. The flag may be specified multiple times and // the values will be merged. // // Ex: // // mycmd -flag key=value,key2=value2 -flag key3=value3 // // Calling ToMap() results in: // // map[string]string{ // "key": "value", // "key2": "value2", // "key3": "value3", // } // type SelectorSet []string // String satisfies the flag.Value interface func (ss *SelectorSet) String() string { return strings.Join([]string(*ss), ",") } // Set satisfies the flag.Value interface func (ss *SelectorSet) Set(selector string) error { for _, pair := range strings.Split(selector, ",") { if len(pair) > 0 { *ss = append(*ss, pair) } } return nil } // Type returns the type of the flag as a string func (ss *SelectorSet) Type() string { return "string" } // ToMap returns a map representation of the SelectorSet func (ss SelectorSet) ToMap() map[string]string { response := map[string]string{} for _, k := range ss { parts := strings.SplitN(k, "=", 2) if len(parts) > 1 { response[parts[0]] = parts[1] } else { response[parts[0]] = "" } } return response }
mit
jonnybee/csla
Source/Csla.test/PropertyGetSet/BadGetSet.cs
1653
//----------------------------------------------------------------------- // <copyright file="BadGetSet.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Csla; using Csla.Serialization; namespace Csla.Test.PropertyGetSet { #if TESTING [System.Diagnostics.DebuggerNonUserCode] #endif [Serializable] public class BadGetSet : BusinessBase<BadGetSet> { // the registering class is intentionally incorrect for this test private static PropertyInfo<int> IdProperty = RegisterProperty<int>(typeof(EditableGetSet), new PropertyInfo<int>("Id")); public int Id { get { return GetProperty<int>(IdProperty); } set { SetProperty<int>(IdProperty, value); } } } #if TESTING [System.Diagnostics.DebuggerNonUserCode] #endif [Serializable] public class BadGetSetTwo : BusinessBase<BadGetSetTwo> { public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id); public int Id { get { return GetProperty<int>(IdProperty); } set { SetProperty<int>(IdProperty, value); } } // the registering class is intentionally incorrect for this test public static readonly PropertyInfo<int> IdTwoProperty = RegisterProperty<int>(c => c.Id); public int IdTwo { get { return GetProperty<int>(IdTwoProperty); } set { SetProperty<int>(IdTwoProperty, value); } } } }
mit
hi2017teamB/ChatAppProject
dateutil/updatezinfo.py
1674
#!/usr/bin/env python import os import hashlib import json import io from six.moves.urllib import request from six.moves.urllib import error as urllib_error from dateutil.zoneinfo import rebuild METADATA_FILE = "zonefile_metadata.json" def main(): with io.open(METADATA_FILE, 'r') as f: metadata = json.load(f) releases_urls = metadata['releases_url'] if metadata['metadata_version'] < 2.0: # In later versions the releases URL is a mirror URL releases_urls = [releases_urls] if not os.path.isfile(metadata['tzdata_file']): for ii, releases_url in enumerate(releases_urls): print("Downloading tz file from mirror {ii}".format(ii=ii)) try: request.urlretrieve(os.path.join(releases_url, metadata['tzdata_file']), metadata['tzdata_file']) except urllib_error.URLError as e: print("Download failed, trying next mirror.") last_error = e continue last_error = None break if last_error is not None: raise last_error with open(metadata['tzdata_file'], 'rb') as tzfile: sha_hasher = hashlib.sha512() sha_hasher.update(tzfile.read()) sha_512_file = sha_hasher.hexdigest() assert metadata['tzdata_file_sha512'] == sha_512_file, "SHA failed for" print("Updating timezone information...") rebuild.rebuild(metadata['tzdata_file'], zonegroups=metadata['zonegroups'], metadata=metadata) print("Done.") if __name__ == "__main__": main()
mit
etsy/phan
tests/files/src/0434_infer_nested_array_type.php
236
<?php // Should not result in a false positive in this case: function test434() : int { $x = ['key' => ['other' => 'value']]; $x['key']['arrayKey'] = [2]; return count($x['key']['arrayKey']) + strlen($x['key']['other']); }
mit
Elao/curvytron-arcade
src/server/model/Bonus/BonusSelfGodzilla.js
523
/** * Godzilla Bonus * * @param {Array} position */ function BonusSelfGodzilla(position) { BonusSelf.call(this, position); } BonusSelfGodzilla.prototype = Object.create(BonusSelf.prototype); BonusSelfGodzilla.prototype.constructor = BonusSelfGodzilla; /** * Get effects * * @param {Avatar} avatar * * @return {Array} */ BonusSelfGodzilla.prototype.getEffects = function(avatar) { return [ ['invincible', true], ['printing', 100], ['radius', 10], ['velocity', 6] ]; };
mit
tottaz/yggdrasil
app/modules/system/language/finnish/system_lang.php
760
<?php $lang['maintenance:list_label'] = 'Välimuistin ylläpito'; $lang['maintenance:no_items'] = 'Ei välimuisti kansioita'; $lang['maintenance:count_label'] = 'Määrä'; $lang['maintenance:empty_msg'] = '%s merkintä(ä) poistettiin kansiosta %s'; $lang['maintenance:remove_msg'] = 'Kansio %2$s poistettiin'; $lang['maintenance:empty_msg_err'] = 'Virhe tyhjentäessä %s kansiota'; $lang['maintenance:remove_msg_err'] = 'Virhe kansiota %s poistaessa'; $lang['maintenance:export_data'] = 'Vie data'; $lang['maintenance:export_xml'] = 'Vie XML'; $lang['maintenance:export_csv'] = 'Vie CSV'; $lang['maintenance:export_json'] = 'Vie JSON'; $lang['maintenance:table_label'] = 'Taulut'; $lang['maintenance:record_label'] = 'Merkinnät';
mit
blacop/DsCppR
DengJunHuiS/TreeCh/stdafx.cpp
202
// stdafx.cpp : Ö»°üÀ¨±ê×¼°üº¬ÎļþµÄÔ´Îļþ // TreeCh.pch ½«×÷ΪԤ±àÒëÍ· // stdafx.obj ½«°üº¬Ô¤±àÒëÀàÐÍÐÅÏ¢ #include "stdafx.h" // TODO: ÔÚ STDAFX.H ÖÐÒýÓÃÈκÎËùÐèµÄ¸½¼ÓÍ·Îļþ£¬ //¶ø²»ÊÇÔÚ´ËÎļþÖÐÒýÓÃ
mit
danielrozo/cake
src/Cake.Common/Tools/NuGet/Pack/NuspecProcessor.cs
4091
using System.Globalization; using System.Xml; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; namespace Cake.Common.Tools.NuGet.Pack { internal sealed class NuspecProcessor { private readonly IFileSystem _fileSystem; private readonly ICakeEnvironment _environment; private readonly ICakeLog _log; public NuspecProcessor(IFileSystem fileSystem, ICakeEnvironment environment, ICakeLog log) { _fileSystem = fileSystem; _environment = environment; _log = log; } public FilePath Process(NuGetPackSettings settings) { var nuspecFilePath = settings.OutputDirectory .CombineWithFilePath(string.Concat(settings.Id, ".nuspec")) .MakeAbsolute(_environment); var xml = LoadEmptyNuSpec(); return ProcessXml(nuspecFilePath, settings, xml); } public FilePath Process(FilePath nuspecFilePath, NuGetPackSettings settings) { // Make the nuspec file path absolute. nuspecFilePath = nuspecFilePath.MakeAbsolute(_environment); // Make sure the nuspec file exist. var nuspecFile = _fileSystem.GetFile(nuspecFilePath); if (!nuspecFile.Exists) { const string format = "Could not find nuspec file '{0}'."; throw new CakeException(string.Format(CultureInfo.InvariantCulture, format, nuspecFilePath.FullPath)); } // Load the content of the nuspec file. _log.Debug("Parsing nuspec..."); var xml = LoadNuspecXml(nuspecFile); return ProcessXml(nuspecFilePath, settings, xml); } private FilePath ProcessXml(FilePath nuspecFilePath, NuGetPackSettings settings, XmlDocument xml) { // Process the XML. _log.Debug("Transforming nuspec..."); NuspecTransformer.Transform(xml, settings); // Return the file of the new nuspec. _log.Debug("Writing temporary nuspec..."); return SaveNuspecXml(nuspecFilePath, xml); } private static XmlDocument LoadNuspecXml(IFile nuspecFile) { using (var stream = nuspecFile.OpenRead()) { var document = new XmlDocument(); document.Load(stream); return document; } } private static XmlDocument LoadEmptyNuSpec() { XmlDocument xml = new XmlDocument(); xml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <id></id> <version>0.0.0</version> <authors></authors> <description></description> </metadata> <files> </files> </package>"); return xml; } private FilePath SaveNuspecXml(FilePath nuspecFilePath, XmlDocument document) { // Get the new nuspec path. var filename = nuspecFilePath.GetFilename(); filename = filename.ChangeExtension("temp.nuspec"); var resultPath = nuspecFilePath.GetDirectory().GetFilePath(filename).MakeAbsolute(_environment); // Make sure the new nuspec file does not exist. var nuspecFile = _fileSystem.GetFile(resultPath); if (nuspecFile.Exists) { const string format = "Could not create the nuspec file '{0}' since it already exist."; throw new CakeException(string.Format(CultureInfo.InvariantCulture, format, resultPath.FullPath)); } // Now create the file. using (var stream = nuspecFile.OpenWrite()) { document.Save(stream); } // Return the new path. return nuspecFile.Path; } } }
mit
raadhuis/modx-basic
core/components/quip/processors/mgr/comment/delete.class.php
1789
<?php /** * Quip * * Copyright 2010-11 by Shaun McCormick <shaun@modx.com> * * This file is part of Quip, a simple commenting component for MODx Revolution. * * Quip is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Quip is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * Quip; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA * * @package quip */ /** * @package quip * @subpackage processors */ class QuipCommentDeleteProcessor extends modObjectProcessor { public $classKey = 'quipComment'; public $permission = 'quip.comment_remove'; public $languageTopics = array('quip:default'); /** @var quipComment $comment */ public $comment; public function initialize() { $id = $this->getProperty('id'); if (empty($id)) return $this->modx->lexicon('quip.comment_err_ns'); $this->comment = $this->modx->getObject($this->classKey,$id); if (empty($this->comment)) return $this->modx->lexicon('quip.comment_err_nf'); return parent::initialize(); } public function process() { if ($this->comment->delete() === false) { return $this->failure($this->modx->lexicon('quip.comment_err_delete')); } return $this->success(); } } return 'QuipCommentDeleteProcessor';
mit
ChilliConnect/Samples
UnitySamples/FBLeaderboard/Assets/ChilliConnect/GeneratedSource/Errors/SetPushGroupsError.cs
8626
// // This file was auto-generated using the ChilliConnect SDK Generator. // // The MIT License (MIT) // // Copyright (c) 2015 Tag Games Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using SdkCore; namespace ChilliConnect { /// <summary> /// <para>A container for information on any errors that occur during a /// SetPushGroupsRequest.</para> /// /// <para>This is immutable after construction and is therefore thread safe.</para> /// </summary> public sealed class SetPushGroupsError { /// <summary> /// An enum describing each of the possible error codes that can be returned from a /// CCSetPushGroupsRequest. /// </summary> public enum Error { /// <summary> /// A connection could not be established. /// </summary> CouldNotConnect = -2, /// <summary> /// An unexpected, fatal error has occured on the server. /// </summary> UnexpectedError = 1, /// <summary> /// Invalid Request. One of more of the provided fields were not correctly formatted. /// The data property of the response body will contain specific error messages for /// each field. /// </summary> InvalidRequest = 1007, /// <summary> /// Expired Connect Access Token. The Connect Access Token used to authenticate with /// the server has expired and should be renewed. /// </summary> ExpiredConnectAccessToken = 1003, /// <summary> /// Invalid Connect Access Token. The Connect Access Token was not valid and cannot /// be used to authenticate requests. /// </summary> InvalidConnectAccessToken = 1004 } private const int SuccessHttpResponseCode = 200; private const int UnexpectedErrorHttpResponseCode = 500; /// <summary> /// A code describing the error that has occurred. /// </summary> public Error ErrorCode { get; private set; } /// <summary> /// A description of the error that as occurred. /// </summary> public string ErrorDescription { get; private set; } /// <summary> /// A dictionary of additional, error specific information. /// </summary> public MultiTypeValue ErrorData { get; private set; } /// <summary> /// Initialises a new instance from the given server response. The server response /// must describe an error otherwise this will throw an error. /// </summary> /// /// <param name="serverResponse">The server response from which to initialise this error. /// The response must describe an error state.</param> public SetPushGroupsError(ServerResponse serverResponse) { ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied."); ReleaseAssert.IsTrue(serverResponse.Result != HttpResult.Success || serverResponse.HttpResponseCode != SuccessHttpResponseCode, "Input server response must describe an error."); switch (serverResponse.Result) { case HttpResult.Success: if (serverResponse.HttpResponseCode == UnexpectedErrorHttpResponseCode) { ErrorCode = Error.UnexpectedError; ErrorData = MultiTypeValue.Null; } else { ErrorCode = GetErrorCode(serverResponse); ErrorData = GetErrorData(serverResponse.Body); } break; case HttpResult.CouldNotConnect: ErrorCode = Error.CouldNotConnect; ErrorData = MultiTypeValue.Null; break; default: throw new ArgumentException("Invalid value for server response result."); } ErrorDescription = GetErrorDescription(ErrorCode); } /// <summary> /// Initialises a new instance from the given error code. /// </summary> /// /// <param name="errorCode">The error code.</param> public SetPushGroupsError(Error errorCode) { ErrorCode = errorCode; ErrorData = MultiTypeValue.Null; ErrorDescription = GetErrorDescription(ErrorCode); } /// <summary> /// Parses the response body to get the response code. /// </summary> /// /// <returns>The error code in the given response body.</returns> /// /// <param name="serverResponse">The server response from which to get the error code. This /// must describe an successful response from the server which contains an error in the /// response body.</param> private static Error GetErrorCode(ServerResponse serverResponse) { const string JsonKeyErrorCode = "Code"; ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied."); ReleaseAssert.IsTrue(serverResponse.Result == HttpResult.Success, "The result must describe a successful server response."); ReleaseAssert.IsTrue(serverResponse.HttpResponseCode != SuccessHttpResponseCode && serverResponse.HttpResponseCode != UnexpectedErrorHttpResponseCode, "Must not be a successful or unexpected HTTP response code."); object errorCodeObject = serverResponse.Body[JsonKeyErrorCode]; ReleaseAssert.IsTrue(errorCodeObject is long, "'Code' must be a long."); long errorCode = (long)errorCodeObject; switch (errorCode) { case 1007: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 422, @"Invalid HTTP response code for error code."); return Error.InvalidRequest; case 1003: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code."); return Error.ExpiredConnectAccessToken; case 1004: ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code."); return Error.InvalidConnectAccessToken; default: return Error.UnexpectedError; } } /// <summary> /// Extracts the error data json from the given response body. /// </summary> /// /// <returns>The additional error data.<returns/> /// /// <param name="responseBody">The response body containing the error data.</param> private static MultiTypeValue GetErrorData(IDictionary<string, object> responseBody) { const string JsonKeyErrorData = "Data"; ReleaseAssert.IsNotNull(responseBody, "The response body cannot be null."); if (!responseBody.ContainsKey(JsonKeyErrorData)) { return MultiTypeValue.Null; } return new MultiTypeValue(responseBody[JsonKeyErrorData]); } /// <summary> /// Gets the error message for the given error code. /// </summary> /// /// <returns>The error message.</returns> /// /// <param name="errorCode">The error code.</param> private static string GetErrorDescription(Error errorCode) { switch (errorCode) { case Error.CouldNotConnect: return "A connection could not be established."; case Error.InvalidRequest: return "Invalid Request. One of more of the provided fields were not correctly formatted." + " The data property of the response body will contain specific error messages for" + " each field."; case Error.ExpiredConnectAccessToken: return "Expired Connect Access Token. The Connect Access Token used to authenticate with" + " the server has expired and should be renewed."; case Error.InvalidConnectAccessToken: return "Invalid Connect Access Token. The Connect Access Token was not valid and cannot" + " be used to authenticate requests."; case Error.UnexpectedError: default: return "An unexpected server error occurred."; } } } }
mit
philogb/philogl
src/program.js
10809
//program.js //Creates programs out of shaders and provides convenient methods for loading //buffers attributes and uniforms (function() { //First, some privates to handle compiling/linking shaders to programs. //Creates a shader from a string source. var createShader = function(gl, shaderSource, shaderType) { var shader = gl.createShader(shaderType); if (shader == null) { throw "Error creating the shader with shader type: " + shaderType; //return false; } gl.shaderSource(shader, shaderSource); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var info = gl.getShaderInfoLog(shader); gl.deleteShader(shader); throw "Error while compiling the shader " + info; //return false; } return shader; }; //Creates a program from vertex and fragment shader sources. var createProgram = function(gl, vertexShader, fragmentShader) { var program = gl.createProgram(); gl.attachShader( program, createShader(gl, vertexShader, gl.VERTEX_SHADER)); gl.attachShader( program, createShader(gl, fragmentShader, gl.FRAGMENT_SHADER)); linkProgram(gl, program); return program; }; var getpath = function(path) { var last = path.lastIndexOf('/'); if (last == '/') { return './'; } else { return path.substr(0, last + 1); } }; // preprocess a source with `#include ""` support // `duplist` records all the pending replacements var preprocess = function(base, source, callback, callbackError, duplist) { duplist = duplist || {}; var match; if ((match = source.match(/#include "(.*?)"/))) { var xhr = PhiloGL.IO.XHR, url = getpath(base) + match[1]; if (duplist[url]) { callbackError('Recursive include'); } new xhr({ url: url, noCache: true, onError: function(code) { callbackError('Load included file `' + url + '` failed: Code ' + code); }, onSuccess: function(response) { duplist[url] = true; return preprocess(url, response, function(replacement) { delete duplist[url]; source = source.replace(/#include ".*?"/, replacement); source = source.replace(/\sHAS_EXTENSION\s*\(\s*([A-Za-z_\-0-9]+)\s*\)/g, function (all, ext) { return gl.getExtension(ext) ? ' 1 ': ' 0 '; }); return preprocess(url, source, callback, callbackError, duplist); }, callbackError, duplist); } }).send(); return null; } else { return callback(source); } }; //Link a program. var linkProgram = function(gl, program) { gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { throw "Error linking the shader: " + gl.getProgramInfoLog(program); //return false; } return true; }; //Returns a Magic Uniform Setter var getUniformSetter = function(program, info, isArray) { var name = info.name, loc = gl.getUniformLocation(program, name), type = info.type, matrix = false, vector = true, glFunction, typedArray; if (info.size > 1 && isArray) { switch(type) { case gl.FLOAT: glFunction = gl.uniform1fv; typedArray = Float32Array; vector = false; break; case gl.INT: case gl.BOOL: case gl.SAMPLER_2D: case gl.SAMPLER_CUBE: glFunction = gl.uniform1iv; typedArray = Uint16Array; vector = false; break; } } if (vector) { switch (type) { case gl.FLOAT: glFunction = gl.uniform1f; break; case gl.FLOAT_VEC2: glFunction = gl.uniform2fv; typedArray = isArray ? Float32Array : new Float32Array(2); break; case gl.FLOAT_VEC3: glFunction = gl.uniform3fv; typedArray = isArray ? Float32Array : new Float32Array(3); break; case gl.FLOAT_VEC4: glFunction = gl.uniform4fv; typedArray = isArray ? Float32Array : new Float32Array(4); break; case gl.INT: case gl.BOOL: case gl.SAMPLER_2D: case gl.SAMPLER_CUBE: glFunction = gl.uniform1i; break; case gl.INT_VEC2: case gl.BOOL_VEC2: glFunction = gl.uniform2iv; typedArray = isArray ? Uint16Array : new Uint16Array(2); break; case gl.INT_VEC3: case gl.BOOL_VEC3: glFunction = gl.uniform3iv; typedArray = isArray ? Uint16Array : new Uint16Array(3); break; case gl.INT_VEC4: case gl.BOOL_VEC4: glFunction = gl.uniform4iv; typedArray = isArray ? Uint16Array : new Uint16Array(4); break; case gl.FLOAT_MAT2: matrix = true; glFunction = gl.uniformMatrix2fv; break; case gl.FLOAT_MAT3: matrix = true; glFunction = gl.uniformMatrix3fv; break; case gl.FLOAT_MAT4: matrix = true; glFunction = gl.uniformMatrix4fv; break; } } glFunction = glFunction.bind(gl); //Set a uniform array if (isArray && typedArray) { return function(val) { glFunction(loc, new typedArray(val)); }; //Set a matrix uniform } else if (matrix) { return function(val) { glFunction(loc, false, val.toFloat32Array()); }; //Set a vector/typed array uniform } else if (typedArray) { return function(val) { typedArray.set(val.toFloat32Array ? val.toFloat32Array() : val); glFunction(loc, typedArray); }; //Set a primitive-valued uniform } else { return function(val) { glFunction(loc, val); }; } // FIXME: Unreachable code throw "Unknown type: " + type; }; //Program Class: Handles loading of programs and mapping of attributes and uniforms var Program = function(vertexShader, fragmentShader) { var program = createProgram(gl, vertexShader, fragmentShader); if (!program) return false; var attributes = {}, attributeEnabled = {}, uniforms = {}, info, name, index; //fill attribute locations var len = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < len; i++) { info = gl.getActiveAttrib(program, i); name = info.name; index = gl.getAttribLocation(program, info.name); attributes[name] = index; } //create uniform setters len = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (i = 0; i < len; i++) { info = gl.getActiveUniform(program, i); name = info.name; //if array name then clean the array brackets name = name[name.length -1] == ']' ? name.substr(0, name.length -3) : name; uniforms[name] = getUniformSetter(program, info, info.name != name); } this.program = program; //handle attributes and uniforms this.attributes = attributes; this.attributeEnabled = attributeEnabled; this.uniforms = uniforms; }; Program.prototype = { $$family: 'program', setUniform: function(name, val) { if (this.uniforms[name]) { this.uniforms[name](val); } return this; }, setUniforms: function(obj) { for (var name in obj) { this.setUniform(name, obj[name]); } return this; } }; ['setBuffer', 'setBuffers', 'use'].forEach(function(name) { Program.prototype[name] = function() { var args = Array.prototype.slice.call(arguments); args.unshift(this); app[name].apply(app, args); return this; }; }); ['setFrameBuffer', 'setFrameBuffers', 'setRenderBuffer', 'setRenderBuffers', 'setTexture', 'setTextures'].forEach(function(name) { Program.prototype[name] = function() { app[name].apply(app, arguments); return this; }; }); //Get options in object or arguments function getOptions(args, base) { var opt; if (args.length == 2) { opt = { vs: args[0], fs: args[1] }; } else { opt = args[0] || {}; } return $.merge(base || {}, opt); } //Create a program from vertex and fragment shader node ids Program.fromShaderIds = function() { var opt = getOptions(arguments), vs = $(opt.vs), fs = $(opt.fs); return preprocess(opt.path, vs.innerHTML, function(vectexShader) { return preprocess(opt.path, fs.innerHTML, function(fragmentShader) { opt.onSuccess(new Program(vectexShader, fragmentShader), opt); }); }); }; //Create a program from vs and fs sources Program.fromShaderSources = function() { var opt = getOptions(arguments, {path: './'}); return preprocess(opt.path, opt.vs, function(vectexShader) { return preprocess(opt.path, opt.fs, function(fragmentShader) { try { var program = new Program(vectexShader, fragmentShader); if(opt.onSuccess) { opt.onSuccess(program, opt); } else { return program; } } catch(e) { if (opt.onError) { opt.onError(e, opt); } else { throw e; } } }); }); }; //Build program from default shaders (requires Shaders) Program.fromDefaultShaders = function(opt) { opt = opt || {}; var vs = opt.vs || 'Default', fs = opt.fs || 'Default', sh = PhiloGL.Shaders; opt.vs = sh.Vertex[vs]; opt.fs = sh.Fragment[fs]; return PhiloGL.Program.fromShaderSources(opt); }; //Implement Program.fromShaderURIs (requires IO) Program.fromShaderURIs = function(opt) { opt = $.merge({ path: '', vs: '', fs: '', noCache: false, onSuccess: $.empty, onError: $.empty }, opt || {}); var vertexShaderURI = opt.path + opt.vs, fragmentShaderURI = opt.path + opt.fs, XHR = PhiloGL.IO.XHR; new XHR.Group({ urls: [vertexShaderURI, fragmentShaderURI], noCache: opt.noCache, onError: function(arg) { opt.onError(arg); }, onComplete: function(ans) { try { return preprocess(vertexShaderURI, ans[0], function(vectexShader) { return preprocess(fragmentShaderURI, ans[1], function(fragmentShader) { opt.vs = vectexShader; opt.fs = fragmentShader; return Program.fromShaderSources(opt); }, opt.onError); }, opt.onError); } catch (e) { opt.onError(e, opt); } } }).send(); }; PhiloGL.Program = Program; })();
mit
beni55/sbt-docker
src/test/scala/sbtdocker/mutable/MutableDockerfileSpec.scala
2214
package sbtdocker.mutable import org.scalatest.{FlatSpec, Matchers} import sbt._ import sbtdocker.ImageName import sbtdocker.staging.CopyFile class MutableDockerfileSpec extends FlatSpec with Matchers { import sbtdocker.Instructions._ "Dockerfile" should "be mutable" in { val dockerfile = new Dockerfile() dockerfile .from("arch") .runRaw("echo 123") dockerfile.instructions should contain theSameElementsInOrderAs Seq(From("arch"), Run("echo 123")) } it should "have methods for all instructions" in { val file1 = file("/1") val file2 = file("/2") val url1 = new URL("http://domain.tld") val url2 = new URL("http://sub.domain.tld") val dockerfile = new Dockerfile { from("image") from(ImageName("ubuntu")) maintainer("marcus") maintainer("marcus", "marcus@domain.tld") run("echo", "1") runShell("echo", "2") cmd("echo", "1") cmdShell("echo", "2") expose(80, 443) env("key", "value") add(file1, "/") add(file2, file2) addRaw(url1, "/") addRaw(url2, file2) copy(file1, "/") copy(file2, file2) entryPoint("echo", "1") entryPointShell("echo", "2") volume("/srv") user("marcus") workDir("/srv") onBuild(Run.exec(Seq("echo", "text"))) } val instructions = Seq( From("image"), From("ubuntu"), Maintainer("marcus"), Maintainer("marcus <marcus@domain.tld>"), Run.exec(Seq("echo", "1")), Run.shell(Seq("echo", "2")), Cmd.exec(Seq("echo", "1")), Cmd.shell(Seq("echo", "2")), Expose(Seq(80, 443)), Env("key", "value"), Add(Seq(CopyFile(file1)), "/"), Add(Seq(CopyFile(file2)), file2.toString), AddRaw(url1.toString, "/"), AddRaw(url2.toString, file2.toString), Copy(Seq(CopyFile(file1)), "/"), Copy(Seq(CopyFile(file2)), file2.toString), EntryPoint.exec(Seq("echo", "1")), EntryPoint.shell(Seq("echo", "2")), Volume("/srv"), User("marcus"), WorkDir("/srv"), OnBuild(Run.exec(Seq("echo", "text")))) dockerfile.instructions should contain theSameElementsInOrderAs instructions } }
mit
dchbx/gluedb
db/seedfiles/plans_2015_json.rb
475
puts "Importing 2015 plans" plan_file = File.open("db/seedfiles/2015_plans.json", "r") data = plan_file.read plan_file.close plan_data = JSON.load(data) counter = 0 puts "#{plan_data.size} plans in json file" plan_data.each do |pd| next if pd["renewal_plan_id"].blank? plan = Plan.find(pd["id"]) plan.renewal_plan_id = pd["renewal_plan_id"] plan.save! counter += 1 end puts "#{counter} 2015 plans updated with renewal_plan_id" puts "Finished importing 2015 plans"
mit
YOTOV-LIMITED/web
node_modules/geoip/lib/netspeedcell.js
2413
/** * Module dependencies */ var fs = require('fs'); var dns = require('dns'); var path = require('path'); var isObject = require('is-object'); // var info = require('debug')('geoip:lib:netspeedcell:info'); var debug = require('debug')('geoip:lib:netspeedcell:debug'); var binding = require('bindings')('native.node'); var validateFile = require('./helpers').validateFile; var isValidIpORdomain = require('./helpers').isValidIpORdomain; /** * Exports */ module.exports = NetSpeedCell; /** * Class * * @param {String} file * @param {Object} options */ function NetSpeedCell(file, options) { this.types = ['netspeed cellular']; this.options = options ? (isObject(options) ? options : {cache: !!options}) : ({cache: true}); // validateFile(file, this.types); this.native = new binding.NetSpeedCell(path.resolve(file), this.options.cache); return this; } /** * Asynchronously lookup * @param {String} ipORdomain * @param {Function} callback */ NetSpeedCell.prototype.lookup = function(ipORdomain, callback) { var self = this; // if(!isValidIpORdomain(ipORdomain)) { self.options.silent ? callback(null, null) : callback(new TypeError('expected string')); return; } dns.lookup(ipORdomain, 4, function(err, address, family) { if (err) { // See @http://nodejs.org/api/dns.html#dns_error_codes debug('Dns error code: %s', err.code); return callback.call(self, err); } info('Address returned from node dns: %s', address); info('Family number returned from nod dns: %d', family); callback.call(self, null, self.native.lookupSync(address)); }); }; /** * Synchronously lookup * @param {String} ipORdomain */ NetSpeedCell.prototype.lookupSync = function(ipORdomain) { // if(!isValidIpORdomain(ipORdomain)) { if (this.options.silent) { return null; } else { throw new TypeError('expected string'); } } return this.native.lookupSync(ipORdomain); }; /** * Update * @param {String} newFile * @param {Object} options */ NetSpeedCell.prototype.update = function(newFile, options) { // validateFile(newFile, this.types); this.native = new binding.NetSpeedCell(path.resolve(newFile), this.options.cache); return this; };
mit
FarmBot/farmbot-web-app
app/mutations/sequences/destroy.rb
2345
module Sequences class Destroy < Mutations::Command IN_USE = "Sequence is still in use by" THE_FOLLOWING = " the following %{resource}: %{items}" AND = " and" # Override `THE_FOLLOWING` here. SPECIAL_CASES = { FarmEvent => " %{resource} on the following dates: %{items}", } required do model :device, class: Device model :sequence, class: Sequence end def validate add_error :sequence, :sequence, (IN_USE + all_deps) if all_deps.present? end def execute sequence.destroy! return "" end private def pin_bindings @pin_bindings ||= PinBinding .where(sequence_id: sequence.id) .to_a end def sibling_ids @sibling_ids ||= EdgeNode .where(kind: "sequence_id", value: sequence.id) .pluck(:sequence_id) .uniq .without(sequence.id) end def sibling_sequences @sibling_sequences ||= Sequence.find(sibling_ids).uniq end def regimens @regimens ||= Regimen .includes(:regimen_items) .where(regimen_items: { sequence_id: sequence.id }) .to_a end def farm_events @farm_events ||= FarmEvent .includes(:executable) .where(executable: sequence) .uniq .to_a end class FancyName attr_reader :fancy_name def self.table_name "items" end def initialize(name) @fancy_name = name end end def fbos_config @fbos_config ||= FbosConfig .where(device_id: device.id, boot_sequence_id: sequence.id) .any? ? [FancyName.new("boot sequence")] : [] end def format_dep_list(klass, items) (SPECIAL_CASES[klass] || THE_FOLLOWING) % { resource: klass.table_name.humanize.downcase, items: items.map(&:fancy_name).uniq.join(", "), } unless items.empty? end def all_deps @all_deps ||= [] .concat(farm_events) # FarmEvent .concat(pin_bindings) # PinBinding .concat(regimens) # Regimen .concat(sibling_sequences) # Sequence .concat(fbos_config) .compact .group_by { |x| x.class } .to_a .map { |(klass, items)| format_dep_list(klass, items) } .compact .join(AND) end end end
mit
auraphp/Aura.SqlQuery
src/Common/LimitTrait.php
781
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/mit-license.php MIT * */ namespace Aura\SqlQuery\Common; /** * * A trait for LIMIT clauses. * * @package Aura.SqlQuery * */ trait LimitTrait { /** * * The LIMIT value. * * @var int * */ protected $limit = 0; /** * * Sets a limit count on the query. * * @param int $limit The number of rows to select. * * @return $this * */ public function limit($limit) { $this->limit = (int) $limit; return $this; } /** * * Returns the LIMIT value. * * @return int * */ public function getLimit() { return $this->limit; } }
mit
nresni/AriadneSandbox
src/vendor/zend/library/Zend/Http/Cookie.php
11765
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage Cookie * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Http; use Zend\Uri; /** * Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters. * * Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters. The * class also enables validating whether the cookie should be sent to the server in * a specified scenario according to the request URI, the expiry time and whether * session cookies should be used or not. Generally speaking cookies should be * contained in a Cookiejar object, or instantiated manually and added to an HTTP * request. * * See http://wp.netscape.com/newsref/std/cookie_spec.html for some specs. * * @uses \Zend\Date\Date * @uses \Zend\Http\Exception * @uses \Zend\Uri\Url * @category Zend * @package Zend_Http * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Cookie { /** * Cookie name * * @var string */ protected $name; /** * Cookie value * * @var string */ protected $value; /** * Cookie expiry date * * @var int */ protected $expires; /** * Cookie domain * * @var string */ protected $domain; /** * Cookie path * * @var string */ protected $path; /** * Whether the cookie is secure or not * * @var boolean */ protected $secure; /** * Whether the cookie value has been encoded/decoded * * @var boolean */ protected $encodeValue; /** * Cookie object constructor * * @todo Add validation of each one of the parameters (legal domain, etc.) * * @param string $name * @param string $value * @param string $domain * @param int $expires * @param string $path * @param bool $secure */ public function __construct($name, $value, $domain, $expires = null, $path = null, $secure = false) { if (preg_match("/[=,; \t\r\n\013\014]/", $name)) { throw new Exception\InvalidArgumentException("Cookie name cannot contain these characters: =,; \\t\\r\\n\\013\\014 ({$name})"); } if (! $this->name = (string) $name) { throw new Exception\InvalidArgumentException('Cookies must have a name'); } if (! $this->domain = (string) $domain) { throw new Exception\InvalidArgumentException('Cookies must have a domain'); } $this->value = (string) $value; $this->expires = ($expires === null ? null : (int) $expires); $this->path = ($path ? $path : '/'); $this->secure = $secure; } /** * Get Cookie name * * @return string */ public function getName() { return $this->name; } /** * Get cookie value * * @return string */ public function getValue() { return $this->value; } /** * Get cookie domain * * @return string */ public function getDomain() { return $this->domain; } /** * Get the cookie path * * @return string */ public function getPath() { return $this->path; } /** * Get the expiry time of the cookie, or null if no expiry time is set * * @return int|null */ public function getExpiryTime() { return $this->expires; } /** * Check whether the cookie should only be sent over secure connections * * @return boolean */ public function isSecure() { return $this->secure; } /** * Check whether the cookie has expired * * Always returns false if the cookie is a session cookie (has no expiry time) * * @param int $now Timestamp to consider as "now" * @return boolean */ public function isExpired($now = null) { if ($now === null) $now = time(); if (is_int($this->expires) && $this->expires < $now) { return true; } else { return false; } } /** * Check whether the cookie is a session cookie (has no expiry time set) * * @return boolean */ public function isSessionCookie() { return ($this->expires === null); } /** * Checks whether the cookie should be sent or not in a specific scenario * * @param string|\Zend\Uri\Url $uri URI to check against (secure, domain, path) * @param boolean $matchSessionCookies Whether to send session cookies * @param int $now Override the current time when checking for expiry time * @return boolean */ public function match($uri, $matchSessionCookies = true, $now = null) { if (is_string ($uri)) { $uri = new Uri\Url($uri); } // Make sure we have a valid Zend_Uri_Http object if (! ($uri->isValid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) { throw new Exception\InvalidArgumentException('Passed URI is not a valid HTTP or HTTPS URI'); } // Check that the cookie is secure (if required) and not expired if ($this->secure && $uri->getScheme() != 'https') return false; if ($this->isExpired($now)) return false; if ($this->isSessionCookie() && ! $matchSessionCookies) return false; // Check if the domain matches if (! self::matchCookieDomain($this->getDomain(), $uri->getHost())) { return false; } // Check that path matches using prefix match if (! self::matchCookiePath($this->getPath(), $uri->getPath())) { return false; } // If we didn't die until now, return true. return true; } /** * Get the cookie as a string, suitable for sending as a "Cookie" header in an * HTTP request * * @return string */ public function __toString() { if ($this->encodeValue) { return $this->name . '=' . urlencode($this->value) . ';'; } return $this->name . '=' . $this->value . ';'; } /** * Generate a new Cookie object from a cookie string * (for example the value of the Set-Cookie HTTP header) * * @param string $cookieStr * @param \Zend\Uri\Url|string $refUri Reference URI for default values (domain, path) * @param boolean $encodeValue Weither or not the cookie's value should be * passed through urlencode/urldecode * @return \Zend\Http\Cookie A new \Zend\Http\Cookie object or false on failure. */ public static function fromString($cookieStr, $refUri = null, $encodeValue = true) { // Set default values if (is_string($refUri)) { $refUri = new Uri\Url($refUri); } $name = ''; $value = ''; $domain = ''; $path = ''; $expires = null; $secure = false; $parts = explode(';', $cookieStr); // If first part does not include '=', fail if (strpos($parts[0], '=') === false) return false; // Get the name and value of the cookie list($name, $value) = explode('=', trim(array_shift($parts)), 2); $name = trim($name); if ($encodeValue) { $value = urldecode(trim($value)); } // Set default domain and path if ($refUri instanceof Uri\Url) { $domain = $refUri->getHost(); $path = $refUri->getPath(); $path = substr($path, 0, strrpos($path, '/')); } // Set other cookie parameters foreach ($parts as $part) { $part = trim($part); if (strtolower($part) == 'secure') { $secure = true; continue; } $keyValue = explode('=', $part, 2); if (count($keyValue) == 2) { list($k, $v) = $keyValue; switch (strtolower($k)) { case 'expires': if(($expires = strtotime($v)) === false) { /** * The expiration is past Tue, 19 Jan 2038 03:14:07 UTC * the maximum for 32-bit signed integer. Zend_Date * can get around that limit. */ $expireDate = new \Zend\Date\Date($v); $expires = $expireDate->getTimestamp(); } break; case 'path': $path = $v; break; case 'domain': $domain = $v; break; default: break; } } } if ($name !== '') { $ret = new self($name, $value, $domain, $expires, $path, $secure); $ret->encodeValue = ($encodeValue) ? true : false; return $ret; } else { return false; } } /** * Check if a cookie's domain matches a host name. * * Used by Zend_Http_Cookie and Zend_Http_CookieJar for cookie matching * * @param string $cookieDomain * @param string $host * * @return boolean */ public static function matchCookieDomain($cookieDomain, $host) { if (! $cookieDomain) { throw new Exception\InvalidArgumentException("\$cookieDomain is expected to be a cookie domain"); } if (! $host) { throw new Exception\InvalidArgumentException("\$host is expected to be a host name"); } $cookieDomain = strtolower($cookieDomain); $host = strtolower($host); if ($cookieDomain[0] == '.') { $cookieDomain = substr($cookieDomain, 1); } // Check for either exact match or suffix match return ($cookieDomain == $host || preg_match("/\.$cookieDomain$/", $host)); } /** * Check if a cookie's path matches a URL path * * Used by Zend_Http_Cookie and Zend_Http_CookieJar for cookie matching * * @param string $cookiePath * @param string $path * @return boolean */ public static function matchCookiePath($cookiePath, $path) { if (! $cookiePath) { throw new Exception\InvalidArgumentException("\$cookiePath is expected to be a cookie path"); } if ((null !== $path) && (!is_scalar($path) || is_numeric($path) || is_bool($path))) { throw new Exception\InvalidArgumentException("\$path is expected to be a cookie path"); } $path = (string) $path; if (empty($path)) { $path = '/'; } return (strpos($path, $cookiePath) === 0); } }
mit
Aurioch/MonoGame.Extended
Source/Tests/MonoGame.Extended.Tests/RangeTests.cs
2971
using System; using NUnit.Framework; namespace MonoGame.Extended.Tests { [TestFixture] public class RangeTests { [Test] public void ConstructorTest() { //can pass min < max Assert.DoesNotThrow(() => new Range<int>(10, 100)); //can't pass min > max Assert.Throws<ArgumentException>(() => new Range<int>(100, 10)); //can pass min == max Assert.DoesNotThrow(() => new Range<int>(10, 10)); } [Test] public void DegenerateTest() { var proper = new Range<double>(0, 1); Assert.IsTrue(proper.IsProper); Assert.IsFalse(proper.IsDegenerate); var degenerate = new Range<double>(1, 1); Assert.IsFalse(degenerate.IsProper); Assert.IsTrue(degenerate.IsDegenerate); } [Test] public void IntegerTest() { var range = new Range<int>(10, 100); Assert.AreEqual(range.Min, 10); Assert.AreEqual(range.Max, 100); for (var i = 10; i <= 100; i++) { Assert.IsTrue(range.IsInBetween(i)); } Assert.IsFalse(range.IsInBetween(9)); Assert.IsFalse(range.IsInBetween(101)); Assert.IsFalse(range.IsInBetween(10, true)); Assert.IsFalse(range.IsInBetween(100, maxValueExclusive: true)); } [Test] public void FloatTest() { var range = new Range<float>(0f, 1f); Assert.AreEqual(range.Min, 0f); Assert.AreEqual(range.Max, 1f); for (float i = 0; i <= 1f; i += 0.001f) { Assert.IsTrue(range.IsInBetween(i)); } Assert.IsFalse(range.IsInBetween(-float.Epsilon)); Assert.IsFalse(range.IsInBetween(1.00001f)); Assert.IsFalse(range.IsInBetween(0f, true)); Assert.IsFalse(range.IsInBetween(1f, maxValueExclusive: true)); } [Test] public void OperatorTest() { var rangeA = new Range<int>(0, 1); var rangeB = new Range<int>(0, 1); var rangeC = new Range<int>(1, 2); var rangeD = new Range<double>(0, 1); Assert.IsTrue(rangeA == rangeB); Assert.IsFalse(rangeA == rangeC); Assert.IsFalse(rangeA != rangeB); Assert.IsTrue(rangeA != rangeC); Assert.IsTrue(rangeA.Equals(rangeB)); Assert.IsFalse(rangeA.Equals(rangeC)); Assert.IsFalse(rangeA.Equals(rangeD)); Range<int> implict = 1; Assert.AreEqual(implict.Max, 1); Assert.AreEqual(implict.Min, 1); } [Test] public void ToStringTest() { var range = new Range<float>(0, 1); Assert.AreEqual(range.ToString(), "Range<Single> [0 1]"); } } }
mit
wilsonwp/panel_control
app/Jugador.php
598
<?php namespace futboleros; use Illuminate\Database\Eloquent\Model; class Jugador extends Model{ protected $fillable = ['nombre','alias','fecha_nac','nacionalidad','peso','estatura','descripcion','equipo_id']; //***** Relaciones entre las Clases****// // Jugador Pertenece a un Equipo function equipo(){ return $this->belongsTo('\futboleros\Equipo'); } // Jugador Pertenece a una Posicion function posicione(){ return $this->belongsTo('\futboleros\Posicione'); } function goles(){ return $this->hasMany('\futboleros\Gol'); } }
mit
ravinderpayal/material2
src/lib/core/testing/event-objects.ts
1726
/** Creates a browser MouseEvent with the specified options. */ export function createMouseEvent(type: string, x = 0, y = 0) { let event = document.createEvent('MouseEvent'); event.initMouseEvent(type, false, /* canBubble */ false, /* cancelable */ window, /* view */ 0, /* detail */ x, /* screenX */ y, /* screenY */ x, /* clientX */ y, /* clientY */ false, /* ctrlKey */ false, /* altKey */ false, /* shiftKey */ false, /* metaKey */ 0, /* button */ null /* relatedTarget */); return event; } /** Dispatches a keydown event from an element. */ export function createKeyboardEvent(type: string, keyCode: number) { let event = document.createEvent('KeyboardEvent') as any; // Firefox does not support `initKeyboardEvent`, but supports `initKeyEvent`. let initEventFn = (event.initKeyEvent || event.initKeyboardEvent).bind(event); let originalPreventDefault = event.preventDefault; initEventFn(type, true, true, window, 0, 0, 0, 0, 0, keyCode); // Webkit Browsers don't set the keyCode when calling the init function. // See related bug https://bugs.webkit.org/show_bug.cgi?id=16735 Object.defineProperty(event, 'keyCode', { get: () => keyCode }); // IE won't set `defaultPrevented` on synthetic events so we need to do it manually. event.preventDefault = function() { Object.defineProperty(event, 'defaultPrevented', { get: () => true }); return originalPreventDefault.apply(this, arguments); }; return event; } /** Creates a fake event object with any desired event type. */ export function createFakeEvent(type: string) { let event = document.createEvent('Event'); event.initEvent(type, true, true); return event; }
mit
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/google/cloud/error_reporting/__init__.py
1002
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client library for Stackdriver Error Reporting""" from pkg_resources import get_distribution __version__ = get_distribution('google-cloud-error-reporting').version from google.cloud.error_reporting.client import Client from google.cloud.error_reporting.client import HTTPContext from google.cloud.error_reporting.util import build_flask_context __all__ = ['__version__', 'Client', 'HTTPContext', 'build_flask_context']
mit
AutoSimDevelopers/automata-simulation
unit-tests/spec/SimulationDFASpec.js
1750
/*jshint -W030*/ describe('', function () { var scope, controller; beforeEach(function () { module('automata-simulation'); }); describe('Simulation', function () { beforeEach(inject(function ($rootScope, $controller) { scope = $rootScope.$new(); controller = $controller('DFACtrl', { '$scope': scope }); scope.statediagram.isGrid = false; /*jshint -W020 */ simulator = scope.simulator; scope.inputWord = "abc"; scope.addStateWithPresets(50, 50); scope.addStateWithPresets(50, 200); scope.addStateWithPresets(200, 200); scope.addStateWithPresets(200, 50); scope.addTransition(0, 1, "a"); scope.addTransition(1, 2, "b"); scope.addTransition(2, 3, "c"); scope.addTransition(3, 0, "l"); scope.addFinalState(3); scope.changeStartState(0); })); it('At the beginning the inputWord should be undefined', function () { expect(scope.inputWord).toBe("abc"); }); it('When resetting', function () { simulator.reset(); expect(simulator.transition).toBeNull(); expect(simulator.inputWord).toBeUndeFined; }); /* it('When press Play', function() { simulator.playOrPause(); expect(simulator.transition).toBeNull(); expect(simulator.inputWord).toBeUndeFined; }); it('State should be created', function() { expect(scope.config.countStateId).toBe(1); expect(scope.config.states.length).toBe(1); });*/ }); });
mit
jalves94/azure-sdk-for-java
azure-mgmt-batch/src/main/java/com/microsoft/azure/management/batch/implementation/ApplicationImpl.java
7223
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.batch.implementation; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.batch.Application; import com.microsoft.azure.management.batch.ApplicationPackage; import com.microsoft.azure.management.batch.BatchAccount; import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.ExternalChildResourceImpl; import rx.Observable; import rx.functions.Func1; import java.util.Map; import java.util.List; /** * Implementation for BatchAccount Application and its parent interfaces. */ @LangDefinition public class ApplicationImpl extends ExternalChildResourceImpl<Application, ApplicationInner, BatchAccountImpl, BatchAccount> implements Application, Application.Definition<BatchAccount.DefinitionStages.WithApplicationAndStorage>, Application.UpdateDefinition<BatchAccount.Update>, Application.Update { private final ApplicationsInner client; private final ApplicationPackagesImpl applicationPackages; protected ApplicationImpl( String name, BatchAccountImpl batchAccount, ApplicationInner inner, ApplicationsInner client, ApplicationPackagesInner applicationPackagesClient) { super(name, batchAccount, inner); this.client = client; applicationPackages = new ApplicationPackagesImpl(applicationPackagesClient, this); } @Override public String id() { return this.inner().id(); } @Override public String displayName() { return this.inner().displayName(); } @Override public Map<String, ApplicationPackage> applicationPackages() { return this.applicationPackages.asMap(); } @Override public boolean updatesAllowed() { return this.inner().allowUpdates(); } @Override public String defaultVersion() { return this.inner().defaultVersion(); } @Override public Observable<Application> createAsync() { final ApplicationImpl self = this; AddApplicationParametersInner createParameter = new AddApplicationParametersInner(); createParameter.withDisplayName(this.inner().displayName()); createParameter.withAllowUpdates(this.inner().allowUpdates()); return this.client.createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), createParameter) .map(new Func1<ApplicationInner, Application>() { @Override public Application call(ApplicationInner inner) { self.setInner(inner); return self; } }) .flatMap(new Func1<Application, Observable<? extends Application>>() { @Override public Observable<? extends Application> call(Application application) { return self.applicationPackages.commitAndGetAllAsync() .map(new Func1<List<ApplicationPackageImpl>, Application>() { @Override public Application call(List<ApplicationPackageImpl> applications) { return self; } }); } }); } @Override public Observable<Application> updateAsync() { final ApplicationImpl self = this; UpdateApplicationParametersInner updateParameter = new UpdateApplicationParametersInner(); updateParameter.withDisplayName(this.inner().displayName()); updateParameter.withAllowUpdates(this.inner().allowUpdates()); return this.client.updateAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), updateParameter) .map(new Func1<Void, Application>() { @Override public Application call(Void result) { return self; } }) .flatMap(new Func1<Application, Observable<? extends Application>>() { @Override public Observable<? extends Application> call(Application application) { return self.applicationPackages.commitAndGetAllAsync() .map(new Func1<List<ApplicationPackageImpl>, Application>() { @Override public Application call(List<ApplicationPackageImpl> applications) { return self; } }); } }); } @Override public Observable<Void> deleteAsync() { return this.client.deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Application refresh() { ApplicationInner inner = this.client.get(this.parent().resourceGroupName(), this.parent().name(), this.inner().id()); this.setInner(inner); this.applicationPackages.refresh(); return this; } @Override public BatchAccountImpl attach() { return this.parent().withApplication(this); } @Override public ApplicationImpl withAllowUpdates(boolean allowUpdates) { this.inner().withAllowUpdates(allowUpdates); return this; } @Override public ApplicationImpl withDisplayName(String displayName) { this.inner().withDisplayName(displayName); return this; } protected static ApplicationImpl newApplication( String name, BatchAccountImpl parent, ApplicationsInner client, ApplicationPackagesInner applicationPackagesClient) { ApplicationInner inner = new ApplicationInner(); inner.withId(name); ApplicationImpl applicationImpl = new ApplicationImpl(name, parent, inner, client, applicationPackagesClient); return applicationImpl; } @Override public Update withoutApplicationPackage(String applicationPackageName) { this.applicationPackages.remove(applicationPackageName); return this; } ApplicationImpl withApplicationPackage(ApplicationPackageImpl applicationPackage) { this.applicationPackages.addApplicationPackage(applicationPackage); return this; } @Override public ApplicationImpl defineNewApplicationPackage(String applicationPackageName) { this.withApplicationPackage(this.applicationPackages.define(applicationPackageName)); return this; } }
mit
cykl/cucumber-jvm
core/src/main/java/cucumber/runtime/table/TableConverter.java
12812
package cucumber.runtime.table; import cucumber.api.DataTable; import cucumber.deps.com.thoughtworks.xstream.converters.ConversionException; import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter; import cucumber.deps.com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter; import cucumber.deps.com.thoughtworks.xstream.io.HierarchicalStreamReader; import cucumber.runtime.CucumberException; import cucumber.runtime.ParameterInfo; import cucumber.runtime.table.CamelCaseStringConverter; import cucumber.runtime.table.StringConverter; import cucumber.runtime.xstream.CellWriter; import cucumber.runtime.xstream.ComplexTypeWriter; import cucumber.runtime.xstream.ListOfComplexTypeReader; import cucumber.runtime.xstream.ListOfSingleValueWriter; import cucumber.runtime.xstream.LocalizedXStreams; import cucumber.runtime.xstream.MapWriter; import gherkin.formatter.model.Comment; import gherkin.formatter.model.DataTableRow; import gherkin.util.Mapper; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static cucumber.runtime.Utils.listItemType; import static cucumber.runtime.Utils.mapKeyType; import static cucumber.runtime.Utils.mapValueType; import static gherkin.util.FixJava.map; import static java.util.Arrays.asList; /** * This class converts a {@link cucumber.api.DataTable} to various other types. */ public class TableConverter { private static final List<Comment> NO_COMMENTS = Collections.emptyList(); private final LocalizedXStreams.LocalizedXStream xStream; private final ParameterInfo parameterInfo; public TableConverter(LocalizedXStreams.LocalizedXStream xStream, ParameterInfo parameterInfo) { this.xStream = xStream; this.parameterInfo = parameterInfo; } /** * This method converts a {@link cucumber.api.DataTable} to abother type. * When a Step Definition is passed a Gherkin Data Table, the runtime will use this method to convert the * {@link cucumber.api.DataTable} to the declared type before invoking the Step Definition. * <p/> * This method uses reflection to inspect the type and delegates to the appropriate {@code toXxx} method. * * @param dataTable the table to convert * @param type the type to convert to * @param transposed whether the table should be transposed first. * @return the transformed object. */ public <T> T convert(DataTable dataTable, Type type, boolean transposed) { if (transposed) { dataTable = dataTable.transpose(); } if (type == null || (type instanceof Class && ((Class) type).isAssignableFrom(DataTable.class))) { return (T) dataTable; } Type mapKeyType = mapKeyType(type); if (mapKeyType != null) { Type mapValueType = mapValueType(type); return (T) toMap(dataTable, mapKeyType, mapValueType); } Type itemType = listItemType(type); if (itemType == null) { throw new CucumberException("Not a Map or List type: " + type); } Type listItemType = listItemType(itemType); if (listItemType != null) { return (T) toLists(dataTable, listItemType); } else { SingleValueConverter singleValueConverter = xStream.getSingleValueConverter(itemType); if (singleValueConverter != null) { return (T) toList(dataTable, singleValueConverter); } else { if (itemType instanceof Class) { if (Map.class.equals(itemType)) { // Non-generic map return (T) toMaps(dataTable, String.class, String.class); } else { return (T) toListOfComplexType(dataTable, (Class) itemType); } } else { return (T) toMaps(dataTable, mapKeyType(itemType), mapValueType(itemType)); } } } } private <T> List<T> toListOfComplexType(DataTable dataTable, Class<T> itemType) { HierarchicalStreamReader reader = new ListOfComplexTypeReader(itemType, convertTopCellsToFieldNames(dataTable), dataTable.cells(1)); try { xStream.setParameterInfo(parameterInfo); return Collections.unmodifiableList((List<T>) xStream.unmarshal(reader)); } catch (AbstractReflectionConverter.UnknownFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (AbstractReflectionConverter.DuplicateFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (ConversionException e) { if (e.getCause() instanceof NullPointerException) { throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class"))); } else { throw new CucumberException(e); } } finally { xStream.unsetParameterInfo(); } } public <T> List<T> toList(DataTable dataTable, Type itemType) { SingleValueConverter itemConverter = xStream.getSingleValueConverter(itemType); if (itemConverter != null) { return toList(dataTable, itemConverter); } else { if (itemType instanceof Class) { return toListOfComplexType(dataTable, (Class<T>) itemType); } else { throw new CucumberException(String.format("Can't convert DataTable to List<%s>", itemType)); } } } private <T> List<T> toList(DataTable dataTable, SingleValueConverter itemConverter) { List<T> result = new ArrayList<T>(); for (List<String> row : dataTable.raw()) { for (String cell : row) { result.add((T) itemConverter.fromString(cell)); } } return Collections.unmodifiableList(result); } public <T> List<List<T>> toLists(DataTable dataTable, Type itemType) { try { xStream.setParameterInfo(parameterInfo); SingleValueConverter itemConverter = xStream.getSingleValueConverter(itemType); if (itemConverter == null) { throw new CucumberException(String.format("Can't convert DataTable to List<List<%s>>", itemType)); } List<List<T>> result = new ArrayList<List<T>>(); for (List<String> row : dataTable.raw()) { List<T> convertedRow = new ArrayList<T>(); for (String cell : row) { convertedRow.add((T) itemConverter.fromString(cell)); } result.add(Collections.unmodifiableList(convertedRow)); } return Collections.unmodifiableList(result); } finally { xStream.unsetParameterInfo(); } } public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) { try { xStream.setParameterInfo(parameterInfo); SingleValueConverter keyConverter = xStream.getSingleValueConverter(keyType); SingleValueConverter valueConverter = xStream.getSingleValueConverter(valueType); if (keyConverter == null || valueConverter == null) { throw new CucumberException(String.format("Can't convert DataTable to Map<%s,%s>", keyType, valueType)); } Map<K, V> result = new HashMap<K, V>(); for (List<String> row : dataTable.raw()) { if (row.size() != 2) { throw new CucumberException("A DataTable can only be converted to a Map when there are 2 columns"); } K key = (K) keyConverter.fromString(row.get(0)); V value = (V) valueConverter.fromString(row.get(1)); result.put(key, value); } return Collections.unmodifiableMap(result); } finally { xStream.unsetParameterInfo(); } } public <K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType) { try { xStream.setParameterInfo(parameterInfo); SingleValueConverter keyConverter = xStream.getSingleValueConverter(keyType); SingleValueConverter valueConverter = xStream.getSingleValueConverter(valueType); if (keyConverter == null || valueConverter == null) { throw new CucumberException(String.format("Can't convert DataTable to List<Map<%s,%s>>", keyType, valueType)); } List<Map<K, V>> result = new ArrayList<Map<K, V>>(); List<String> keyStrings = dataTable.topCells(); List<K> keys = new ArrayList<K>(); for (String keyString : keyStrings) { keys.add((K) keyConverter.fromString(keyString)); } List<List<String>> valueRows = dataTable.cells(1); for (List<String> valueRow : valueRows) { Map<K, V> map = new HashMap<K, V>(); int i = 0; for (String cell : valueRow) { map.put(keys.get(i), (V) valueConverter.fromString(cell)); i++; } result.add(Collections.unmodifiableMap(map)); } return Collections.unmodifiableList(result); } finally { xStream.unsetParameterInfo(); } } /** * Converts a List of objects to a DataTable. * * @param objects the objects to convert * @param columnNames an explicit list of column names * @return a DataTable */ public DataTable toTable(List<?> objects, String... columnNames) { try { xStream.setParameterInfo(parameterInfo); List<String> header = null; List<List<String>> valuesList = new ArrayList<List<String>>(); for (Object object : objects) { CellWriter writer; if (isListOfSingleValue(object)) { // XStream needs an instance of ArrayList object = new ArrayList<Object>((List<Object>) object); writer = new ListOfSingleValueWriter(); } else if (isArrayOfSingleValue(object)) { // XStream needs an instance of ArrayList object = new ArrayList<Object>(asList((Object[]) object)); writer = new ListOfSingleValueWriter(); } else if (object instanceof Map) { writer = new MapWriter(asList(columnNames)); } else { writer = new ComplexTypeWriter(asList(columnNames)); } xStream.marshal(object, writer); if (header == null) { header = writer.getHeader(); } List<String> values = writer.getValues(); valuesList.add(values); } return createDataTable(header, valuesList); } finally { xStream.unsetParameterInfo(); } } private DataTable createDataTable(List<String> header, List<List<String>> valuesList) { List<DataTableRow> gherkinRows = new ArrayList<DataTableRow>(); if (header != null) { gherkinRows.add(gherkinRow(header)); } for (List<String> values : valuesList) { gherkinRows.add(gherkinRow(values)); } return new DataTable(gherkinRows, this); } private DataTableRow gherkinRow(List<String> cells) { return new DataTableRow(NO_COMMENTS, cells, 0); } private List<String> convertTopCellsToFieldNames(DataTable dataTable) { final StringConverter mapper = new CamelCaseStringConverter(); return map(dataTable.topCells(), new Mapper<String, String>() { @Override public String map(String attributeName) { return mapper.map(attributeName); } }); } private boolean isListOfSingleValue(Object object) { if (object instanceof List) { List list = (List) object; return list.size() > 0 && xStream.getSingleValueConverter(list.get(0).getClass()) != null; } return false; } private boolean isArrayOfSingleValue(Object object) { if (object.getClass().isArray()) { Object[] array = (Object[]) object; return array.length > 0 && xStream.getSingleValueConverter(array[0].getClass()) != null; } return false; } }
mit
jcanongia/meanjs
node_modules/yo/lib/routes/install.js
4445
'use strict'; var async = require('async'); var chalk = require('chalk'); var inquirer = require('inquirer'); var spawn = require('cross-spawn-async'); var sortOn = require('sort-on'); var figures = require('figures'); var npmKeyword = require('npm-keyword'); var packageJson = require('package-json'); var got = require('got'); var OFFICIAL_GENERATORS = [ 'generator-angular', 'generator-backbone', 'generator-bootstrap', 'generator-chrome-extension', 'generator-chromeapp', 'generator-commonjs', 'generator-generator', 'generator-gruntplugin', 'generator-gulp-webapp', 'generator-jasmine', 'generator-jquery', 'generator-karma', 'generator-mobile', 'generator-mocha', 'generator-node', 'generator-polymer', 'generator-webapp' ]; module.exports = function (app) { app.insight.track('yoyo', 'install'); inquirer.prompt([{ name: 'searchTerm', message: 'Search npm for generators:' }], function (answers) { searchNpm(app, answers.searchTerm, function (err) { if (err) { throw err; } }); }); }; var getAllGenerators = (function () { var allGenerators; return function (cb) { if (allGenerators) { return cb(null, allGenerators); } npmKeyword('yeoman-generator').then(function (packages) { cb(null, packages.map(function (el) { el.match = function (term) { return (el.name + ' ' + el.description).indexOf(term) >= 0; }; return el; })); }).catch(cb); }; })(); function searchMatchingGenerators(app, term, cb) { got('yeoman.io/blacklist.json', {json: true}, function (err, data) { var blacklist = err ? [] : data; var installedGenerators = app.env.getGeneratorNames(); getAllGenerators(function (err, allGenerators) { if (err) { cb(err); return; } cb(null, allGenerators.filter(function (generator) { if (blacklist.indexOf(generator.name) !== -1) { return false; } if (installedGenerators.indexOf(generator.name) !== -1) { return false; } return generator.match(term); })); }); }); } function fetchGeneratorInfo(generator, cb) { packageJson(generator.name).then(function (pkg) { var official = OFFICIAL_GENERATORS.indexOf(pkg.name) !== -1; var mustache = official ? chalk.green(' ' + figures.mustache + ' ') : ''; cb(null, { name: generator.name.replace(/^generator-/, '') + // `gray` → `dim` when iTerm 2.9 is out mustache + ' ' + chalk.gray(pkg.description), value: generator.name, official: -official }); }).catch(cb); } function searchNpm(app, term, cb) { searchMatchingGenerators(app, term, function (err, matches) { if (err) { cb(err); return; } async.map(matches, fetchGeneratorInfo, function (err, choices) { if (err) { cb(err); return; } promptInstallOptions(app, sortOn(choices, ['official', 'name'])); cb(); }); }); } function promptInstallOptions(app, choices) { var introMessage = 'Sorry, no results matches your search term'; if (choices.length > 0) { introMessage = 'Here\'s what I found. ' + chalk.gray('Official generator → ' + chalk.green(figures.mustache)) + '\n Install one?'; } var resultsPrompt = [{ name: 'toInstall', type: 'list', message: introMessage, choices: choices.concat([{ name: 'Search again', value: 'install' }, { name: 'Return home', value: 'home' }]) }]; inquirer.prompt(resultsPrompt, function (answer) { if (answer.toInstall === 'home' || answer.toInstall === 'install') { return app.navigate(answer.toInstall); } installGenerator(app, answer.toInstall); }); } function installGenerator(app, pkgName) { app.insight.track('yoyo', 'install', pkgName); return spawn('npm', ['install', '-g', pkgName], {stdio: 'inherit'}) .on('error', function (err) { app.insight.track('yoyo:err', 'install', pkgName); throw err; }) .on('close', function () { app.insight.track('yoyo', 'installed', pkgName); console.log( '\nI just installed a generator by running:\n' + chalk.blue.bold('\n npm install -g ' + pkgName + '\n') ); app.env.lookup(function () { app.updateAvailableGenerators(); app.navigate('home'); }); }); }
mit
danielkay/primeng
src/app/showcase/components/megamenu/megamenudemo.ts
4525
import {Component} from '@angular/core'; import {MenuItem} from '../../../components/common/api'; @Component({ templateUrl: './megamenudemo.html' }) export class MegaMenuDemo { private items: MenuItem[]; ngOnInit() { this.items = [ { label: 'TV', icon: 'fa-check', items: [ [ { label: 'TV 1', items: [{label: 'TV 1.1'},{label: 'TV 1.2'}] }, { label: 'TV 2', items: [{label: 'TV 2.1'},{label: 'TV 2.2'}] } ], [ { label: 'TV 3', items: [{label: 'TV 3.1'},{label: 'TV 3.2'}] }, { label: 'TV 4', items: [{label: 'TV 4.1'},{label: 'TV 4.2'}] } ] ] }, { label: 'Sports', icon: 'fa-soccer-ball-o', items: [ [ { label: 'Sports 1', items: [{label: 'Sports 1.1'},{label: 'Sports 1.2'}] }, { label: 'Sports 2', items: [{label: 'Sports 2.1'},{label: 'Sports 2.2'}] }, ], [ { label: 'Sports 3', items: [{label: 'Sports 3.1'},{label: 'Sports 3.2'}] }, { label: 'Sports 4', items: [{label: 'Sports 4.1'},{label: 'Sports 4.2'}] } ], [ { label: 'Sports 5', items: [{label: 'Sports 5.1'},{label: 'Sports 5.2'}] }, { label: 'Sports 6', items: [{label: 'Sports 6.1'},{label: 'Sports 6.2'}] } ] ] }, { label: 'Entertainment', icon: 'fa-child', items: [ [ { label: 'Entertainment 1', items: [{label: 'Entertainment 1.1'},{label: 'Entertainment 1.2'}] }, { label: 'Entertainment 2', items: [{label: 'Entertainment 2.1'},{label: 'Entertainment 2.2'}] } ], [ { label: 'Entertainment 3', items: [{label: 'Entertainment 3.1'},{label: 'Entertainment 3.2'}] }, { label: 'Entertainment 4', items: [{label: 'Entertainment 4.1'},{label: 'Entertainment 4.2'}] } ] ] }, { label: 'Technology', icon: 'fa-gears', items: [ [ { label: 'Technology 1', items: [{label: 'Technology 1.1'},{label: 'Technology 1.2'}] }, { label: 'Technology 2', items: [{label: 'Technology 2.1'},{label: 'Technology 2.2'}] }, { label: 'Technology 3', items: [{label: 'Technology 3.1'},{label: 'Technology 3.2'}] } ], [ { label: 'Technology 4', items: [{label: 'Technology 4.1'},{label: 'Technology 4.2'}] } ] ] } ]; } }
mit
sergeyfedotov/symfony
src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
11835
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Csrf\CsrfToken; use Symfony\Component\Form\FormTypeInterface; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Doctrine\Bundle\DoctrineBundle\Registry; /** * Controller is a simple implementation of a Controller. * * It provides methods to common features needed in controllers. * * @author Fabien Potencier <fabien@symfony.com> */ class Controller extends ContainerAware { /** * Generates a URL from the given parameters. * * @param string $route The name of the route * @param mixed $parameters An array of parameters * @param bool|string $referenceType The type of reference (one of the constants in UrlGeneratorInterface) * * @return string The generated URL * * @see UrlGeneratorInterface */ public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) { return $this->container->get('router')->generate($route, $parameters, $referenceType); } /** * Forwards the request to another controller. * * @param string $controller The controller name (a string like BlogBundle:Post:index) * @param array $path An array of path parameters * @param array $query An array of query parameters * * @return Response A Response instance */ public function forward($controller, array $path = array(), array $query = array()) { $path['_controller'] = $controller; $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate($query, null, $path); return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } /** * Returns a RedirectResponse to the given URL. * * @param string $url The URL to redirect to * @param int $status The status code to use for the Response * * @return RedirectResponse */ public function redirect($url, $status = 302) { return new RedirectResponse($url, $status); } /** * Returns a RedirectResponse to the given route with the given parameters. * * @param string $route The name of the route * @param array $parameters An array of parameters * @param int $status The status code to use for the Response * * @return RedirectResponse */ protected function redirectToRoute($route, array $parameters = array(), $status = 302) { return $this->redirect($this->generateUrl($route, $parameters), $status); } /** * Adds a flash message to the current session for type. * * @param string $type The type * @param string $message The message * * @throws \LogicException */ protected function addFlash($type, $message) { if (!$this->container->has('session')) { throw new \LogicException('You can not use the addFlash method if sessions are disabled.'); } $this->container->get('session')->getFlashBag()->add($type, $message); } /** * Checks if the attributes are granted against the current authentication token and optionally supplied object. * * @param mixed $attributes The attributes * @param mixed $object The object * * @throws \LogicException * @return bool */ protected function isGranted($attributes, $object = null) { if (!$this->container->has('security.authorization_checker')) { throw new \LogicException('The SecurityBundle is not registered in your application.'); } return $this->container->get('security.authorization_checker')->isGranted($attributes, $object); } /** * Throws an exception unless the attributes are granted against the current authentication token and optionally * supplied object. * * @param mixed $attributes The attributes * @param mixed $object The object * @param string $message The message passed to the exception * * @throws AccessDeniedException */ protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.') { if (!$this->isGranted($attributes, $object)) { throw $this->createAccessDeniedException($message); } } /** * Returns a rendered view. * * @param string $view The view name * @param array $parameters An array of parameters to pass to the view * * @return string The rendered view */ public function renderView($view, array $parameters = array()) { return $this->container->get('templating')->render($view, $parameters); } /** * Renders a view. * * @param string $view The view name * @param array $parameters An array of parameters to pass to the view * @param Response $response A response instance * * @return Response A Response instance */ public function render($view, array $parameters = array(), Response $response = null) { return $this->container->get('templating')->renderResponse($view, $parameters, $response); } /** * Streams a view. * * @param string $view The view name * @param array $parameters An array of parameters to pass to the view * @param StreamedResponse $response A response instance * * @return StreamedResponse A StreamedResponse instance */ public function stream($view, array $parameters = array(), StreamedResponse $response = null) { $templating = $this->container->get('templating'); $callback = function () use ($templating, $view, $parameters) { $templating->stream($view, $parameters); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; } /** * Returns a NotFoundHttpException. * * This will result in a 404 response code. Usage example: * * throw $this->createNotFoundException('Page not found!'); * * @param string $message A message * @param \Exception|null $previous The previous exception * * @return NotFoundHttpException */ public function createNotFoundException($message = 'Not Found', \Exception $previous = null) { return new NotFoundHttpException($message, $previous); } /** * Returns an AccessDeniedException. * * This will result in a 403 response code. Usage example: * * throw $this->createAccessDeniedException('Unable to access this page!'); * * @param string $message A message * @param \Exception|null $previous The previous exception * * @return AccessDeniedException */ public function createAccessDeniedException($message = 'Access Denied', \Exception $previous = null) { return new AccessDeniedException($message, $previous); } /** * Creates and returns a Form instance from the type of the form. * * @param string|FormTypeInterface $type The built type of the form * @param mixed $data The initial data for the form * @param array $options Options for the form * * @return Form */ public function createForm($type, $data = null, array $options = array()) { return $this->container->get('form.factory')->create($type, $data, $options); } /** * Creates and returns a form builder instance. * * @param mixed $data The initial data for the form * @param array $options Options for the form * * @return FormBuilder */ public function createFormBuilder($data = null, array $options = array()) { return $this->container->get('form.factory')->createBuilder('form', $data, $options); } /** * Shortcut to return the request service. * * @return Request * * @deprecated Deprecated since version 2.4, to be removed in 3.0. Ask * Symfony to inject the Request object into your controller * method instead by type hinting it in the method's signature. */ public function getRequest() { trigger_error('The "getRequest" method of the base "Controller" class has been deprecated since Symfony 2.4 and will be removed in 3.0. The only reliable way to get the "Request" object is to inject it in the action method.', E_USER_DEPRECATED); return $this->container->get('request_stack')->getCurrentRequest(); } /** * Shortcut to return the Doctrine Registry service. * * @return Registry * * @throws \LogicException If DoctrineBundle is not available */ public function getDoctrine() { if (!$this->container->has('doctrine')) { throw new \LogicException('The DoctrineBundle is not registered in your application.'); } return $this->container->get('doctrine'); } /** * Get a user from the Security Context. * * @return mixed * * @throws \LogicException If SecurityBundle is not available * * @see Symfony\Component\Security\Core\Authentication\Token\TokenInterface::getUser() */ public function getUser() { if (!$this->container->has('security.context')) { throw new \LogicException('The SecurityBundle is not registered in your application.'); } if (null === $token = $this->container->get('security.context')->getToken()) { return; } if (!is_object($user = $token->getUser())) { return; } return $user; } /** * Returns true if the service id is defined. * * @param string $id The service id * * @return bool true if the service id is defined, false otherwise */ public function has($id) { return $this->container->has($id); } /** * Gets a service by id. * * @param string $id The service id * * @return object The service */ public function get($id) { return $this->container->get($id); } /** * Checks the validity of a CSRF token * * @param string $id The id used when generating the token * @param string $token The actual token sent with the request that should be validated * * @return bool */ protected function isCsrfTokenValid($id, $token) { if (!$this->container->has('security.csrf.token_manager')) { throw new \LogicException('CSRF protection is not enabled in your application.'); } return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token)); } }
mit
uglyfruitcake/Axelrod
axelrod/strategies/__init__.py
1118
from ..player import is_basic, obey_axelrod from ._strategies import * # `from ._strategies import *` import the collection `strategies` # Now import the Meta strategies. This cannot be done in _strategies # because it creates circular dependencies from .meta import ( MetaPlayer, MetaMajority, MetaMinority, MetaWinner, MetaHunter, MetaMajorityMemoryOne, MetaWinnerMemoryOne, MetaMajorityFiniteMemory, MetaWinnerFiniteMemory, MetaMajorityLongMemory, MetaWinnerLongMemory ) strategies.extend((MetaHunter, MetaMajority, MetaMinority, MetaWinner, MetaMajorityMemoryOne, MetaWinnerMemoryOne, MetaMajorityFiniteMemory, MetaWinnerFiniteMemory, MetaMajorityLongMemory, MetaWinnerLongMemory)) # Distinguished strategy collections in addition to # `strategies` from _strategies.py demo_strategies = [Cooperator, Defector, TitForTat, Grudger, Random] basic_strategies = [s for s in strategies if is_basic(s())] ordinary_strategies = [s for s in strategies if obey_axelrod(s())] cheating_strategies = [s for s in strategies if not obey_axelrod(s())]
mit
pupudu/sID_system
config/passport.js
45414
// load all the things we need var chalk = require('chalk'); var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy; var rest = require('restler'); // load the auth variables var configAuth = require('./auth'); // load up the user model var User = require('../app/models/user'); var Facebook = require('../app/models/facebook'); var Entry = require("../app/models/entry"); var LinkedIn = require("../app/models/linkedin"); var controller = require('../app/controllers/controllers'); var OrgUser = require("../app/models/orgUser"); module.exports = function (passport) { // ========================================================================= // passport session setup ================================================== // ========================================================================= // required for persistent login sessions // passport needs ability to serialize and deserialize users out of session // used to serialize the user for the session passport.serializeUser(function (user, done) { //console.log("From Serializer: " + user); done(null, user._id); }); // used to deserialize the user passport.deserializeUser(function (id, done) { //User.findById(id, function (err, user) { // done(err, user); //}); console.log("Deserializing user"); User.findOne({ _id: id }) .populate('userDetails.facebook') .populate('userDetails.linkedin') //.populate('facebook.ratedByMe') .exec(function (error, user) { console.log(JSON.stringify(user, null, "\t")); if (error) { done(error); console.log("Error 1564512332131 ++++++++++++++++++++++++++++++++++++++"); } else { if (user) { done(error, user); } else { // done(error); OrgUser.findOne({ _id: id }) // .populate('userDetails.facebook') // .populate('userDetails.linkedin') //.populate('facebook.ratedByMe') .exec(function (error, user) { if (error) { done(error); console.log("Error 94516513132 +++++++++++++++++-----------------------"); } else { console.log(JSON.stringify(user, null, "\t")); if (user) { done(error, user); } else { done(null, false); } } }); } } }); }); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField: 'email', passwordField: 'password', passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, email, password, done) { var tempUser; if (email) { email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching } // asynchronous process.nextTick(function () { OrgUser.findOne({'userDetails.email': email}, function (err, user) { // if there are any errors, return the error if (err) { return done(err); } // if no user is found, return the message if (user) { if (!user.validPassword(password)) { return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); }// all is well, return user else { return done(null, user); } } else { User.findOne({'userDetails.local.email': email}, function (err, user) { // if there are any errors, return the error if (err) { return done(err); } // if no user is found, return the message if (!user) { return done(null, false, req.flash('loginMessage', 'No user found.')); } if (!user.validPassword(password)) { return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); } // all is well, return user else { return done(null, user); } }); } }); }); })); // ========================================================================= // LOCAL SIGNUP ============================================================ // ========================================================================= passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField: 'email', passwordField: 'password', passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, email, password, done) { if (email) { email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching } // asynchronous process.nextTick(function () { // if the user is not already logged in: if (!req.user) { User.findOne({'userDetails.local.email': email}, function (err, user) { // if there are any errors, return the error if (err) { return done(err); } if (req.body.firstname === "" || req.body.lastname === "") { return done(null, false, req.flash('signupMessage', 'Please enter your full name.')); } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } if (!validateEmail(req.body.email)) { return done(null, false, req.flash('signupMessage', 'Please enter a valid email address.')); } // if(!password){ // console.log(chalk.blue('Inside validateEmail' + password)); // return done(null, false, req.flash('signupMessage', 'Please a password for your sID account.')); // } // check to see if theres already a user with that email if (user) { return done(null, false, req.flash('signupMessage', 'Email that you have entered is already used to create an account.')); } else { // create the user var newUser = new User(); //firstname, lastname added newUser.userDetails.local.firstname = req.body.firstname; newUser.userDetails.local.lastname = req.body.lastname; newUser.userDetails.local.email = email; newUser.userDetails.local.password = newUser.generateHash(password); controller.sendEmail(req); newUser.save(function (err) { if (err) { return done(err); } else { return done(null, newUser); } }); } }); // if the user is logged in but has no local account... } else { return done(null, req.user); } //else if (!req.user.userDetails.local.email) { // // ...presumably they're trying to connect a local account // // BUT let's check if the email used to connect a local account is being used by another user // User.findOne({'userDetails.local.email': email}, function (err, user) { // if (err) { // return done(err); // } // if (user) { // return done(null, false, req.flash('loginMessage', 'Email that you have entered is already used to create an account.')); // // Using 'loginMessage instead of signupMessage because it's used by /connect/local' // } else { // var tempUser = req.user;//User already used above // tempUser.userDetails.local.email = email; // var newUser = new User(); // tempUser.userDetails.local.password = newUser.generateHash(password); // tempUser.save(function (err) { // if (err) { // return done(err); // } // return done(null, tempUser); // }); // } // }); //} else { // // user is logged in and already has a local account. Ignore signup. (You should log out before trying to create a new account, user!) // return done(null, req.user); //} }); })); // ========================================================================= // FACEBOOK ================================================================ // ========================================================================= //This function is used for facebook authentication var facebookAuth = function (req, token, refreshToken, profile, done) { console.log(chalk.yellow("TOKEN1: " + JSON.stringify(token, null, "\t"))); //console.log(chalk.blue("TOKEN SECRET: " + JSON.stringify(tokenSecret, null, "\t"))); console.log(chalk.yellow("PROFILE1: " + JSON.stringify(profile, null, "\t"))); // asynchronous process.nextTick(function () { // check if the user is already logged in if (!req.user) { Facebook.findOne({ id: profile.id }, function (err, facebook) { if (err) { return done(err); } else { if (facebook) { facebook.name = profile.displayName; if (profile.emails) { facebook.email = (profile.emails[0].value || '').toLowerCase(); } if (!facebook.token) { facebook.token = token; //console.log("USER: "+user); //var newUser = new User({ // 'userDetails.facebook': facebook._id //}); //facebook.user = newUser._id; facebook.save(function (err) { if (err) { return done(err); } //newUser.save(function (err) { // if (err) { // return done(err); // } // return done(null, newUser); //}); }); } else { User.findById(facebook.user, function (err, user) { if (err) { return done(err); } else { return done(null, user); } }); } } else { return done(null, false, req.flash('error', 'Facebook account is not linked to a Local account.')); } } }); } else { return done(null); } }); }; //facebook authenticate http strategy passport.use('facebook-auth-http', new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL_auth_http, passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, token, refreshToken, profile, done) { facebookAuth(req, token, refreshToken, profile, done); }) ); //facebook authenticate https strategy passport.use('facebook-auth-https', new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL_auth_https, passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, token, refreshToken, profile, done) { facebookAuth(req, token, refreshToken, profile, done); }) ); //facebook authenticate https strategy passport.use('facebook-auth-plugin-https', new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL_auth_plugin_https, passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, token, refreshToken, profile, done) { console.log("ID: " + profile.id); //return done(null, {_id: profile.id}); facebookAuth(req, token, refreshToken, profile, done); }) ); //This function is used for facebook connect var facebookConnect = function (req, token, refreshToken, profile, done) { console.log(chalk.blue("TOKEN: " + JSON.stringify(token, null, "\t"))); //console.log(chalk.blue("TOKEN SECRET: " + JSON.stringify(tokenSecret, null, "\t"))); console.log(chalk.blue("PROFILE: " + JSON.stringify(profile, null, "\t"))); // asynchronous process.nextTick(function () { // check if the user is already logged in if (!req.user) { return done(null); } else { // user already exists and is logged in, we have to link accounts var newUser = req.user; // pull the user out of the session console.log("Looking for FB user"); //var userID; // //if (req.user.userDetails.facebook && req.user.userDetails.facebook.id) { // userID = req.user.userDetails.facebook.id; //} else { // userID = profile.id; //} Facebook.findOne({ id: profile.id }, function (err, fbUser) { if (err) { console.log("Error 152131"); return done(err); } else { if (fbUser) { console.log("FB user found"); newUser.userDetails.facebook = fbUser._id; fbUser.id = profile.id; fbUser.token = token; fbUser.name = profile.displayName; if (profile.emails) { fbUser.email = (profile.emails[0].value || '').toLowerCase(); } fbUser.user = newUser._id; fbUser.save(function (err) { if (err) { console.log("Error 51586"); return done(err); } else { newUser.save(function (err) { if (err) { console.log("Error 894541"); return done(err); } else { return done(null, newUser); } }); } }); //if (fbUser.user == newUser._id) { // // console.log("fbUser.user == newUser._id"); // // fbUser.token = token; // // //fbUser.user = newUser._id; // // fbUser.save(function (err) { // if (err) { // console.log("Error 64512"); // return done(err); // } else { // //newUser.userDetails.facebook = fbUser._id; // // // //newUser.save(function (err) { // // if (err) { // // return done(err); // // } else { // // // // //Content merging // // // // //User.findOne({ // // // _id: oldUserId // // //}, function (err, oldUser) { // // // User.update( // // // {_id: newUser._id}, // // // {$addToSet: {'facebook.ratedByMe': {$each: oldUserId.facebook.ratedByMe}}} // // // ) // // // User.update( // // // {_id: newUser._id}, // // // {$addToSet: {'facebook.ratedByOthers': {$each: oldUserId.facebook.ratedByOthers}}} // // // ) // // //}); // // // return done(null, newUser); // // } // //}); // } // }); //} else { // // console.log("fbUser.user != newUser._id"); // // User.findOne({ // _id: fbUser.user // }, function (err, user) { // if (err) { // console.log("Error 464561"); // return done(err); // } else { // if (user) { // // console.log("OldUser found"); // // console.log(chalk.yellow("Old User: " + JSON.stringify(user, null, "\t"))); // console.log(chalk.yellow("New User: " + JSON.stringify(newUser, null, "\t"))); // // console.log("Adding data: old -> new"); // // newUser.facebook = user.facebook; // newUser.linkedin = user.linkedin; // newUser.userDetails.facebook = fbUser._id; // // console.log(chalk.green("New User: " + JSON.stringify(newUser, null, "\t"))); // // newUser.save(function (err) { // if (err) { // console.log("Error 8451456"); // } else { // User.findOneAndRemove({ // _id: user._id // }, function (err) { // if (err) { // console.log("Error occurred: " + err); // } else { // console.log("No error") // } // }); // } // }); // // fbUser.user = newUser._id; // fbUser.save(function (err) { // if (err) { // console.log("Error 8451456"); // } // }); // // // return done(null, newUser); // } else { // console.log(chalk.red("NO USER FOUND 984515")); // return done(null, newUser); // } // } // }); // //} } else { var newFBUser = new User(); var facebook = new Facebook(); facebook.id = profile.id; facebook.token = token; facebook.name = profile.displayName; if (profile.emails) { facebook.email = (profile.emails[0].value || '').toLowerCase(); } //facebook.user = newUser._id; facebook.user = newFBUser._id; newFBUser.userDetails.facebook = facebook._id; newFBUser.userDetails.local = req.user.userDetails.local; req.user.userDetails.local = null; if (req.user.userDetails.linkedin) { newFBUser.userDetails.linkedin = req.user.userDetails.linkedin; req.user.userDetails.linkedin = null; } if (req.user.linkedin) { newFBUser.linkedin = req.user.linkedin; req.user.linkedin = null; } req.user.save(function (err) { if (err) { console.log(chalk.red("Error 646156132 - req.user cannot save: " + err)); } }); console.log("++++++++++++++++++++++++++++++++++++++"); console.log('getting user ID'); //controller.getID(profile.id, function (error, uid) { // // if (!error) { // facebook.uid = uid; // console.log("UID: " + uid); // } else { // console.log(error) // } facebook.save(function (err) { if (err) { return done(err); } else { //newUser.userDetails.facebook = facebook._id; // //newUser.save(function (err) { // if (err) { // return done(err); // } // return done(null, newUser); //}); newFBUser.save(function (err) { if (err) { return done(err); } else { return done(null, newFBUser); } }); } }); //}); } } }); } }); }; passport.use('facebook-connect-http', new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL_connect_http, passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, token, refreshToken, profile, done) { facebookConnect(req, token, refreshToken, profile, done); }) ); passport.use('facebook-connect-https', new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL_connect_https, passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function (req, token, refreshToken, profile, done) { facebookConnect(req, token, refreshToken, profile, done); }) ); var getLinkedInID = function getQueryVariable(variable, string) { var qId = string.indexOf("?"); var query = string.substring(qId + 1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (decodeURIComponent(pair[0]) == variable) { return decodeURIComponent(pair[1]); } } return null; }; passport.use('linkedin-auth', new LinkedInStrategy({ clientID: configAuth.linkedinAuth.consumerKey, clientSecret: configAuth.linkedinAuth.consumerSecret, callbackURL: configAuth.linkedinAuth.callbackURL, passReqToCallback: true, // allows us to pass in the req from our route (lets us check if a user is logged in or not) state: true, //profileFields: ['id', 'first-name', 'last-name', 'email-address'], scope: ['r_emailaddress', 'r_basicprofile'] }, function (req, token, refreshToken, profile, done) { //console.log(profile); /*console.log(' req : '+ req); console.log(' token : '+ token); console.log(' rtoken : '+ refreshToken); console.log(' profile: '+ profile); console.log(' done : '+ done); */ //linkedin.setLinkedInToken(token); console.log(chalk.yellow("User found: " + JSON.stringify(profile, null, "\t"))); console.log(chalk.yellow("Token found 3232: " + JSON.stringify(token, null, "\t"))); console.log(chalk.yellow("refreshToken found b53453: " + JSON.stringify(refreshToken, null, "\t"))); // asynchronous process.nextTick(function () { // check if the user is already logged in if (!req.user) { LinkedIn.findOne({ appid: profile.id }, function (err, linkedin) { if (err) { console.log("Error 54654: " + err); return done(err); } else { if (linkedin) { console.log("Linkedin found"); linkedin.token = token; linkedin.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned if (profile.emails && profile.emails.length > 0) { linkedin.email = (profile.emails[0].value || '').toLowerCase(); } if (profile.photos && profile.photos.length > 0) { linkedin.photo = profile.photos[0].value; } linkedin.url = profile._json.siteStandardProfileRequest.url; linkedin.publicurl = profile._json.publicProfileUrl; linkedin.newid = getLinkedInID("id", linkedin.url); linkedin.uid = profile._json.publicProfileUrl; linkedin.save(function (err) { if (err) { console.log(chalk.red("Error occurred 51368435")); return done(err); } else { User.findById(linkedin.user, function (err, user) { if (err) { return done(err); } else { return done(null, user); } }); } }); } else { LinkedIn.findOne({ uid: profile._json.publicProfileUrl }, function (err, linkedin) { if (err) { console.log(chalk.red("Error occurred 6546456")); return done(err); } else { if (linkedinUser) { console.log("Linkedin found 2"); linkedin.token = token; linkedin.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned if (profile.emails && profile.emails.length > 0) { linkedin.email = (profile.emails[0].value || '').toLowerCase(); } if (profile.photos && profile.photos.length > 0) { linkedin.photo = profile.photos[0].value; } linkedin.url = profile._json.siteStandardProfileRequest.url; linkedin.publicurl = profile._json.publicProfileUrl; linkedin.newid = getLinkedInID("id", linkedin.url); linkedin.uid = profile._json.publicProfileUrl; linkedin.save(function (err) { if (err) { console.log(chalk.red("Error occurred 51368435")); return done(err); } else { User.findById(linkedin.user, function (err, user) { if (err) { return done(err); } else { return done(null, user); } }); } }); } else { console.log("No linkedin connected"); return done(null, false, req.flash('error', 'LinkedIn account is not linked to a Local account.')); } } }); } } }); } else { console.log("Already authenticated"); return done(null); } }); })); passport.use('linkedin-connect', new LinkedInStrategy({ clientID: configAuth.linkedinAuth.consumerKey, clientSecret: configAuth.linkedinAuth.consumerSecret, callbackURL: configAuth.linkedinAuth.callbackURL2, passReqToCallback: true, // allows us to pass in the req from our route (lets us check if a user is logged in or not) state: true, //profileFields: ['id', 'first-name', 'last-name', 'email-address'], scope: ['r_emailaddress', 'r_basicprofile'] }, function (req, token, refreshToken, profile, done) { //console.log(profile); /*console.log(' req : '+ req); console.log(' token : '+ token); console.log(' rtoken : '+ refreshToken); console.log(' profile: '+ profile); console.log(' done : '+ done); */ //linkedin.setLinkedInToken(token); console.log(chalk.yellow("User found 564: " + JSON.stringify(profile, null, "\t"))); console.log(chalk.yellow("Token found 75876: " + JSON.stringify(token, null, "\t"))); console.log(chalk.yellow("refreshToken found: " + JSON.stringify(refreshToken, null, "\t"))); // asynchronous process.nextTick(function () { // check if the user is already logged in if (!req.user) { return done(null); } else { // user already exists and is logged in, we have to link accounts var newUser = req.user; // pull the user out of the session LinkedIn.findOne({ appid: profile.id }, function (err, linkedinUser) { if (err) { return done(null); } else if (linkedinUser) { console.log("LinkedIn user found"); linkedinUser.token = token; linkedinUser.name = profile.name.givenName + ' ' + profile.name.familyName; linkedinUser.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned if (profile.emails && profile.emails.length > 0) { linkedinUser.email = (profile.emails[0].value || '').toLowerCase(); } if (profile.photos && profile.photos.length > 0) { linkedinUser.photo = profile.photos[0].value; } linkedinUser.url = profile._json.siteStandardProfileRequest.url; linkedinUser.publicurl = profile._json.publicProfileUrl; linkedinUser.newid = getLinkedInID("id", linkedinUser.url); linkedinUser.uid = profile._json.publicProfileUrl; linkedinUser.user = newUser._id; linkedinUser.save(function (err) { if (err) { return done(err); } else { newUser.userDetails.linkedin = linkedinUser._id; newUser.save(function (err) { if (err) { return done(err); } else { return done(null, newUser); } }); } }); } else { LinkedIn.findOne({ uid: profile._json.publicProfileUrl }, function (err, linkedinUser) { if (err) { return done(null); } else { if (err) { return done(null); } else { if (linkedinUser) { console.log("LinkedIn user found 2"); linkedinUser.token = token; linkedinUser.name = profile.name.givenName + ' ' + profile.name.familyName; linkedinUser.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned if (profile.emails && profile.emails.length > 0) { linkedinUser.email = (profile.emails[0].value || '').toLowerCase(); } if (profile.photos && profile.photos.length > 0) { linkedinUser.photo = profile.photos[0].value; } linkedinUser.url = profile._json.siteStandardProfileRequest.url; linkedinUser.publicurl = profile._json.publicProfileUrl; linkedinUser.newid = getLinkedInID("id", linkedinUser.url); linkedinUser.uid = profile._json.publicProfileUrl; linkedinUser.user = newUser._id; linkedinUser.save(function (err) { if (err) { return done(err); } else { newUser.userDetails.linkedin = linkedinUser._id; newUser.save(function (err) { if (err) { return done(err); } else { return done(null, newUser); } }); } }); } else { console.log("LinkedIn user not found"); var linkedin = new LinkedIn(); linkedin.appid = profile.id; linkedin.token = token; linkedin.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned if (profile.emails && profile.emails.length > 0) { linkedin.email = (profile.emails[0].value || '').toLowerCase(); } if (profile.photos && profile.photos.length > 0) { linkedin.photo = profile.photos[0].value; } linkedin.url = profile._json.siteStandardProfileRequest.url; linkedin.publicurl = profile._json.publicProfileUrl; linkedin.newid = getLinkedInID("id", linkedin.url); linkedin.uid = profile._json.publicProfileUrl; linkedin.user = newUser._id; linkedin.save(function (err) { if (err) { return done(err); } else { newUser.userDetails.linkedin = linkedin._id; newUser.save(function (err) { if (err) { return done(err); } else { return done(null, newUser); } }); } }); } } } }); } }); } }); })); };
mit
pheanex/xpython
exercises/rectangles/rectangles.py
35
def count(ascii_diagram): pass
mit
PopcornTimeTV/PopcornTorrent
include/boost/beast/websocket/impl/handshake.hpp
16098
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_HPP #define BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_HPP #include <boost/beast/websocket/impl/stream_impl.hpp> #include <boost/beast/websocket/detail/type_traits.hpp> #include <boost/beast/http/empty_body.hpp> #include <boost/beast/http/message.hpp> #include <boost/beast/http/read.hpp> #include <boost/beast/http/write.hpp> #include <boost/beast/core/async_base.hpp> #include <boost/beast/core/flat_buffer.hpp> #include <boost/beast/core/stream_traits.hpp> #include <boost/asio/coroutine.hpp> #include <boost/assert.hpp> #include <boost/throw_exception.hpp> #include <memory> namespace boost { namespace beast { namespace websocket { //------------------------------------------------------------------------------ // send the upgrade request and process the response // template<class NextLayer, bool deflateSupported> template<class Handler> class stream<NextLayer, deflateSupported>::handshake_op : public beast::stable_async_base<Handler, beast::executor_type<stream>> , public net::coroutine { struct data { // VFALCO This really should be two separate // composed operations, to save on memory request_type req; http::response_parser< typename response_type::body_type> p; flat_buffer fb; bool overflow = false; // could be a member of the op explicit data(request_type&& req_) : req(std::move(req_)) { } }; boost::weak_ptr<impl_type> wp_; detail::sec_ws_key_type key_; response_type* res_p_; data& d_; public: template<class Handler_> handshake_op( Handler_&& h, boost::shared_ptr<impl_type> const& sp, request_type&& req, detail::sec_ws_key_type key, response_type* res_p) : stable_async_base<Handler, beast::executor_type<stream>>( std::forward<Handler_>(h), sp->stream().get_executor()) , wp_(sp) , key_(key) , res_p_(res_p) , d_(beast::allocate_stable<data>( *this, std::move(req))) { sp->reset(); // VFALCO I don't like this (*this)({}, 0, false); } void operator()( error_code ec = {}, std::size_t bytes_used = 0, bool cont = true) { boost::ignore_unused(bytes_used); auto sp = wp_.lock(); if(! sp) { ec = net::error::operation_aborted; return this->complete(cont, ec); } auto& impl = *sp; BOOST_ASIO_CORO_REENTER(*this) { impl.change_status(status::handshake); impl.update_timer(this->get_executor()); // write HTTP request impl.do_pmd_config(d_.req); BOOST_ASIO_CORO_YIELD http::async_write(impl.stream(), d_.req, std::move(*this)); if(impl.check_stop_now(ec)) goto upcall; // read HTTP response BOOST_ASIO_CORO_YIELD http::async_read(impl.stream(), impl.rd_buf, d_.p, std::move(*this)); if(ec == http::error::buffer_overflow) { // If the response overflows the internal // read buffer, switch to a dynamically // allocated flat buffer. d_.fb.commit(net::buffer_copy( d_.fb.prepare(impl.rd_buf.size()), impl.rd_buf.data())); impl.rd_buf.clear(); BOOST_ASIO_CORO_YIELD http::async_read(impl.stream(), d_.fb, d_.p, std::move(*this)); if(! ec) { // Copy any leftovers back into the read // buffer, since this represents websocket // frame data. if(d_.fb.size() <= impl.rd_buf.capacity()) { impl.rd_buf.commit(net::buffer_copy( impl.rd_buf.prepare(d_.fb.size()), d_.fb.data())); } else { ec = http::error::buffer_overflow; } } // Do this before the upcall d_.fb.clear(); } if(impl.check_stop_now(ec)) goto upcall; // success impl.reset_idle(); impl.on_response(d_.p.get(), key_, ec); if(res_p_) swap(d_.p.get(), *res_p_); upcall: this->complete(cont ,ec); } } }; template<class NextLayer, bool deflateSupported> struct stream<NextLayer, deflateSupported>:: run_handshake_op { template<class HandshakeHandler> void operator()( HandshakeHandler&& h, boost::shared_ptr<impl_type> const& sp, request_type&& req, detail::sec_ws_key_type key, response_type* res_p) { // If you get an error on the following line it means // that your handler does not meet the documented type // requirements for the handler. static_assert( beast::detail::is_invocable<HandshakeHandler, void(error_code)>::value, "HandshakeHandler type requirements not met"); handshake_op< typename std::decay<HandshakeHandler>::type>( std::forward<HandshakeHandler>(h), sp, std::move(req), key, res_p); } }; //------------------------------------------------------------------------------ template<class NextLayer, bool deflateSupported> template<class RequestDecorator> void stream<NextLayer, deflateSupported>:: do_handshake( response_type* res_p, string_view host, string_view target, RequestDecorator const& decorator, error_code& ec) { auto& impl = *impl_; impl.change_status(status::handshake); impl.reset(); detail::sec_ws_key_type key; { auto const req = impl.build_request( key, host, target, decorator); impl.do_pmd_config(req); http::write(impl.stream(), req, ec); } if(impl.check_stop_now(ec)) return; http::response_parser< typename response_type::body_type> p; http::read(next_layer(), impl.rd_buf, p, ec); if(ec == http::error::buffer_overflow) { // If the response overflows the internal // read buffer, switch to a dynamically // allocated flat buffer. flat_buffer fb; fb.commit(net::buffer_copy( fb.prepare(impl.rd_buf.size()), impl.rd_buf.data())); impl.rd_buf.clear(); http::read(next_layer(), fb, p, ec);; if(! ec) { // Copy any leftovers back into the read // buffer, since this represents websocket // frame data. if(fb.size() <= impl.rd_buf.capacity()) { impl.rd_buf.commit(net::buffer_copy( impl.rd_buf.prepare(fb.size()), fb.data())); } else { ec = http::error::buffer_overflow; } } } if(impl.check_stop_now(ec)) return; impl.on_response(p.get(), key, ec); if(impl.check_stop_now(ec)) return; if(res_p) *res_p = p.release(); } //------------------------------------------------------------------------------ template<class NextLayer, bool deflateSupported> template<class HandshakeHandler> BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler) stream<NextLayer, deflateSupported>:: async_handshake( string_view host, string_view target, HandshakeHandler&& handler) { static_assert(is_async_stream<next_layer_type>::value, "AsyncStream type requirements not met"); detail::sec_ws_key_type key; auto req = impl_->build_request( key, host, target, &default_decorate_req); return net::async_initiate< HandshakeHandler, void(error_code)>( run_handshake_op{}, handler, impl_, std::move(req), key, nullptr); } template<class NextLayer, bool deflateSupported> template<class HandshakeHandler> BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler) stream<NextLayer, deflateSupported>:: async_handshake( response_type& res, string_view host, string_view target, HandshakeHandler&& handler) { static_assert(is_async_stream<next_layer_type>::value, "AsyncStream type requirements not met"); detail::sec_ws_key_type key; auto req = impl_->build_request( key, host, target, &default_decorate_req); return net::async_initiate< HandshakeHandler, void(error_code)>( run_handshake_op{}, handler, impl_, std::move(req), key, &res); } template<class NextLayer, bool deflateSupported> void stream<NextLayer, deflateSupported>:: handshake(string_view host, string_view target) { static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); error_code ec; handshake( host, target, ec); if(ec) BOOST_THROW_EXCEPTION(system_error{ec}); } template<class NextLayer, bool deflateSupported> void stream<NextLayer, deflateSupported>:: handshake(response_type& res, string_view host, string_view target) { static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); error_code ec; handshake(res, host, target, ec); if(ec) BOOST_THROW_EXCEPTION(system_error{ec}); } template<class NextLayer, bool deflateSupported> void stream<NextLayer, deflateSupported>:: handshake(string_view host, string_view target, error_code& ec) { static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); do_handshake(nullptr, host, target, &default_decorate_req, ec); } template<class NextLayer, bool deflateSupported> void stream<NextLayer, deflateSupported>:: handshake(response_type& res, string_view host, string_view target, error_code& ec) { static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); do_handshake(&res, host, target, &default_decorate_req, ec); } //------------------------------------------------------------------------------ template<class NextLayer, bool deflateSupported> template<class RequestDecorator> void stream<NextLayer, deflateSupported>:: handshake_ex(string_view host, string_view target, RequestDecorator const& decorator) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); error_code ec; handshake_ex(host, target, decorator, ec); if(ec) BOOST_THROW_EXCEPTION(system_error{ec}); } template<class NextLayer, bool deflateSupported> template<class RequestDecorator> void stream<NextLayer, deflateSupported>:: handshake_ex(response_type& res, string_view host, string_view target, RequestDecorator const& decorator) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); error_code ec; handshake_ex(res, host, target, decorator, ec); if(ec) BOOST_THROW_EXCEPTION(system_error{ec}); } template<class NextLayer, bool deflateSupported> template<class RequestDecorator> void stream<NextLayer, deflateSupported>:: handshake_ex(string_view host, string_view target, RequestDecorator const& decorator, error_code& ec) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); do_handshake(nullptr, host, target, decorator, ec); } template<class NextLayer, bool deflateSupported> template<class RequestDecorator> void stream<NextLayer, deflateSupported>:: handshake_ex(response_type& res, string_view host, string_view target, RequestDecorator const& decorator, error_code& ec) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_sync_stream<next_layer_type>::value, "SyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); do_handshake(&res, host, target, decorator, ec); } template<class NextLayer, bool deflateSupported> template<class RequestDecorator, class HandshakeHandler> BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler) stream<NextLayer, deflateSupported>:: async_handshake_ex(string_view host, string_view target, RequestDecorator const& decorator, HandshakeHandler&& handler) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_async_stream<next_layer_type>::value, "AsyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); detail::sec_ws_key_type key; auto req = impl_->build_request( key, host, target, decorator); return net::async_initiate< HandshakeHandler, void(error_code)>( run_handshake_op{}, handler, impl_, std::move(req), key, nullptr); } template<class NextLayer, bool deflateSupported> template<class RequestDecorator, class HandshakeHandler> BOOST_BEAST_ASYNC_RESULT1(HandshakeHandler) stream<NextLayer, deflateSupported>:: async_handshake_ex(response_type& res, string_view host, string_view target, RequestDecorator const& decorator, HandshakeHandler&& handler) { #ifndef BOOST_BEAST_ALLOW_DEPRECATED static_assert(sizeof(RequestDecorator) == 0, BOOST_BEAST_DEPRECATION_STRING); #endif static_assert(is_async_stream<next_layer_type>::value, "AsyncStream type requirements not met"); static_assert(detail::is_request_decorator< RequestDecorator>::value, "RequestDecorator requirements not met"); detail::sec_ws_key_type key; auto req = impl_->build_request( key, host, target, decorator); return net::async_initiate< HandshakeHandler, void(error_code)>( run_handshake_op{}, handler, impl_, std::move(req), key, &res); } } // websocket } // beast } // boost #endif
mit
mrkmarron/ChakraCore
test/inlining/bug12528802.js
619
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var obj = { foo : function() {} }; function bar(arg) { obj.foo.apply(obj, arguments); let local; let baz = function() { local; }; } function test() { bar(); } test(); test(); test(); WScript.Echo("PASSED");
mit
georgiachr/bootstrap
config/sockets.js
10292
/** * WebSocket Server Settings * (sails.config.sockets) * * These settings provide transparent access to the options for Sails' * encapsulated WebSocket server, as well as some additional Sails-specific * configuration layered on top. * * For more information on using Sails with Sockets, check out: * http://links.sailsjs.org/docs/config/sockets */ module.exports.sockets = { // This custom onConnect function will be run each time AFTER a new socket connects // (To control whether a socket is allowed to connect, check out `authorization` config.) // Keep in mind that Sails' RESTful simulation for sockets // mixes in socket.io events for your routes and blueprints automatically. onConnect: function(session, socket) { // By default, do nothing. console.log("New connection"); console.log(socket); }, // This custom onDisconnect function will be run each time a socket disconnects onDisconnect: function(session, socket) { console.log("connection closed"); // By default: do nothing. }, // `transports` // // A array of allowed transport methods which the clients will try to use. // The flashsocket transport is disabled by default // You can enable flashsockets by adding 'flashsocket' to this list: transports: [ 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling' ], // Use this option to set the datastore socket.io will use to manage rooms/sockets/subscriptions: // default: memory adapter: 'memory', // Node.js (and consequently Sails.js) apps scale horizontally. // It's a powerful, efficient approach, but it involves a tiny bit of planning. // At scale, you'll want to be able to copy your app onto multiple Sails.js servers // and throw them behind a load balancer. // // One of the big challenges of scaling an application is that these sorts of clustered // deployments cannot share memory, since they are on physically different machines. // On top of that, there is no guarantee that a user will "stick" with the same server between // requests (whether HTTP or sockets), since the load balancer will route each request to the // Sails server with the most available resources. However that means that all room/pubsub/socket // processing and shared memory has to be offloaded to a shared, remote messaging queue (usually Redis) // // Luckily, Socket.io (and consequently Sails.js) apps support Redis for sockets by default. // To enable a remote redis pubsub server: // adapter: 'redis', // host: '127.0.0.1', // port: 6379, // db: 'sails', // pass: '<redis auth password>' // Worth mentioning is that, if `adapter` config is `redis`, // but host/port is left unset, Sails will try to connect to redis // running on localhost via port 6379 // `authorization` // // Global authorization for Socket.IO access, // this is called when the initial handshake is performed with the server. // // By default (`authorization: false`), when a socket tries to connect, Sails // allows it, every time. If no valid cookie was sent, a temporary session will // be created for the connecting socket. // // If `authorization: true`, before allowing a connection, Sails verifies that a // valid cookie was sent with the upgrade request. If the cookie doesn't match // any known user session, a new user session is created for it. (In most cases, the // user would already have a cookie since they loaded the socket.io client and the initial // HTML page.) // // However, in the case of cross-domain requests, it is possible to receive a connection // upgrade request WITHOUT A COOKIE (for certain transports) // In this case, there is no way to keep track of the requesting user between requests, // since there is no identifying information to link him/her with a session. // The sails.io.js client solves this by connecting to a CORS endpoint first to get a // 3rd party cookie (fortunately this works, even in Safari), then opening the connection. // // You can also pass along a ?cookie query parameter to the upgrade url, // which Sails will use in the absense of a proper cookie // e.g. (when connection from the client): // io.connect('http://localhost:1337?cookie=smokeybear') // // (Un)fortunately, the user's cookie is (should!) not accessible in client-side js. // Using HTTP-only cookies is crucial for your app's security. // Primarily because of this situation, as well as a handful of other advanced // use cases, Sails allows you to override the authorization behavior // with your own custom logic by specifying a function, e.g: /* authorization: function authorizeAttemptedSocketConnection(reqObj, cb) { // Any data saved in `handshake` is available in subsequent requests // from this as `req.socket.handshake.*` // // to allow the connection, call `cb(null, true)` // to prevent the connection, call `cb(null, false)` // to report an error, call `cb(err)` } */ authorization: false, // Whether to run code which supports legacy usage for connected // sockets running the v0.9 version of the socket client SDK (i.e. sails.io.js). // Disabled in newly generated projects, but enabled as an implicit default (i.e. // legacy usage/v0.9 clients be supported if this property is set to true, but also // if it is removed from this configuration file or set to `undefined`) 'backwardsCompatibilityFor0.9SocketClients': false, // Whether to expose a 'get /__getcookie' route with CORS support // that sets a cookie (this is used by the sails.io.js socket client // to get access to a 3rd party cookie and to enable sessions). // // Warning: Currently in this scenario, CORS settings apply to interpreted // requests sent via a socket.io connection that used this cookie to connect, // even for non-browser clients! (e.g. iOS apps, toasters, node.js unit tests) grant3rdPartyCookie: true, // Match string representing the origins that are allowed to connect to the Socket.IO server origins: '*:*', // Should we use heartbeats to check the health of Socket.IO connections? heartbeats: true, // When client closes connection, the # of seconds to wait before attempting a reconnect. // This value is sent to the client after a successful handshake. 'close timeout': 60, // The # of seconds between heartbeats sent from the client to the server // This value is sent to the client after a successful handshake. 'heartbeat timeout': 60, // The max # of seconds to wait for an expcted heartbeat before declaring the pipe broken // This number should be less than the `heartbeat timeout` 'heartbeat interval': 25, // The maximum duration of one HTTP poll- // if it exceeds this limit it will be closed. 'polling duration': 20, // Enable the flash policy server if the flashsocket transport is enabled // 'flash policy server': true, // By default the Socket.IO client will check port 10843 on your server // to see if flashsocket connections are allowed. // The Adobe Flash Player normally uses 843 as default port, // but Socket.io defaults to a non root port (10843) by default // // If you are using a hosting provider that doesn't allow you to start servers // other than on port 80 or the provided port, and you still want to support flashsockets // you can set the `flash policy port` to -1 'flash policy port': 10843, // Used by the HTTP transports. The Socket.IO server buffers HTTP request bodies up to this limit. // This limit is not applied to websocket or flashsockets. 'destroy buffer size': '10E7', // Do we need to destroy non-socket.io upgrade requests? 'destroy upgrade': true, // Should Sails/Socket.io serve the `socket.io.js` client? // (as well as WebSocketMain.swf for Flash sockets, etc.) 'browser client': true, // Cache the Socket.IO file generation in the memory of the process // to speed up the serving of the static files. 'browser client cache': true, // Does Socket.IO need to send a minified build of the static client script? 'browser client minification': false, // Does Socket.IO need to send an ETag header for the static requests? 'browser client etag': false, // Adds a Cache-Control: private, x-gzip-ok="", max-age=31536000 header to static requests, // but only if the file is requested with a version number like /socket.io/socket.io.v0.9.9.js. 'browser client expires': 315360000, // Does Socket.IO need to GZIP the static files? // This process is only done once and the computed output is stored in memory. // So we don't have to spawn a gzip process for each request. 'browser client gzip': false, // Optional override function to serve all static files, // including socket.io.js et al. // Of the form :: function (req, res) { /* serve files */ } 'browser client handler': false, // Meant to be used when running socket.io behind a proxy. // Should be set to true when you want the location handshake to match the protocol of the origin. // This fixes issues with terminating the SSL in front of Node // and forcing location to think it's wss instead of ws. 'match origin protocol': false, // Direct access to the socket.io MQ store config // The 'adapter' property is the preferred method // (`undefined` indicates that Sails should defer to the 'adapter' config) store: undefined, // A logger instance that is used to output log information. // (`undefined` indicates deferment to the main Sails log config) logger: undefined, // The amount of detail that the server should output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log level': undefined, // Whether to color the log type when output to the logger. // (`undefined` indicates deferment to the main Sails log config) 'log colors': undefined, // A Static instance that is used to serve the socket.io client and its dependencies. // (`undefined` indicates use default) 'static': undefined, // The entry point where Socket.IO starts looking for incoming connections. // This should be the same between the client and the server. resource: '/socket.io' };
mit
SamsungSDS-Contest/2017Guide-Kata
C/Kata2/ConstructionManager.cpp
25737
#include "ConstructionManager.h" using namespace MyBot; ConstructionManager::ConstructionManager() : reservedMinerals(0) , reservedGas(0) { } // add a new building to be constructed void ConstructionManager::addConstructionTask(BWAPI::UnitType type, BWAPI::TilePosition desiredPosition) { if (type == BWAPI::UnitTypes::None || type == BWAPI::UnitTypes::Unknown) { return; } if (desiredPosition == BWAPI::TilePositions::None || desiredPosition == BWAPI::TilePositions::Invalid || desiredPosition == BWAPI::TilePositions::Unknown) { return; } ConstructionTask b(type, desiredPosition); b.status = ConstructionStatus::Unassigned; // reserve resources reservedMinerals += type.mineralPrice(); reservedGas += type.gasPrice(); constructionQueue.push_back(b); } // ConstructionTask 하나를 삭제한다 void ConstructionManager::cancelConstructionTask(BWAPI::UnitType type, BWAPI::TilePosition desiredPosition) { reservedMinerals -= type.mineralPrice(); reservedGas -= type.gasPrice(); ConstructionTask b(type, desiredPosition); auto & it = std::find(constructionQueue.begin(), constructionQueue.end(), b); if (it != constructionQueue.end()) { std::cout << std::endl << "Cancel Construction " << it->type.getName() << " at " << it->desiredPosition.x << "," << it->desiredPosition.y << std::endl; if (it->constructionWorker) { WorkerManager::Instance().setIdleWorker(it->constructionWorker); } if (it->finalPosition) { ConstructionPlaceFinder::Instance().freeTiles(it->finalPosition, it->type.tileWidth(), it->type.tileHeight()); } constructionQueue.erase(it); } } // ConstructionTask 여러개를 삭제한다 // 건설을 시작했었던 ConstructionTask 이기 때문에 reservedMinerals, reservedGas 는 건드리지 않는다 void ConstructionManager::removeCompletedConstructionTasks(const std::vector<ConstructionTask> & toRemove) { for (auto & b : toRemove) { auto & it = std::find(constructionQueue.begin(), constructionQueue.end(), b); if (it != constructionQueue.end()) { constructionQueue.erase(it); } } } // gets called every frame from GameCommander void ConstructionManager::update() { // 1초에 1번만 실행한다 //if (BWAPI::Broodwar->getFrameCount() % 24 != 0) return; // constructionQueue 에 들어있는 ConstructionTask 들은 // Unassigned -> Assigned (buildCommandGiven=false) -> Assigned (buildCommandGiven=true) -> UnderConstruction -> (Finished) 로 상태 변화된다 validateWorkersAndBuildings(); assignWorkersToUnassignedBuildings(); checkForStartedConstruction(); constructAssignedBuildings(); checkForDeadTerranBuilders(); checkForCompletedBuildings(); checkForDeadlockConstruction(); } // STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED void ConstructionManager::validateWorkersAndBuildings() { std::vector<ConstructionTask> toRemove; for (auto & b : constructionQueue) { if (b.status == ConstructionStatus::UnderConstruction) { // 건설 진행 도중 (공격을 받아서) 건설하려던 건물이 파괴된 경우, constructionQueue 에서 삭제한다 // 그렇지 않으면 (아마도 전투가 벌어지고있는) 기존 위치에 다시 건물을 지으려 할 것이기 때문. if (b.buildingUnit == nullptr || !b.buildingUnit->getType().isBuilding() || b.buildingUnit->getHitPoints() <= 0 || !b.buildingUnit->exists()) { std::cout << "Construction Failed case -> remove ConstructionTask " << b.type.getName() << std::endl; toRemove.push_back(b); if (b.constructionWorker) { WorkerManager::Instance().setIdleWorker(b.constructionWorker); } } } } removeCompletedConstructionTasks(toRemove); } // STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM void ConstructionManager::assignWorkersToUnassignedBuildings() { // for each building that doesn't have a builder, assign one for (ConstructionTask & b : constructionQueue) { if (b.status != ConstructionStatus::Unassigned) { continue; } //std::cout << "find build place near desiredPosition " << b.desiredPosition.x << "," << b.desiredPosition.y << std::endl; // 건설 일꾼이 Unassigned 인 상태에서 getBuildLocationNear 로 건설할 위치를 다시 정한다. -> Assigned BWAPI::TilePosition testLocation = ConstructionPlaceFinder::Instance().getBuildLocationNear(b.type, b.desiredPosition); // std::cout << "ConstructionPlaceFinder Selected Location : " << testLocation.x << "," << testLocation.y << std::endl; if (testLocation == BWAPI::TilePositions::None || testLocation == BWAPI::TilePositions::Invalid || testLocation.isValid() == false) { // 지금 건물 지을 장소를 전혀 찾을 수 없게 된 경우는, // desiredPosition 주위에 다른 건물/유닛들이 있게 되었거나, Pylon 이 파괴되었거나, Creep 이 없어진 경우이고, // 대부분 다른 건물/유닛들이 있게된 경우이므로 다음 frame 에서 다시 지을 곳을 탐색한다 continue; } // grab a worker unit from WorkerManager which is closest to this final position // 건설을 못하는 worker 가 계속 construction worker 로 선정될 수 있다. 직전에 선정되었었던 worker 는 다시 선정안하도록 한다 BWAPI::Unit workerToAssign = WorkerManager::Instance().chooseConstuctionWorkerClosestTo(b.type, testLocation, true, b.lastConstructionWorkerID); //std::cout << "assignWorkersToUnassignedBuildings - chooseConstuctionWorkerClosest for " << b.type.getName().c_str() << " to worker near " << testLocation.x << "," << testLocation.y << std::endl; if (workerToAssign) { //std::cout << "set ConstuctionWorker " << workerToAssign->getID() << std::endl; b.constructionWorker = workerToAssign; b.finalPosition = testLocation; b.status = ConstructionStatus::Assigned; // reserve this building's space ConstructionPlaceFinder::Instance().reserveTiles(testLocation, b.type.tileWidth(), b.type.tileHeight()); b.lastConstructionWorkerID = b.constructionWorker->getID(); } } } // STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED void ConstructionManager::constructAssignedBuildings() { for (auto & b : constructionQueue) { if (b.status != ConstructionStatus::Assigned) { continue; } /* if (b.constructionWorker == nullptr) { std::cout << b.type.c_str() << " constructionWorker null" << std::endl; } else { std::cout << b.type.c_str() << " constructionWorker " << b.constructionWorker->getID() << " exists " << b.constructionWorker->exists() << " isIdle " << b.constructionWorker->isIdle() << " isConstructing " << b.constructionWorker->isConstructing() << " isMorphing " << b.constructionWorker->isMorphing() << std::endl; } */ // 일꾼에게 build 명령을 내리기 전에는 isConstructing = false 이다 // 아직 탐색하지 않은 곳에 대해서는 build 명령을 내릴 수 없다 // 일꾼에게 build 명령을 내리면, isConstructing = true 상태가 되어 이동을 하다가 // build 를 실행할 수 없는 상황이라고 판단되면 isConstructing = false 상태가 된다 // build 를 실행할 수 있으면, 프로토스 / 테란 종족의 경우 일꾼이 build 를 실행하고 // 저그 종족 건물 중 Extractor 건물이 아닌 다른 건물의 경우 일꾼이 exists = true, isConstructing = true, isMorphing = true 가 되고, 일꾼 ID 가 건물 ID가 된다 // 저그 종족 건물 중 Extractor 건물의 경우 일꾼이 exists = false, isConstructing = true, isMorphing = true 가 된 후, 일꾼 ID 가 건물 ID가 된다. // Extractor 건물 빌드를 도중에 취소하면, 새로운 ID 를 가진 일꾼이 된다 // 일꾼이 Assigned 된 후, UnderConstruction 상태로 되기 전, 즉 일꾼이 이동 중에 일꾼이 죽은 경우, 건물을 Unassigned 상태로 되돌려 일꾼을 다시 Assign 하도록 한다 if (b.constructionWorker == nullptr || b.constructionWorker->exists() == false || b.constructionWorker->getHitPoints() <= 0) { // 저그 종족 건물 중 Extractor 건물의 경우 일꾼이 exists = false 이지만 isConstructing = true 가 되므로, 일꾼이 죽은 경우가 아니다 if (b.type == BWAPI::UnitTypes::Zerg_Extractor && b.constructionWorker != nullptr && b.constructionWorker->isConstructing() == true) { continue; } //std::cout << "unassign " << b.type.getName().c_str() << " worker " << b.constructionWorker->getID() << ", because it is not exists" << std::endl; // Unassigned 된 상태로 되돌린다 WorkerManager::Instance().setIdleWorker(b.constructionWorker); // free the previous location in reserved ConstructionPlaceFinder::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight()); b.constructionWorker = nullptr; b.buildCommandGiven = false; b.finalPosition = BWAPI::TilePositions::None; b.status = ConstructionStatus::Unassigned; } // if that worker is not currently constructing // 일꾼이 build command 를 받으면 isConstructing = true 가 되고 건설을 하기위해 이동하는데, // isConstructing = false 가 되었다는 것은, build command 를 수행할 수 없어 게임에서 해당 임무가 취소되었다는 것이다 else if (b.constructionWorker->isConstructing() == false) { // if we haven't explored the build position, first we mush go there // 한번도 안가본 곳에는 build 커맨드 자체를 지시할 수 없으므로, 일단 그곳으로 이동하게 한다 if (!isBuildingPositionExplored(b)) { CommandUtil::move(b.constructionWorker,BWAPI::Position(b.finalPosition)); } else if (b.buildCommandGiven == false) { //std::cout << b.type.c_str() << " build commanded to " << b.constructionWorker->getID() << ", buildCommandGiven true " << std::endl; // build command b.constructionWorker->build(b.type, b.finalPosition); WorkerManager::Instance().setConstructionWorker(b.constructionWorker, b.type); // set the buildCommandGiven flag to true b.buildCommandGiven = true; b.lastBuildCommandGivenFrame = BWAPI::Broodwar->getFrameCount(); b.lastConstructionWorkerID = b.constructionWorker->getID(); } // if this is not the first time we've sent this guy to build this // 일꾼에게 build command 를 주었지만, 건설시작하기전에 도중에 자원이 미달하게 되었거나, 해당 장소에 다른 유닛들이 있어서 건설을 시작 못하게 되거나, Pylon 이나 Creep 이 없어진 경우 등이 발생할 수 있다 // 이 경우, 해당 일꾼의 build command 를 해제하고, 건물 상태를 Unassigned 로 바꿔서, 다시 건물 위치를 정하고, 다른 일꾼을 지정하는 식으로 처리한다 else { if (BWAPI::Broodwar->getFrameCount() - b.lastBuildCommandGivenFrame > 24) { //std::cout << b.type.c_str() // << " constructionWorker " << b.constructionWorker->getID() // << " buildCommandGiven " << b.buildCommandGiven // << " lastBuildCommandGivenFrame " << b.lastBuildCommandGivenFrame // << " lastConstructionWorkerID " << b.lastConstructionWorkerID // << " exists " << b.constructionWorker->exists() // << " isIdle " << b.constructionWorker->isIdle() // << " isConstructing " << b.constructionWorker->isConstructing() // << " isMorphing " << b.constructionWorker->isMorphing() << std::endl; //std::cout << b.type.c_str() << "(" << b.finalPosition.x << "," << b.finalPosition.y << ") buildCommandGiven -> but now Unassigned " << std::endl; // tell worker manager the unit we had is not needed now, since we might not be able // to get a valid location soon enough WorkerManager::Instance().setIdleWorker(b.constructionWorker); // free the previous location in reserved ConstructionPlaceFinder::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight()); // nullify its current builder unit b.constructionWorker = nullptr; // nullify its current builder unit b.finalPosition = BWAPI::TilePositions::None; // reset the build command given flag b.buildCommandGiven = false; // add the building back to be assigned b.status = ConstructionStatus::Unassigned; } } } } } // STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION void ConstructionManager::checkForStartedConstruction() { // for each building unit which is being constructed for (auto & buildingThatStartedConstruction : BWAPI::Broodwar->self()->getUnits()) { // filter out units which aren't buildings under construction if (!buildingThatStartedConstruction->getType().isBuilding() || !buildingThatStartedConstruction->isBeingConstructed()) { continue; } //std::cout << "buildingThatStartedConstruction " << buildingThatStartedConstruction->getType().getName().c_str() << " isBeingConstructed at " << buildingThatStartedConstruction->getTilePosition().x << "," << buildingThatStartedConstruction->getTilePosition().y << std::endl; // check all our building status objects to see if we have a match and if we do, update it for (auto & b : constructionQueue) { if (b.status != ConstructionStatus::Assigned) { continue; } // check if the positions match. Worker just started construction. if (b.finalPosition == buildingThatStartedConstruction->getTilePosition()) { //std::cout << "construction " << b.type.getName().c_str() << " started at " << b.finalPosition.x << "," << b.finalPosition.y << std::endl; // the resources should now be spent, so unreserve them reservedMinerals -= buildingThatStartedConstruction->getType().mineralPrice(); reservedGas -= buildingThatStartedConstruction->getType().gasPrice(); // flag it as started and set the buildingUnit b.underConstruction = true; b.buildingUnit = buildingThatStartedConstruction; // if we are zerg, make the buildingUnit nullptr since it's morphed or destroyed // Extractor 의 경우 destroyed 되고, 그외 건물의 경우 morphed 된다 if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg) { b.constructionWorker = nullptr; } // if we are protoss, give the worker back to worker manager else if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Protoss) { WorkerManager::Instance().setIdleWorker(b.constructionWorker); b.constructionWorker = nullptr; } // free this space ConstructionPlaceFinder::Instance().freeTiles(b.finalPosition,b.type.tileWidth(),b.type.tileHeight()); // put it in the under construction vector b.status = ConstructionStatus::UnderConstruction; // only one building will match break; } } } } // STEP 5: IF WE ARE TERRAN, THIS MATTERS // 테란은 건설을 시작한 후, 건설 도중에 일꾼이 죽을 수 있다. 이 경우, 건물에 대해 다시 다른 SCV를 할당한다 // 참고로, 프로토스 / 저그는 건설을 시작하면 일꾼 포인터를 nullptr 로 만들기 때문에 (constructionWorker = nullptr) 건설 도중에 죽은 일꾼을 신경쓸 필요 없다 void ConstructionManager::checkForDeadTerranBuilders() { if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran) { if (BWAPI::Broodwar->self()->completedUnitCount(BWAPI::UnitTypes::Terran_SCV) <= 0) return; // for each of our buildings under construction for (auto & b : constructionQueue) { // if a terran building whose worker died mid construction, // send the right click command to the buildingUnit to resume construction if (b.status == ConstructionStatus::UnderConstruction) { if (b.buildingUnit->isCompleted()) continue; if (b.constructionWorker == nullptr || b.constructionWorker->exists() == false || b.constructionWorker->getHitPoints() <= 0 ) { //std::cout << "checkForDeadTerranBuilders - chooseConstuctionWorkerClosest for " << b.type.getName().c_str() << " to worker near " << b.finalPosition.x << "," << b.finalPosition.y << std::endl; // grab a worker unit from WorkerManager which is closest to this final position BWAPI::Unit workerToAssign = WorkerManager::Instance().chooseConstuctionWorkerClosestTo(b.type, b.finalPosition, true, b.lastConstructionWorkerID); if (workerToAssign) { //std::cout << "set ConstuctionWorker " << workerToAssign->getID() << std::endl; b.constructionWorker = workerToAssign; //b.status 는 계속 UnderConstruction 로 둔다. Assigned 로 바꾸면, 결국 Unassigned 가 되어서 새로 짓게 되기 때문이다 //b.status = ConstructionStatus::Assigned; CommandUtil::rightClick(b.constructionWorker, b.buildingUnit); b.buildCommandGiven = true; b.lastBuildCommandGivenFrame = BWAPI::Broodwar->getFrameCount(); b.lastConstructionWorkerID = b.constructionWorker->getID(); } } } } } } // STEP 6: CHECK FOR COMPLETED BUILDINGS void ConstructionManager::checkForCompletedBuildings() { std::vector<ConstructionTask> toRemove; // for each of our buildings under construction for (auto & b : constructionQueue) { if (b.status != ConstructionStatus::UnderConstruction) { continue; } // if the unit has completed if (b.buildingUnit->isCompleted()) { //std::cout << "construction " << b.type.getName().c_str() << " completed at " << b.finalPosition.x << "," << b.finalPosition.y << std::endl; // if we are terran, give the worker back to worker manager if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran) { WorkerManager::Instance().setIdleWorker(b.constructionWorker); } // remove this unit from the under construction vector toRemove.push_back(b); } } removeCompletedConstructionTasks(toRemove); } void ConstructionManager::checkForDeadlockConstruction() { std::vector<ConstructionTask> toCancel; for (auto & b : constructionQueue) { if (b.status != ConstructionStatus::UnderConstruction) { // BuildManager가 판단했을때 Construction 가능조건이 갖춰져서 ConstructionManager의 ConstructionQueue 에 들어갔는데, // 선행 건물이 파괴되서 Construction을 수행할 수 없게 되었거나, // 일꾼이 다 사망하는 등 게임상황이 바뀌어서, 계속 ConstructionQueue 에 남아있게 되는 dead lock 상황이 된다 // 선행 건물을 BuildQueue에 추가해넣을지, 해당 ConstructionQueueItem 을 삭제할지 전략적으로 판단해야 한다 BWAPI::UnitType unitType = b.type; BWAPI::UnitType producerType = b.type.whatBuilds().first; const std::map< BWAPI::UnitType, int >& requiredUnits = unitType.requiredUnits(); BWTA::Region* desiredPositionRegion = BWTA::getRegion(b.desiredPosition); bool isDeadlockCase = false; // 건물을 생산하는 유닛이나, 유닛을 생산하는 건물이 존재하지 않고, 건설 예정이지도 않으면 dead lock if (BuildManager::Instance().isProducerWillExist(producerType) == false) { isDeadlockCase = true; } // Refinery 건물의 경우, 건물 지을 장소를 찾을 수 없게 되었거나, 건물 지을 수 있을거라고 판단했는데 이미 Refinery 가 지어져있는 경우, dead lock if (!isDeadlockCase && unitType == InformationManager::Instance().getRefineryBuildingType()) { bool hasAvailableGeyser = true; BWAPI::TilePosition testLocation; if (b.finalPosition != BWAPI::TilePositions::None && b.finalPosition != BWAPI::TilePositions::Invalid && b.finalPosition.isValid()) { testLocation = b.finalPosition; } else { testLocation = ConstructionPlaceFinder::Instance().getBuildLocationNear(b.type, b.desiredPosition); } // Refinery 를 지으려는 장소를 찾을 수 없으면 dead lock if (testLocation == BWAPI::TilePositions::None || testLocation == BWAPI::TilePositions::Invalid || testLocation.isValid() == false) { std::cout << "Construction Dead lock case -> Cann't find place to construct " << b.type.getName() << std::endl; hasAvailableGeyser = false; } else { // Refinery 를 지으려는 장소에 Refinery 가 이미 건설되어 있다면 dead lock BWAPI::Unitset uot = BWAPI::Broodwar->getUnitsOnTile(testLocation); for (auto & u : uot) { if (u->getType().isRefinery() && u->exists() ) { hasAvailableGeyser = false; break; } } if (hasAvailableGeyser == false) { std::cout << "Construction Dead lock case -> Refinery Building was built already at " << testLocation.x << ", " << testLocation.y << std::endl; } } if (hasAvailableGeyser == false) { isDeadlockCase = true; } } // 정찰결과 혹은 전투결과, 건설 장소가 아군 점령 Region 이 아니고, 적군이 점령한 Region 이 되었으면 일반적으로는 현실적으로 dead lock 이 된다 // (포톤캐논 러시이거나, 적군 점령 Region 근처에서 테란 건물 건설하는 경우에는 예외일테지만..) if (!isDeadlockCase && InformationManager::Instance().getOccupiedRegions(InformationManager::Instance().selfPlayer).find(desiredPositionRegion) == InformationManager::Instance().getOccupiedRegions(InformationManager::Instance().selfPlayer).end() && InformationManager::Instance().getOccupiedRegions(InformationManager::Instance().enemyPlayer).find(desiredPositionRegion) != InformationManager::Instance().getOccupiedRegions(InformationManager::Instance().enemyPlayer).end()) { isDeadlockCase = true; } // 선행 건물/유닛이 있는데 if (!isDeadlockCase && requiredUnits.size() > 0) { for (auto & u : requiredUnits) { BWAPI::UnitType requiredUnitType = u.first; if (requiredUnitType != BWAPI::UnitTypes::None) { // 선행 건물 / 유닛이 존재하지 않고, 생산 중이지도 않고 if (BWAPI::Broodwar->self()->completedUnitCount(requiredUnitType) == 0 && BWAPI::Broodwar->self()->incompleteUnitCount(requiredUnitType) == 0) { // 선행 건물이 건설 예정이지도 않으면 dead lock if (requiredUnitType.isBuilding()) { if (ConstructionManager::Instance().getConstructionQueueItemCount(requiredUnitType) == 0) { isDeadlockCase = true; } } } } } } if (isDeadlockCase) { toCancel.push_back(b); } } } for (auto & i : toCancel) { cancelConstructionTask(i.type, i.desiredPosition); } } // COMPLETED bool ConstructionManager::isEvolvedBuilding(BWAPI::UnitType type) { if (type == BWAPI::UnitTypes::Zerg_Sunken_Colony || type == BWAPI::UnitTypes::Zerg_Spore_Colony || type == BWAPI::UnitTypes::Zerg_Lair || type == BWAPI::UnitTypes::Zerg_Hive || type == BWAPI::UnitTypes::Zerg_Greater_Spire) { return true; } return false; } bool ConstructionManager::isBuildingPositionExplored(const ConstructionTask & b) const { BWAPI::TilePosition tile = b.finalPosition; // for each tile where the building will be built for (int x=0; x<b.type.tileWidth(); ++x) { for (int y=0; y<b.type.tileHeight(); ++y) { if (!BWAPI::Broodwar->isExplored(tile.x + x,tile.y + y)) { return false; } } } return true; } int ConstructionManager::getReservedMinerals() { return reservedMinerals; } int ConstructionManager::getReservedGas() { return reservedGas; } ConstructionManager & ConstructionManager::Instance() { static ConstructionManager instance; return instance; } std::vector<BWAPI::UnitType> ConstructionManager::buildingsQueued() { std::vector<BWAPI::UnitType> buildingsQueued; for (const auto & b : constructionQueue) { if (b.status == ConstructionStatus::Unassigned || b.status == ConstructionStatus::Assigned) { buildingsQueued.push_back(b.type); } } return buildingsQueued; } // constructionQueue에 해당 type 의 Item 이 존재하는지 카운트한다. queryTilePosition 을 입력한 경우, 위치간 거리까지도 고려한다 int ConstructionManager::getConstructionQueueItemCount(BWAPI::UnitType queryType, BWAPI::TilePosition queryTilePosition) { // queryTilePosition 을 입력한 경우, 거리의 maxRange. 타일단위 int maxRange = 16; const BWAPI::Point<int, 32> queryTilePositionPoint(queryTilePosition.x, queryTilePosition.y); int count = 0; for (auto & b : constructionQueue) { if (b.type == queryType) { if (queryType.isBuilding() && queryTilePosition != BWAPI::TilePositions::None) { if (queryTilePositionPoint.getDistance(b.desiredPosition) <= maxRange) { count++; } } else { count++; } } } return count; } std::vector<ConstructionTask> * ConstructionManager::getConstructionQueue() { return & constructionQueue; }
mit
uspgamedev/3D-experiment
externals/Ogre/Components/RTShaderSystem/src/OgreShaderFFPTexturing.cpp
38613
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreShaderFFPTexturing.h" #ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS #include "OgreShaderFFPRenderState.h" #include "OgreShaderProgram.h" #include "OgreShaderParameter.h" #include "OgreShaderProgramSet.h" #include "OgreTextureUnitState.h" #include "OgreFrustum.h" #include "OgrePass.h" namespace Ogre { namespace RTShader { /************************************************************************/ /* */ /************************************************************************/ String FFPTexturing::Type = "FFP_Texturing"; #define _INT_VALUE(f) (*(int*)(&(f))) const String c_ParamTexelEx("texel_"); //----------------------------------------------------------------------- FFPTexturing::FFPTexturing() { } //----------------------------------------------------------------------- const String& FFPTexturing::getType() const { return Type; } //----------------------------------------------------------------------- int FFPTexturing::getExecutionOrder() const { return FFP_TEXTURING; } //----------------------------------------------------------------------- bool FFPTexturing::resolveParameters(ProgramSet* programSet) { for (unsigned int i=0; i < mTextureUnitParamsList.size(); ++i) { TextureUnitParams* curParams = &mTextureUnitParamsList[i]; if (false == resolveUniformParams(curParams, programSet)) return false; if (false == resolveFunctionsParams(curParams, programSet)) return false; } return true; } //----------------------------------------------------------------------- bool FFPTexturing::resolveUniformParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet) { Program* vsProgram = programSet->getCpuVertexProgram(); Program* psProgram = programSet->getCpuFragmentProgram(); bool hasError = false; // Resolve texture sampler parameter. textureUnitParams->mTextureSampler = psProgram->resolveParameter(textureUnitParams->mTextureSamplerType, textureUnitParams->mTextureSamplerIndex, (uint16)GPV_GLOBAL, "gTextureSampler"); hasError |= !(textureUnitParams->mTextureSampler.get()); // Resolve texture matrix parameter. if (needsTextureMatrix(textureUnitParams->mTextureUnitState)) { textureUnitParams->mTextureMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_TEXTURE_MATRIX, textureUnitParams->mTextureSamplerIndex); hasError |= !(textureUnitParams->mTextureMatrix.get()); } switch (textureUnitParams->mTexCoordCalcMethod) { case TEXCALC_NONE: break; // Resolve World + View matrices. case TEXCALC_ENVIRONMENT_MAP: case TEXCALC_ENVIRONMENT_MAP_PLANAR: case TEXCALC_ENVIRONMENT_MAP_NORMAL: //TODO: change the following 'mWorldITMatrix' member to 'mWorldViewITMatrix' mWorldITMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX, 0); mViewMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_VIEW_MATRIX, 0); mWorldMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLD_MATRIX, 0); hasError |= !(mWorldITMatrix.get()) || !(mViewMatrix.get()) || !(mWorldITMatrix.get()); break; case TEXCALC_ENVIRONMENT_MAP_REFLECTION: mWorldMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLD_MATRIX, 0); mWorldITMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX, 0); mViewMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_VIEW_MATRIX, 0); hasError |= !(mWorldMatrix.get()) || !(mWorldITMatrix.get()) || !(mViewMatrix.get()); break; case TEXCALC_PROJECTIVE_TEXTURE: mWorldMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLD_MATRIX, 0); textureUnitParams->mTextureViewProjImageMatrix = vsProgram->resolveParameter(GCT_MATRIX_4X4, -1, (uint16)GPV_LIGHTS, "gTexViewProjImageMatrix"); hasError |= !(mWorldMatrix.get()) || !(textureUnitParams->mTextureViewProjImageMatrix.get()); const TextureUnitState::EffectMap& effectMap = textureUnitParams->mTextureUnitState->getEffects(); TextureUnitState::EffectMap::const_iterator effi; for (effi = effectMap.begin(); effi != effectMap.end(); ++effi) { if (effi->second.type == TextureUnitState::ET_PROJECTIVE_TEXTURE) { textureUnitParams->mTextureProjector = effi->second.frustum; break; } } hasError |= !(textureUnitParams->mTextureProjector); break; } if (hasError) { OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Not all parameters could be constructed for the sub-render state.", "FFPTexturing::resolveUniformParams" ); } return true; } //----------------------------------------------------------------------- bool FFPTexturing::resolveFunctionsParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet) { Program* vsProgram = programSet->getCpuVertexProgram(); Program* psProgram = programSet->getCpuFragmentProgram(); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); Parameter::Content texCoordContent = Parameter::SPC_UNKNOWN; bool hasError = false; switch (textureUnitParams->mTexCoordCalcMethod) { case TEXCALC_NONE: // Resolve explicit vs input texture coordinates. if (textureUnitParams->mTextureMatrix.get() == NULL) texCoordContent = Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet()); textureUnitParams->mVSInputTexCoord = vsMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES, textureUnitParams->mTextureUnitState->getTextureCoordSet(), Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet()), textureUnitParams->mVSInTextureCoordinateType); hasError |= !(textureUnitParams->mVSInputTexCoord.get()); break; case TEXCALC_ENVIRONMENT_MAP: case TEXCALC_ENVIRONMENT_MAP_PLANAR: case TEXCALC_ENVIRONMENT_MAP_NORMAL: // Resolve vertex normal. mVSInputPos = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4); mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3); hasError |= !(mVSInputNormal.get()) || !(mVSInputPos.get()); break; case TEXCALC_ENVIRONMENT_MAP_REFLECTION: // Resolve vertex normal. mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3); // Resolve vertex position. mVSInputPos = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4); hasError |= !(mVSInputNormal.get()) || !(mVSInputPos.get()); break; case TEXCALC_PROJECTIVE_TEXTURE: // Resolve vertex position. mVSInputPos = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4); hasError |= !(mVSInputPos.get()); break; } // Resolve vs output texture coordinates. textureUnitParams->mVSOutputTexCoord = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, texCoordContent, textureUnitParams->mVSOutTextureCoordinateType); // Resolve ps input texture coordinates. textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES, textureUnitParams->mVSOutputTexCoord->getIndex(), textureUnitParams->mVSOutputTexCoord->getContent(), textureUnitParams->mVSOutTextureCoordinateType); const ShaderParameterList& inputParams = psMain->getInputParameters(); const ShaderParameterList& localParams = psMain->getLocalParameters(); mPSDiffuse = psMain->getParameterByContent(inputParams, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4); if (mPSDiffuse.get() == NULL) { mPSDiffuse = psMain->getParameterByContent(localParams, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4); } mPSSpecular = psMain->getParameterByContent(inputParams, Parameter::SPC_COLOR_SPECULAR, GCT_FLOAT4); if (mPSSpecular.get() == NULL) { mPSSpecular = psMain->getParameterByContent(localParams, Parameter::SPC_COLOR_SPECULAR, GCT_FLOAT4); } mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4); hasError |= !(textureUnitParams->mVSOutputTexCoord.get()) || !(textureUnitParams->mPSInputTexCoord.get()) || !(mPSDiffuse.get()) || !(mPSSpecular.get()) || !(mPSOutDiffuse.get()); if (hasError) { OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Not all parameters could be constructed for the sub-render state.", "FFPTexturing::resolveFunctionsParams" ); } return true; } //----------------------------------------------------------------------- bool FFPTexturing::resolveDependencies(ProgramSet* programSet) { Program* vsProgram = programSet->getCpuVertexProgram(); Program* psProgram = programSet->getCpuFragmentProgram(); vsProgram->addDependency(FFP_LIB_COMMON); vsProgram->addDependency(FFP_LIB_TEXTURING); psProgram->addDependency(FFP_LIB_COMMON); psProgram->addDependency(FFP_LIB_TEXTURING); return true; } //----------------------------------------------------------------------- bool FFPTexturing::addFunctionInvocations(ProgramSet* programSet) { Program* vsProgram = programSet->getCpuVertexProgram(); Program* psProgram = programSet->getCpuFragmentProgram(); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); int internalCounter = 0; for (unsigned int i=0; i < mTextureUnitParamsList.size(); ++i) { TextureUnitParams* curParams = &mTextureUnitParamsList[i]; if (false == addVSFunctionInvocations(curParams, vsMain)) return false; if (false == addPSFunctionInvocations(curParams, psMain, internalCounter)) return false; } return true; } //----------------------------------------------------------------------- bool FFPTexturing::addVSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* vsMain) { FunctionInvocation* texCoordCalcFunc = NULL; switch (textureUnitParams->mTexCoordCalcMethod) { case TEXCALC_NONE: if (textureUnitParams->mTextureMatrix.get() == NULL) { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(textureUnitParams->mVSInputTexCoord, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } else { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_TRANSFORM_TEXCOORD, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(textureUnitParams->mTextureMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSInputTexCoord, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } break; case TEXCALC_ENVIRONMENT_MAP: case TEXCALC_ENVIRONMENT_MAP_PLANAR: if (textureUnitParams->mTextureMatrix.get() == NULL) { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_SPHERE, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); //TODO: Add field member mWorldViewITMatrix texCoordCalcFunc->pushOperand(mWorldMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputPos, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } else { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_SPHERE, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputPos, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mTextureMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } break; case TEXCALC_ENVIRONMENT_MAP_REFLECTION: if (textureUnitParams->mTextureMatrix.get() == NULL) { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_REFLECT, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputPos, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } else { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_REFLECT, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mTextureMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputPos, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } break; case TEXCALC_ENVIRONMENT_MAP_NORMAL: if (textureUnitParams->mTextureMatrix.get() == NULL) { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_NORMAL, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } else { texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_ENV_NORMAL, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldITMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mViewMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mTextureMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputNormal, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); } break; case TEXCALC_PROJECTIVE_TEXTURE: texCoordCalcFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_GENERATE_TEXCOORD_PROJECTION, FFP_VS_TEXTURING, textureUnitParams->mTextureSamplerIndex); texCoordCalcFunc->pushOperand(mWorldMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mTextureViewProjImageMatrix, Operand::OPS_IN); texCoordCalcFunc->pushOperand(mVSInputPos, Operand::OPS_IN); texCoordCalcFunc->pushOperand(textureUnitParams->mVSOutputTexCoord, Operand::OPS_OUT); break; } if (texCoordCalcFunc != NULL) vsMain->addAtomInstance(texCoordCalcFunc); return true; } //----------------------------------------------------------------------- bool FFPTexturing::addPSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* psMain, int& internalCounter) { const LayerBlendModeEx& colourBlend = textureUnitParams->mTextureUnitState->getColourBlendMode(); const LayerBlendModeEx& alphaBlend = textureUnitParams->mTextureUnitState->getAlphaBlendMode(); ParameterPtr source1; ParameterPtr source2; int groupOrder = FFP_PS_TEXTURING; // Add texture sampling code. ParameterPtr texel = psMain->resolveLocalParameter(Parameter::SPS_UNKNOWN, 0, c_ParamTexelEx + StringConverter::toString(textureUnitParams->mTextureSamplerIndex), GCT_FLOAT4); addPSSampleTexelInvocation(textureUnitParams, psMain, texel, FFP_PS_SAMPLING, internalCounter); // Build colour argument for source1. source1 = psMain->resolveLocalParameter(Parameter::SPS_UNKNOWN, 0, "source1", GCT_FLOAT4); addPSArgumentInvocations(psMain, source1, texel, textureUnitParams->mTextureSamplerIndex, colourBlend.source1, colourBlend.colourArg1, colourBlend.alphaArg1, false, groupOrder, internalCounter); // Build colour argument for source2. source2 = psMain->resolveLocalParameter(Parameter::SPS_UNKNOWN, 0, "source2", GCT_FLOAT4); addPSArgumentInvocations(psMain, source2, texel, textureUnitParams->mTextureSamplerIndex, colourBlend.source2, colourBlend.colourArg2, colourBlend.alphaArg2, false, groupOrder, internalCounter); bool needDifferentAlphaBlend = false; if (alphaBlend.operation != colourBlend.operation || alphaBlend.source1 != colourBlend.source1 || alphaBlend.source2 != colourBlend.source2 || colourBlend.source1 == LBS_MANUAL || colourBlend.source2 == LBS_MANUAL || alphaBlend.source1 == LBS_MANUAL || alphaBlend.source2 == LBS_MANUAL) needDifferentAlphaBlend = true; // Build colours blend addPSBlendInvocations(psMain, source1, source2, texel, textureUnitParams->mTextureSamplerIndex, colourBlend, groupOrder, internalCounter, needDifferentAlphaBlend ? Operand::OPM_XYZ : Operand::OPM_ALL); // Case we need different alpha channel code. if (needDifferentAlphaBlend) { // Build alpha argument for source1. addPSArgumentInvocations(psMain, source1, texel, textureUnitParams->mTextureSamplerIndex, alphaBlend.source1, alphaBlend.colourArg1, alphaBlend.alphaArg1, true, groupOrder, internalCounter); // Build alpha argument for source2. addPSArgumentInvocations(psMain, source2, texel, textureUnitParams->mTextureSamplerIndex, alphaBlend.source2, alphaBlend.colourArg2, alphaBlend.alphaArg2, true, groupOrder, internalCounter); // Build alpha blend addPSBlendInvocations(psMain, source1, source2, texel, textureUnitParams->mTextureSamplerIndex, alphaBlend, groupOrder, internalCounter, Operand::OPM_W); } return true; } //----------------------------------------------------------------------- void FFPTexturing::addPSSampleTexelInvocation(TextureUnitParams* textureUnitParams, Function* psMain, const ParameterPtr& texel, int groupOrder, int& internalCounter) { FunctionInvocation* curFuncInvocation = NULL; if (textureUnitParams->mTexCoordCalcMethod == TEXCALC_PROJECTIVE_TEXTURE) curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_SAMPLE_TEXTURE_PROJ, groupOrder, internalCounter++); else curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_SAMPLE_TEXTURE, groupOrder, internalCounter++); curFuncInvocation->pushOperand(textureUnitParams->mTextureSampler, Operand::OPS_IN); curFuncInvocation->pushOperand(textureUnitParams->mPSInputTexCoord, Operand::OPS_IN); curFuncInvocation->pushOperand(texel, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); } //----------------------------------------------------------------------- void FFPTexturing::addPSArgumentInvocations(Function* psMain, ParameterPtr arg, ParameterPtr texel, int samplerIndex, LayerBlendSource blendSrc, const ColourValue& colourValue, Real alphaValue, bool isAlphaArgument, const int groupOrder, int& internalCounter) { FunctionInvocation* curFuncInvocation = NULL; switch(blendSrc) { case LBS_CURRENT: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); if (samplerIndex == 0) curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN); else curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_IN); curFuncInvocation->pushOperand(arg, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); break; case LBS_TEXTURE: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); curFuncInvocation->pushOperand(texel, Operand::OPS_IN); curFuncInvocation->pushOperand(arg, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); break; case LBS_DIFFUSE: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN); curFuncInvocation->pushOperand(arg, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); break; case LBS_SPECULAR: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); curFuncInvocation->pushOperand(mPSSpecular, Operand::OPS_IN); curFuncInvocation->pushOperand(arg, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); break; case LBS_MANUAL: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_CONSTRUCT, groupOrder, internalCounter++); if (isAlphaArgument) { curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(alphaValue), Operand::OPS_IN); } else { curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(colourValue.r), Operand::OPS_IN); curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(colourValue.g), Operand::OPS_IN); curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(colourValue.b), Operand::OPS_IN); curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(colourValue.a), Operand::OPS_IN); } curFuncInvocation->pushOperand(arg, Operand::OPS_OUT); psMain->addAtomInstance(curFuncInvocation); break; } } //----------------------------------------------------------------------- void FFPTexturing::addPSBlendInvocations(Function* psMain, ParameterPtr arg1, ParameterPtr arg2, ParameterPtr texel, int samplerIndex, const LayerBlendModeEx& blendMode, const int groupOrder, int& internalCounter, int targetChannels) { FunctionInvocation* curFuncInvocation = NULL; switch(blendMode.operation) { case LBX_SOURCE1: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_SOURCE2: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_MODULATE: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_MODULATE, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_MODULATE_X2: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_MODULATEX2, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_MODULATE_X4: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_MODULATEX4, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_ADD: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ADD, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_ADD_SIGNED: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ADDSIGNED, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_ADD_SMOOTH: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ADDSMOOTH, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_SUBTRACT: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_SUBTRACT, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_BLEND_DIFFUSE_ALPHA: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_SUBTRACT, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_W); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_BLEND_TEXTURE_ALPHA: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_LERP, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(texel, Operand::OPS_IN, Operand::OPM_W); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_BLEND_CURRENT_ALPHA: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_LERP, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); if (samplerIndex == 0) curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_W); else curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_IN, Operand::OPM_W); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_BLEND_MANUAL: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_LERP, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(ParameterFactory::createConstParamFloat(blendMode.factor), Operand::OPS_IN); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_DOTPRODUCT: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_DOTPRODUCT, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; case LBX_BLEND_DIFFUSE_COLOUR: curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_LERP, groupOrder, internalCounter++); curFuncInvocation->pushOperand(arg2, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(arg1, Operand::OPS_IN, targetChannels); curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN); curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT, targetChannels); psMain->addAtomInstance(curFuncInvocation); break; } } //----------------------------------------------------------------------- TexCoordCalcMethod FFPTexturing::getTexCalcMethod(TextureUnitState* textureUnitState) { TexCoordCalcMethod texCoordCalcMethod = TEXCALC_NONE; const TextureUnitState::EffectMap& effectMap = textureUnitState->getEffects(); TextureUnitState::EffectMap::const_iterator effi; for (effi = effectMap.begin(); effi != effectMap.end(); ++effi) { switch (effi->second.type) { case TextureUnitState::ET_ENVIRONMENT_MAP: if (effi->second.subtype == TextureUnitState::ENV_CURVED) { texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP; } else if (effi->second.subtype == TextureUnitState::ENV_PLANAR) { texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_PLANAR; } else if (effi->second.subtype == TextureUnitState::ENV_REFLECTION) { texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_REFLECTION; } else if (effi->second.subtype == TextureUnitState::ENV_NORMAL) { texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_NORMAL; } break; case TextureUnitState::ET_UVSCROLL: case TextureUnitState::ET_USCROLL: case TextureUnitState::ET_VSCROLL: case TextureUnitState::ET_ROTATE: case TextureUnitState::ET_TRANSFORM: break; case TextureUnitState::ET_PROJECTIVE_TEXTURE: texCoordCalcMethod = TEXCALC_PROJECTIVE_TEXTURE; break; } } return texCoordCalcMethod; } //----------------------------------------------------------------------- bool FFPTexturing::needsTextureMatrix(TextureUnitState* textureUnitState) { const TextureUnitState::EffectMap& effectMap = textureUnitState->getEffects(); TextureUnitState::EffectMap::const_iterator effi; for (effi = effectMap.begin(); effi != effectMap.end(); ++effi) { switch (effi->second.type) { case TextureUnitState::ET_UVSCROLL: case TextureUnitState::ET_USCROLL: case TextureUnitState::ET_VSCROLL: case TextureUnitState::ET_ROTATE: case TextureUnitState::ET_TRANSFORM: case TextureUnitState::ET_ENVIRONMENT_MAP: case TextureUnitState::ET_PROJECTIVE_TEXTURE: return true; } } const Ogre::Matrix4 matTexture = textureUnitState->getTextureTransform(); // Resolve texture matrix parameter. if (matTexture != Matrix4::IDENTITY) return true; return false; } //----------------------------------------------------------------------- void FFPTexturing::copyFrom(const SubRenderState& rhs) { const FFPTexturing& rhsTexture = static_cast<const FFPTexturing&>(rhs); setTextureUnitCount(rhsTexture.getTextureUnitCount()); for (unsigned int i=0; i < rhsTexture.getTextureUnitCount(); ++i) { setTextureUnit(i, rhsTexture.mTextureUnitParamsList[i].mTextureUnitState); } } //----------------------------------------------------------------------- bool FFPTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { //count the number of texture units we need to process size_t validTexUnits = 0; for (unsigned short i=0; i < srcPass->getNumTextureUnitStates(); ++i) { if (isProcessingNeeded(srcPass->getTextureUnitState(i))) { ++validTexUnits; } } setTextureUnitCount(validTexUnits); // Build texture stage sub states. for (unsigned short i=0; i < srcPass->getNumTextureUnitStates(); ++i) { TextureUnitState* texUnitState = srcPass->getTextureUnitState(i); if (isProcessingNeeded(texUnitState)) { setTextureUnit(i, texUnitState); } } return true; } //----------------------------------------------------------------------- void FFPTexturing::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) { for (unsigned int i=0; i < mTextureUnitParamsList.size(); ++i) { TextureUnitParams* curParams = &mTextureUnitParamsList[i]; if (curParams->mTextureProjector != NULL && curParams->mTextureViewProjImageMatrix.get() != NULL) { Matrix4 matTexViewProjImage; matTexViewProjImage = Matrix4::CLIPSPACE2DTOIMAGESPACE * curParams->mTextureProjector->getProjectionMatrixWithRSDepth() * curParams->mTextureProjector->getViewMatrix(); curParams->mTextureViewProjImageMatrix->setGpuParameter(matTexViewProjImage); } } } //----------------------------------------------------------------------- void FFPTexturing::setTextureUnitCount(size_t count) { mTextureUnitParamsList.resize(count); for (unsigned int i=0; i < count; ++i) { TextureUnitParams& curParams = mTextureUnitParamsList[i]; curParams.mTextureUnitState = NULL; curParams.mTextureProjector = NULL; curParams.mTextureSamplerIndex = 0; curParams.mTextureSamplerType = GCT_SAMPLER2D; curParams.mVSInTextureCoordinateType = GCT_FLOAT2; curParams.mVSOutTextureCoordinateType = GCT_FLOAT2; } } //----------------------------------------------------------------------- void FFPTexturing::setTextureUnit(unsigned short index, TextureUnitState* textureUnitState) { if (index >= mTextureUnitParamsList.size()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "FFPTexturing unit index out of bounds !!!", "FFPTexturing::setTextureUnit"); } if (textureUnitState->getBindingType() == TextureUnitState::BT_VERTEX) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "FFP Texture unit does not support vertex texture fetch !!!", "FFPTexturing::setTextureUnit"); } TextureUnitParams& curParams = mTextureUnitParamsList[index]; curParams.mTextureSamplerIndex = index; curParams.mTextureUnitState = textureUnitState; switch (curParams.mTextureUnitState->getTextureType()) { case TEX_TYPE_1D: curParams.mTextureSamplerType = GCT_SAMPLER1D; curParams.mVSInTextureCoordinateType = GCT_FLOAT1; break; case TEX_TYPE_2D: curParams.mTextureSamplerType = GCT_SAMPLER2D; curParams.mVSInTextureCoordinateType = GCT_FLOAT2; break; case TEX_TYPE_2D_RECT: curParams.mTextureSamplerType = GCT_SAMPLERRECT; curParams.mVSInTextureCoordinateType = GCT_FLOAT2; break; case TEX_TYPE_2D_ARRAY: curParams.mTextureSamplerType = GCT_SAMPLER2DARRAY; curParams.mVSInTextureCoordinateType = GCT_FLOAT3; break; case TEX_TYPE_3D: curParams.mTextureSamplerType = GCT_SAMPLER3D; curParams.mVSInTextureCoordinateType = GCT_FLOAT3; break; case TEX_TYPE_CUBE_MAP: curParams.mTextureSamplerType = GCT_SAMPLERCUBE; curParams.mVSInTextureCoordinateType = GCT_FLOAT3; break; } curParams.mVSOutTextureCoordinateType = curParams.mVSInTextureCoordinateType; curParams.mTexCoordCalcMethod = getTexCalcMethod(curParams.mTextureUnitState); if (curParams.mTexCoordCalcMethod == TEXCALC_PROJECTIVE_TEXTURE) curParams.mVSOutTextureCoordinateType = GCT_FLOAT3; } //----------------------------------------------------------------------- bool FFPTexturing::isProcessingNeeded(TextureUnitState* texUnitState) { return texUnitState->getBindingType() == TextureUnitState::BT_FRAGMENT; } //----------------------------------------------------------------------- const String& FFPTexturingFactory::getType() const { return FFPTexturing::Type; } //----------------------------------------------------------------------- SubRenderState* FFPTexturingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) { if (prop->name == "texturing_stage") { if(prop->values.size() == 1) { String modelType; if(false == SGScriptTranslator::getString(prop->values.front(), &modelType)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } if (modelType == "ffp") { return createOrRetrieveInstance(translator); } } } return NULL; } //----------------------------------------------------------------------- void FFPTexturingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) { ser->writeAttribute(4, "texturing_stage"); ser->writeValue("ffp"); } //----------------------------------------------------------------------- SubRenderState* FFPTexturingFactory::createInstanceImpl() { return OGRE_NEW FFPTexturing; } } } #endif
mit
cdnjs/cdnjs
ajax/libs/highcharts/9.3.3/es-modules/Stock/Indicators/ABands/ABandsIndicator.js
7782
/* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import MultipleLinesComposition from '../MultipleLinesComposition.js'; import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js'; var SMAIndicator = SeriesRegistry.seriesTypes.sma; import U from '../../../Core/Utilities.js'; var correctFloat = U.correctFloat, extend = U.extend, merge = U.merge; /* eslint-disable valid-jsdoc */ /** * @private */ function getBaseForBand(low, high, factor) { return (((correctFloat(high - low)) / ((correctFloat(high + low)) / 2)) * 1000) * factor; } /** * @private */ function getPointUB(high, base) { return high * (correctFloat(1 + 2 * base)); } /** * @private */ function getPointLB(low, base) { return low * (correctFloat(1 - 2 * base)); } /* eslint-enable valid-jsdoc */ /** * The ABands series type * * @private * @class * @name Highcharts.seriesTypes.abands * * @augments Highcharts.Series */ var ABandsIndicator = /** @class */ (function (_super) { __extends(ABandsIndicator, _super); function ABandsIndicator() { /* * * * Static Properties * * */ var _this = _super !== null && _super.apply(this, arguments) || this; /* * * * Properties * * */ _this.data = void 0; _this.options = void 0; _this.points = void 0; return _this; } /* * * * Functions * * */ ABandsIndicator.prototype.getValues = function (series, params) { var period = params.period, factor = params.factor, index = params.index, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, // Upperbands UB = [], // Lowerbands LB = [], // ABANDS array structure: // 0-date, 1-top line, 2-middle line, 3-bottom line ABANDS = [], // middle line, top line and bottom line ML, TL, BL, date, bandBase, pointSMA, ubSMA, lbSMA, low = 2, high = 1, xData = [], yData = [], slicedX, slicedY, i; if (yValLen < period) { return; } for (i = 0; i <= yValLen; i++) { // Get UB and LB values of every point. This condition // is necessary, because there is a need to calculate current // UB nad LB values simultaneously with given period SMA // in one for loop. if (i < yValLen) { bandBase = getBaseForBand(yVal[i][low], yVal[i][high], factor); UB.push(getPointUB(yVal[i][high], bandBase)); LB.push(getPointLB(yVal[i][low], bandBase)); } if (i >= period) { slicedX = xVal.slice(i - period, i); slicedY = yVal.slice(i - period, i); ubSMA = _super.prototype.getValues.call(this, { xData: slicedX, yData: UB.slice(i - period, i) }, { period: period }); lbSMA = _super.prototype.getValues.call(this, { xData: slicedX, yData: LB.slice(i - period, i) }, { period: period }); pointSMA = _super.prototype.getValues.call(this, { xData: slicedX, yData: slicedY }, { period: period, index: index }); date = pointSMA.xData[0]; TL = ubSMA.yData[0]; BL = lbSMA.yData[0]; ML = pointSMA.yData[0]; ABANDS.push([date, TL, ML, BL]); xData.push(date); yData.push([TL, ML, BL]); } } return { values: ABANDS, xData: xData, yData: yData }; }; /** * Acceleration bands (ABANDS). This series requires the `linkedTo` option * to be set and should be loaded after the * `stock/indicators/indicators.js`. * * @sample {highstock} stock/indicators/acceleration-bands * Acceleration Bands * * @extends plotOptions.sma * @mixes Highcharts.MultipleLinesMixin * @since 7.0.0 * @product highstock * @excluding allAreas, colorAxis, compare, compareBase, joinBy, keys, * navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, * stacking, * @requires stock/indicators/indicators * @requires stock/indicators/acceleration-bands * @optionparent plotOptions.abands */ ABandsIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, { /** * Option for fill color between lines in Accelleration bands Indicator. * * @sample {highstock} stock/indicators/indicator-area-fill * Background fill between lines. * * @type {Highcharts.Color} * @since 9.3.2 * @apioption plotOptions.abands.fillColor * */ params: { period: 20, /** * The algorithms factor value used to calculate bands. * * @product highstock */ factor: 0.001, index: 3 }, lineWidth: 1, topLine: { styles: { /** * Pixel width of the line. */ lineWidth: 1 } }, bottomLine: { styles: { /** * Pixel width of the line. */ lineWidth: 1 } }, dataGrouping: { approximation: 'averages' } }); return ABandsIndicator; }(SMAIndicator)); extend(ABandsIndicator.prototype, { areaLinesNames: ['top', 'bottom'], linesApiNames: ['topLine', 'bottomLine'], nameBase: 'Acceleration Bands', nameComponents: ['period', 'factor'], pointArrayMap: ['top', 'middle', 'bottom'], pointValKey: 'middle' }); MultipleLinesComposition.compose(ABandsIndicator); SeriesRegistry.registerSeriesType('abands', ABandsIndicator); /* * * * Default Export * * */ export default ABandsIndicator; /* * * * API Options * * */ /** * An Acceleration bands indicator. If the [type](#series.abands.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.abands * @since 7.0.0 * @product highstock * @excluding allAreas, colorAxis, compare, compareBase, dataParser, dataURL, * joinBy, keys, navigatorOptions, pointInterval, * pointIntervalUnit, pointPlacement, pointRange, pointStart, * stacking, showInNavigator, * @requires stock/indicators/indicators * @requires stock/indicators/acceleration-bands * @apioption series.abands */ ''; // to include the above in jsdoc
mit
cdnjs/cdnjs
ajax/libs/highcharts/9.2.2/es-modules/Accessibility/Components/LegendComponent.js
13164
/* * * * (c) 2009-2021 Øystein Moseng * * Accessibility component for chart legend. * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import A from '../../Core/Animation/AnimationUtilities.js'; var animObject = A.animObject; import Chart from '../../Core/Chart/Chart.js'; import H from '../../Core/Globals.js'; import Legend from '../../Core/Legend/Legend.js'; import U from '../../Core/Utilities.js'; var addEvent = U.addEvent, extend = U.extend, find = U.find, fireEvent = U.fireEvent, isNumber = U.isNumber, pick = U.pick, syncTimeout = U.syncTimeout; import AccessibilityComponent from '../AccessibilityComponent.js'; import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js'; import HTMLUtilities from '../Utils/HTMLUtilities.js'; var removeElement = HTMLUtilities.removeElement, stripHTMLTags = HTMLUtilities.stripHTMLTagsFromString; import ChartUtils from '../Utils/ChartUtilities.js'; var getChartTitle = ChartUtils.getChartTitle; /* eslint-disable no-invalid-this, valid-jsdoc */ /** * @private */ function scrollLegendToItem(legend, itemIx) { var itemPage = legend.allItems[itemIx].pageIx, curPage = legend.currentPage; if (typeof itemPage !== 'undefined' && itemPage + 1 !== curPage) { legend.scroll(1 + itemPage - curPage); } } /** * @private */ function shouldDoLegendA11y(chart) { var items = chart.legend && chart.legend.allItems, legendA11yOptions = (chart.options.legend.accessibility || {}); return !!(items && items.length && !(chart.colorAxis && chart.colorAxis.length) && legendA11yOptions.enabled !== false); } /** * Highlight legend item by index. * * @private * @function Highcharts.Chart#highlightLegendItem * * @param {number} ix * * @return {boolean} */ Chart.prototype.highlightLegendItem = function (ix) { var items = this.legend.allItems, oldIx = this.accessibility && this.accessibility.components.legend.highlightedLegendItemIx; if (items[ix]) { if (isNumber(oldIx) && items[oldIx]) { fireEvent(items[oldIx].legendGroup.element, 'mouseout'); } scrollLegendToItem(this.legend, ix); this.setFocusToElement(items[ix].legendItem, items[ix].a11yProxyElement); fireEvent(items[ix].legendGroup.element, 'mouseover'); return true; } return false; }; // Keep track of pressed state for legend items addEvent(Legend, 'afterColorizeItem', function (e) { var chart = this.chart, a11yOptions = chart.options.accessibility, legendItem = e.item; if (a11yOptions.enabled && legendItem && legendItem.a11yProxyElement) { legendItem.a11yProxyElement.setAttribute('aria-pressed', e.visible ? 'true' : 'false'); } }); /** * The LegendComponent class * * @private * @class * @name Highcharts.LegendComponent */ var LegendComponent = function () { }; LegendComponent.prototype = new AccessibilityComponent(); extend(LegendComponent.prototype, /** @lends Highcharts.LegendComponent */ { /** * Init the component * @private */ init: function () { var component = this; this.proxyElementsList = []; this.recreateProxies(); // Note: Chart could create legend dynamically, so events can not be // tied to the component's chart's current legend. this.addEvent(Legend, 'afterScroll', function () { if (this.chart === component.chart) { component.updateProxiesPositions(); component.updateLegendItemProxyVisibility(); this.chart.highlightLegendItem(component.highlightedLegendItemIx); } }); this.addEvent(Legend, 'afterPositionItem', function (e) { if (this.chart === component.chart && this.chart.renderer) { component.updateProxyPositionForItem(e.item); } }); this.addEvent(Legend, 'afterRender', function () { if (this.chart === component.chart && this.chart.renderer && component.recreateProxies()) { syncTimeout(function () { return component.updateProxiesPositions(); }, animObject(pick(this.chart.renderer.globalAnimation, true)).duration); } }); }, /** * @private */ updateLegendItemProxyVisibility: function () { var legend = this.chart.legend, items = legend.allItems || [], curPage = legend.currentPage || 1, clipHeight = legend.clipHeight || 0; items.forEach(function (item) { var itemPage = item.pageIx || 0, y = item._legendItemPos ? item._legendItemPos[1] : 0, h = item.legendItem ? Math.round(item.legendItem.getBBox().height) : 0, hide = y + h - legend.pages[itemPage] > clipHeight || itemPage !== curPage - 1; if (item.a11yProxyElement) { item.a11yProxyElement.style.visibility = hide ? 'hidden' : 'visible'; } }); }, /** * The legend needs updates on every render, in order to update positioning * of the proxy overlays. */ onChartRender: function () { if (!shouldDoLegendA11y(this.chart)) { this.removeProxies(); } }, /** * @private */ onChartUpdate: function () { this.updateLegendTitle(); }, /** * @private */ updateProxiesPositions: function () { for (var _i = 0, _a = this.proxyElementsList; _i < _a.length; _i++) { var _b = _a[_i], element = _b.element, posElement = _b.posElement; this.updateProxyButtonPosition(element, posElement); } }, /** * @private */ updateProxyPositionForItem: function (item) { var proxyRef = find(this.proxyElementsList, function (ref) { return ref.item === item; }); if (proxyRef) { this.updateProxyButtonPosition(proxyRef.element, proxyRef.posElement); } }, /** * @private */ recreateProxies: function () { this.removeProxies(); if (shouldDoLegendA11y(this.chart)) { this.addLegendProxyGroup(); this.addLegendListContainer(); this.proxyLegendItems(); this.updateLegendItemProxyVisibility(); return true; } return false; }, /** * @private */ removeProxies: function () { removeElement(this.legendProxyGroup); this.proxyElementsList = []; }, /** * @private */ updateLegendTitle: function () { var chart = this.chart; var legendTitle = stripHTMLTags((chart.legend && chart.legend.options.title && chart.legend.options.title.text || '').replace(/<br ?\/?>/g, ' ')); var legendLabel = chart.langFormat('accessibility.legend.legendLabel' + (legendTitle ? '' : 'NoTitle'), { chart: chart, legendTitle: legendTitle, chartTitle: getChartTitle(chart) }); if (this.legendProxyGroup) { this.legendProxyGroup.setAttribute('aria-label', legendLabel); } }, /** * @private */ addLegendProxyGroup: function () { var a11yOptions = this.chart.options.accessibility, groupRole = a11yOptions.landmarkVerbosity === 'all' ? 'region' : null; this.legendProxyGroup = this.addProxyGroup({ 'aria-label': '_placeholder_', role: groupRole }); }, /** * @private */ addLegendListContainer: function () { if (this.legendProxyGroup) { var container = this.legendListContainer = this.createElement('ul'); container.style.listStyle = 'none'; this.legendProxyGroup.appendChild(container); } }, /** * @private */ proxyLegendItems: function () { var component = this, items = (this.chart.legend && this.chart.legend.allItems || []); items.forEach(function (item) { if (item.legendItem && item.legendItem.element) { component.proxyLegendItem(item); } }); }, /** * @private * @param {Highcharts.BubbleLegendItem|Point|Highcharts.Series} item */ proxyLegendItem: function (item) { if (!item.legendItem || !item.legendGroup || !this.legendListContainer) { return; } var itemLabel = this.chart.langFormat('accessibility.legend.legendItem', { chart: this.chart, itemName: stripHTMLTags(item.name), item: item }), attribs = { tabindex: -1, 'aria-pressed': item.visible, 'aria-label': itemLabel }, // Considers useHTML proxyPositioningElement = item.legendGroup.div ? item.legendItem : item.legendGroup; var listItem = this.createElement('li'); this.legendListContainer.appendChild(listItem); item.a11yProxyElement = this.createProxyButton(item.legendItem, listItem, attribs, proxyPositioningElement); this.proxyElementsList.push({ item: item, element: item.a11yProxyElement, posElement: proxyPositioningElement }); }, /** * Get keyboard navigation handler for this component. * @return {Highcharts.KeyboardNavigationHandler} */ getKeyboardNavigation: function () { var keys = this.keyCodes, component = this, chart = this.chart; return new KeyboardNavigationHandler(chart, { keyCodeMap: [ [ [keys.left, keys.right, keys.up, keys.down], function (keyCode) { return component.onKbdArrowKey(this, keyCode); } ], [ [keys.enter, keys.space], function (keyCode) { if (H.isFirefox && keyCode === keys.space) { // #15520 return this.response.success; } return component.onKbdClick(this); } ] ], validate: function () { return component.shouldHaveLegendNavigation(); }, init: function (direction) { return component.onKbdNavigationInit(direction); }, terminate: function () { chart.legend.allItems.forEach(function (item) { return item.setState('', true); }); } }); }, /** * @private * @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler * @param {number} keyCode * @return {number} * Response code */ onKbdArrowKey: function (keyboardNavigationHandler, keyCode) { var keys = this.keyCodes, response = keyboardNavigationHandler.response, chart = this.chart, a11yOptions = chart.options.accessibility, numItems = chart.legend.allItems.length, direction = (keyCode === keys.left || keyCode === keys.up) ? -1 : 1; var res = chart.highlightLegendItem(this.highlightedLegendItemIx + direction); if (res) { this.highlightedLegendItemIx += direction; return response.success; } if (numItems > 1 && a11yOptions.keyboardNavigation.wrapAround) { keyboardNavigationHandler.init(direction); return response.success; } // No wrap, move return response[direction > 0 ? 'next' : 'prev']; }, /** * @private * @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler * @return {number} * Response code */ onKbdClick: function (keyboardNavigationHandler) { var legendItem = this.chart.legend.allItems[this.highlightedLegendItemIx]; if (legendItem && legendItem.a11yProxyElement) { fireEvent(legendItem.a11yProxyElement, 'click'); } return keyboardNavigationHandler.response.success; }, /** * @private * @return {boolean|undefined} */ shouldHaveLegendNavigation: function () { var chart = this.chart, legendOptions = chart.options.legend || {}, hasLegend = chart.legend && chart.legend.allItems, hasColorAxis = chart.colorAxis && chart.colorAxis.length, legendA11yOptions = (legendOptions.accessibility || {}); return !!(hasLegend && chart.legend.display && !hasColorAxis && legendA11yOptions.enabled && legendA11yOptions.keyboardNavigation && legendA11yOptions.keyboardNavigation.enabled); }, /** * @private * @param {number} direction */ onKbdNavigationInit: function (direction) { var chart = this.chart, lastIx = chart.legend.allItems.length - 1, ixToHighlight = direction > 0 ? 0 : lastIx; chart.highlightLegendItem(ixToHighlight); this.highlightedLegendItemIx = ixToHighlight; } }); export default LegendComponent;
mit
Codecarinas/server
Server/work/decompile-8eb82bde/net/minecraft/server/EnchantmentModifierProtection.java
387
package net.minecraft.server; final class EnchantmentModifierProtection implements EnchantmentModifier { public int a; public DamageSource b; private EnchantmentModifierProtection() {} public void a(Enchantment enchantment, int i) { this.a += enchantment.a(i, this.b); } EnchantmentModifierProtection(EmptyClass emptyclass) { this(); } }
cc0-1.0
Charling-Huang/birt
model/org.eclipse.birt.report.model.adapter.oda/src/org/eclipse/birt/report/model/adapter/oda/IODAFactory.java
1490
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.adapter.oda; import org.eclipse.birt.core.exception.BirtException; /** * The factory contains methods that make calls to datatools.oda objects. * */ public interface IODAFactory { /** * Returns the data type by given nativeCode, ROM data type and choice name. * * @param dataSourceId * the id of the data source * @param dataSetId * the id of the data set * @param nativeCode * the native data type code. * @param romDataType * the ROM defined data type in string * @param choiceName * the ROM choice to map. Can be column data type choice or * parameter data type choices. * * @return the ROM defined data type in string * @throws BirtException */ public String getUpdatedDataType( String dataSourceId, String dataSetId, int nativeCode, String romDataType, String choiceName ) throws BirtException; }
epl-1.0
kgibm/open-liberty
dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/event/BehaviorListener.java
919
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.faces.event; /** * @since 2.0 */ public interface BehaviorListener extends FacesListener { }
epl-1.0
georgeerhan/openhab2-addons
addons/binding/org.openhab.binding.russound/src/main/java/org/openhab/binding/russound/internal/rio/controller/RioControllerConfig.java
961
/** * Copyright (c) 2010-2017 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.russound.internal.rio.controller; /** * Configuration class for the {@link RioControllerHandler} * * @author Tim Roberts */ public class RioControllerConfig { /** * ID of the controller */ private int controller; /** * Gets the controller identifier * * @return the controller identifier */ public int getController() { return controller; } /** * Sets the controller identifier * * @param controller the controller identifier */ public void setController(int controller) { this.controller = controller; } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/device/DS2401Test.java
1302
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.onewire.device; import static org.openhab.binding.onewire.internal.OwBindingConstants.THING_TYPE_BASIC; import org.eclipse.jdt.annotation.NonNullByDefault; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openhab.binding.onewire.internal.OwException; import org.openhab.binding.onewire.internal.device.DS2401; import org.openhab.core.library.types.OnOffType; /** * Tests cases for {@link DS2401}. * * @author Jan N. Klug - Initial contribution */ @NonNullByDefault public class DS2401Test extends DeviceTestParent<DS2401> { @BeforeEach public void setupMocks() { setupMocks(THING_TYPE_BASIC, DS2401.class); } @Test public void presenceTestOn() throws OwException { presenceTest(OnOffType.ON); } @Test public void presenceTestOff() throws OwException { presenceTest(OnOffType.OFF); } }
epl-1.0
Charling-Huang/birt
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/ScriptConstants.java
1073
/******************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.script; /** * */ public final class ScriptConstants { public static final String DATA_SET_ROW_SCRIPTABLE = "dataSetRow"; public static final String DATA_SET_BINDING_SCRIPTABLE = "row"; public static final String DATA_BINDING_SCRIPTABLE = "data"; public static final String MEASURE_SCRIPTABLE = "measure"; public static final String DIMENSION_SCRIPTABLE = "dimension"; public static final String OUTER_RESULT_KEYWORD = "_outer"; public static final String ROW_NUM_KEYWORD = "__rownum"; }
epl-1.0
Panthro/che-plugins
plugin-runner/che-plugin-runner-ext-runner/src/test/java/org/eclipse/che/ide/ext/runner/client/runneractions/impl/RunActionTest.java
9512
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.runner.client.runneractions.impl; import com.google.gwtmockito.GwtMockitoTestRunner; import com.google.inject.Provider; import org.eclipse.che.api.analytics.client.logger.AnalyticsEventLogger; import org.eclipse.che.api.project.shared.dto.ProjectDescriptor; import org.eclipse.che.api.runner.dto.ApplicationProcessDescriptor; import org.eclipse.che.api.runner.dto.RunOptions; import org.eclipse.che.api.runner.gwt.client.RunnerServiceClient; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.app.CurrentProject; import org.eclipse.che.ide.ext.runner.client.RunnerLocalizationConstant; import org.eclipse.che.ide.ext.runner.client.callbacks.AsyncCallbackBuilder; import org.eclipse.che.ide.ext.runner.client.callbacks.FailureCallback; import org.eclipse.che.ide.ext.runner.client.callbacks.SuccessCallback; import org.eclipse.che.ide.ext.runner.client.inject.factories.RunnerActionFactory; import org.eclipse.che.ide.ext.runner.client.manager.RunnerManagerPresenter; import org.eclipse.che.ide.ext.runner.client.models.Runner; import org.eclipse.che.ide.ext.runner.client.runneractions.impl.launch.LaunchAction; import org.eclipse.che.ide.ext.runner.client.util.RunnerUtil; import org.eclipse.che.ide.rest.AsyncRequestCallback; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Matchers; import org.mockito.Mock; import static org.eclipse.che.ide.ext.runner.client.tabs.properties.panel.common.RAM.MB_500; import static org.mockito.Matchers.any; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * @author Alexander Andrienko * @author Dmitry Shnurenko */ @RunWith(GwtMockitoTestRunner.class) public class RunActionTest { private static final String PATH_TO_PROJECT = "somePath"; private static final String PROJECT_NAME = "projectName"; private static final String ENV_ID = "project://project a"; /*constructor variables*/ @Mock private RunnerServiceClient service; @Mock private AppContext appContext; @Mock private RunnerLocalizationConstant locale; @Mock private RunnerManagerPresenter presenter; @Mock private Provider<AsyncCallbackBuilder<ApplicationProcessDescriptor>> callbackBuilderProvider; @Mock private RunnerUtil runnerUtil; @Mock private RunnerActionFactory actionFactory; @Mock private AnalyticsEventLogger eventLogger; @Mock private Throwable reason; //callbacks for server @Mock private AsyncCallbackBuilder<ApplicationProcessDescriptor> asyncCallbackBuilder; @Mock private AsyncRequestCallback<ApplicationProcessDescriptor> asyncRequestCallback; //project variables @Mock private CurrentProject project; @Mock private ProjectDescriptor projectDescriptor; //run variables @Mock private RunOptions runOptions; @Mock private Runner runner; //action variables @Mock private ApplicationProcessDescriptor descriptor; @Mock private LaunchAction launchAction; //captors @Captor private ArgumentCaptor<FailureCallback> failedCallBackCaptor; @Captor private ArgumentCaptor<SuccessCallback<ApplicationProcessDescriptor>> successCallBackCaptor; private RunAction runAction; @Before public void setUp() { when(actionFactory.createLaunch()).thenReturn(launchAction); runAction = new RunAction(service, appContext, locale, presenter, callbackBuilderProvider, runnerUtil, actionFactory, eventLogger); //preparing callbacks for server when(appContext.getCurrentProject()).thenReturn(project); when(callbackBuilderProvider.get()).thenReturn(asyncCallbackBuilder); when(asyncCallbackBuilder.unmarshaller(ApplicationProcessDescriptor.class)).thenReturn(asyncCallbackBuilder); when(asyncCallbackBuilder.failure(any(FailureCallback.class))).thenReturn(asyncCallbackBuilder); when(asyncCallbackBuilder.success(Matchers.<SuccessCallback<ApplicationProcessDescriptor>>anyObject())) .thenReturn(asyncCallbackBuilder); when(asyncCallbackBuilder.build()).thenReturn(asyncRequestCallback); //preparing project data when(project.getProjectDescription()).thenReturn(projectDescriptor); when(projectDescriptor.getPath()).thenReturn(PATH_TO_PROJECT); when(runner.getOptions()).thenReturn(runOptions); when(runOptions.getEnvironmentId()).thenReturn(ENV_ID); } @Test public void shouldPerformWhenCurrentProjectIsNull() { reset(launchAction); when(appContext.getCurrentProject()).thenReturn(null); runAction.perform(runner); verify(eventLogger).log(runAction); verify(appContext).getCurrentProject(); verifyNoMoreInteractions(runner, service, locale, launchAction, presenter, callbackBuilderProvider); } @Test public void shouldSuccessPerform() { //preparing descriptor data when(descriptor.getMemorySize()).thenReturn(MB_500.getValue()); when(descriptor.getProcessId()).thenReturn(12345678L); when(runner.getOptions()).thenReturn(runOptions); runAction.perform(runner); verify(eventLogger).log(runAction); verify(presenter).setActive(); verify(asyncCallbackBuilder).success(successCallBackCaptor.capture()); SuccessCallback<ApplicationProcessDescriptor> successCallback = successCallBackCaptor.getValue(); successCallback.onSuccess(descriptor); verify(runner).setProcessDescriptor(descriptor); verify(runner).setRAM(MB_500.getValue()); verify(presenter).addRunnerId(12345678L); verify(presenter).update(runner); verify(launchAction).perform(runner); verify(service).run(PATH_TO_PROJECT, runOptions, asyncRequestCallback); } @Test public void shouldFailedPerform() { String someRunningMessage = "run information"; when(runner.getOptions()).thenReturn(runOptions); when(locale.startApplicationFailed(PROJECT_NAME)).thenReturn(someRunningMessage); when(project.getRunner()).thenReturn(PROJECT_NAME); when(projectDescriptor.getName()).thenReturn(someRunningMessage); when(locale.startApplicationFailed(someRunningMessage)).thenReturn(someRunningMessage); runAction.perform(runner); verify(eventLogger).log(runAction); verify(presenter).setActive(); verify(asyncCallbackBuilder).failure(failedCallBackCaptor.capture()); FailureCallback failureCallback = failedCallBackCaptor.getValue(); failureCallback.onFailure(reason); verify(runnerUtil).showError(runner, someRunningMessage, null); verify(project).getRunner(); verify(project, times(2)).getProjectDescription(); verify(projectDescriptor).getName(); verify(locale).startApplicationFailed(someRunningMessage); verify(service).run(PATH_TO_PROJECT, runOptions, asyncRequestCallback); } @Test public void shouldFailedWhenDefaultRunnerAbsent() { String someRunningMessage = "run information"; when(runner.getOptions()).thenReturn(runOptions); when(locale.startApplicationFailed(PROJECT_NAME)).thenReturn(someRunningMessage); when(projectDescriptor.getName()).thenReturn(someRunningMessage); when(locale.defaultRunnerAbsent()).thenReturn(someRunningMessage); runAction.perform(runner); verify(eventLogger).log(runAction); verify(presenter).setActive(); verify(asyncCallbackBuilder).failure(failedCallBackCaptor.capture()); FailureCallback failureCallback = failedCallBackCaptor.getValue(); failureCallback.onFailure(reason); verify(runnerUtil).showError(runner, someRunningMessage, null); verify(project).getRunner(); verify(locale).defaultRunnerAbsent(); verify(service).run(PATH_TO_PROJECT, runOptions, asyncRequestCallback); } }
epl-1.0
szarnekow/xsemantics
tests/it.xsemantics.dsl.tests/xsemantics-gen/it/xsemantics/test/fj/first/validation/FjFirstTypeSystemValidator.java
1880
package it.xsemantics.test.fj.first.validation; import com.google.inject.Inject; import it.xsemantics.example.fj.fj.Field; import it.xsemantics.example.fj.fj.Method; import it.xsemantics.example.fj.fj.Program; import it.xsemantics.example.fj.validation.AbstractFJJavaValidator; import it.xsemantics.runtime.validation.XsemanticsValidatorErrorGenerator; import it.xsemantics.test.fj.first.FjFirstTypeSystem; import org.eclipse.xtext.validation.Check; @SuppressWarnings("all") public class FjFirstTypeSystemValidator extends AbstractFJJavaValidator { @Inject protected XsemanticsValidatorErrorGenerator errorGenerator; @Inject protected FjFirstTypeSystem xsemanticsSystem; protected FjFirstTypeSystem getXsemanticsSystem() { return this.xsemanticsSystem; } @Check public void checkMain(final Program program) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkMain(program), program); } @Check public void checkClassOk(final it.xsemantics.example.fj.fj.Class clazz) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkClassOk(clazz), clazz); } @Check public void checkMethodBody(final Method method) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkMethodBody(method), method); } @Check public void checkField(final Field field) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkField(field), field); } @Check public void checkMethodOverride(final Method method) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkMethodOverride(method), method); } @Check public void checkClassHierachyNotCyclic(final it.xsemantics.example.fj.fj.Class cl) { errorGenerator.generateErrors(this, getXsemanticsSystem().checkClassHierachyNotCyclic(cl), cl); } }
epl-1.0
alastrina123/debrief
org.mwc.asset.legacy/src/ASSET/Util/XML/Control/Observers/ScenarioControllerHandler.java
2977
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package ASSET.Util.XML.Control.Observers; /** * Title: Debrief 2000 * Description: Debrief 2000 Track Analysis Software * Copyright: Copyright (c) 2000 * Company: MWC * @author Ian Mayo * @version 1.0 */ import ASSET.Scenario.Observers.ScenarioObserver; import ASSET.Util.XML.ASSETReaderWriter; import ASSET.Util.XML.MonteCarlo.ScenarioGeneratorHandler; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; import java.util.Vector; abstract public class ScenarioControllerHandler extends MWC.Utilities.ReaderWriter.XML.MWCXMLReader { public final static String type = "ScenarioController"; Vector<ScenarioObserver> _myObserverList; File _outputDirectory; private static final String OUTPUT_DIRECTORY = "OutputDirectory"; private static final String RANDOM_SEED = "RandomSeed"; Integer _randomSeed = null; public ScenarioControllerHandler() { // inform our parent what type of class we are super(type); addHandler(new ObserverListHandler() { public void setObserverList(Vector<ScenarioObserver> list) { _myObserverList = list; } }); addAttributeHandler(new HandleAttribute(OUTPUT_DIRECTORY) { public void setValue(String name, String value) { _outputDirectory = new File(value); } }); addAttributeHandler(new HandleAttribute(RANDOM_SEED) { public void setValue(String name, String value) { _randomSeed = Integer.valueOf(value); } }); addHandler(new ScenarioGeneratorHandler() { }); } public void elementClosed() { // build the results object ASSETReaderWriter.ResultsContainer rc = new ASSETReaderWriter.ResultsContainer(); rc.observerList = _myObserverList; rc.outputDirectory = _outputDirectory; rc.randomSeed = _randomSeed; // ok, now output it setResults(rc); // and clear _myObserverList = null; _randomSeed = null; _outputDirectory = null; } abstract public void setResults(ASSETReaderWriter.ResultsContainer results); public static void exportThis(final Vector<ScenarioObserver> list, final Object generator, final Element parent, final Document doc) { // create ourselves final Element sens = doc.createElement(type); ObserverListHandler.exportThis(list, sens, doc); // todo export the scenario generator stuff parent.appendChild(sens); } }
epl-1.0
stzilli/kapua
message/api/src/main/java/org/eclipse/kapua/message/xml/MetricsXmlAdapter.java
2153
/******************************************************************************* * Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.message.xml; import org.eclipse.kapua.model.type.ObjectValueConverter; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MetricsXmlAdapter extends XmlAdapter<XmlAdaptedMetrics, Map<String, Object>> { @Override public XmlAdaptedMetrics marshal(Map<String, Object> sourceMap) throws Exception { List<XmlAdaptedMetric> adaptedMapItems = new ArrayList<>(); for (Entry<String, Object> sourceEntry : sourceMap.entrySet()) { if (sourceEntry.getValue() != null) { XmlAdaptedMetric adaptedMapItem = new XmlAdaptedMetric(); adaptedMapItem.setName(sourceEntry.getKey()); adaptedMapItem.setValueType(sourceEntry.getValue().getClass()); adaptedMapItem.setValue(ObjectValueConverter.toString(sourceEntry.getValue())); adaptedMapItems.add(adaptedMapItem); } } return new XmlAdaptedMetrics(adaptedMapItems); } // // Unmarshal // @Override public Map<String, Object> unmarshal(XmlAdaptedMetrics sourceAdapter) throws Exception { Map<String, Object> map = new HashMap<>(); for (XmlAdaptedMetric sourceItem : sourceAdapter.getAdaptedMetrics()) { String name = sourceItem.getName(); Object value = ObjectValueConverter.fromString(sourceItem.getValue(), sourceItem.getValueType()); map.put(name, value); } return map; } }
epl-1.0
yetu/smarthome
bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/item/beans/GroupItemBean.java
622
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.io.rest.core.item.beans; /** * This is a java bean that is used to serialize group items to JSON. * * @author Kai Kreuzer - Initial contribution and API * */ public class GroupItemBean extends ItemBean { public ItemBean[] members; }
epl-1.0
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.resources.phaser.code/phaser-master/src/dom/RemoveFromDOM.js
558
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Attempts to remove the element from its parentNode in the DOM. * * @function Phaser.DOM.RemoveFromDOM * @since 3.0.0 * * @param {HTMLElement} element - The DOM element to remove from its parent node. */ var RemoveFromDOM = function (element) { if (element.parentNode) { element.parentNode.removeChild(element); } }; module.exports = RemoveFromDOM;
epl-1.0
aebrahim/CyLP
cylp/cy/__init__.py
506
from CyCoinIndexedVector import CyCoinIndexedVector from CyClpSimplex import CyClpSimplex from CyCbcNode import CyCbcNode from CyClpPrimalColumnPivotBase import CyClpPrimalColumnPivotBase from CyCoinMpsIO import CyCoinMpsIO from CyCoinPackedMatrix import CyCoinPackedMatrix from CyCbcModel import CyCbcModel from CyCoinModel import CyCoinModel # from CyPivotPythonBase import CyPivotPythonBase from CyDantzigPivot import CyDantzigPivot from CyPEPivot import CyPEPivot from CyWolfePivot import CyWolfePivot
epl-1.0
neelance/swt4ruby
swt4ruby/lib/linux-x86_32/org/eclipse/swt/internal/mozilla/NsIWebProgressListener.rb
5191
require "rjava" # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is Mozilla Communicator client code, released March 31, 1998. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by Netscape are Copyright (C) 1998-1999 # Netscape Communications Corporation. All Rights Reserved. # # Contributor(s): # # IBM # - Binding to permit interfacing between Mozilla and SWT # - Copyright (C) 2003, 2005 IBM Corp. All Rights Reserved. # # ***** END LICENSE BLOCK ***** module Org::Eclipse::Swt::Internal::Mozilla module NsIWebProgressListenerImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Swt::Internal::Mozilla } end class NsIWebProgressListener < NsIWebProgressListenerImports.const_get :NsISupports include_class_members NsIWebProgressListenerImports class_module.module_eval { const_set_lazy(:LAST_METHOD_ID) { NsISupports::LAST_METHOD_ID + 5 } const_attr_reader :LAST_METHOD_ID const_set_lazy(:NS_IWEBPROGRESSLISTENER_IID_STR) { "570f39d1-efd0-11d3-b093-00a024ffc08c" } const_attr_reader :NS_IWEBPROGRESSLISTENER_IID_STR const_set_lazy(:NS_IWEBPROGRESSLISTENER_IID) { NsID.new(NS_IWEBPROGRESSLISTENER_IID_STR) } const_attr_reader :NS_IWEBPROGRESSLISTENER_IID } typesig { [::Java::Int] } # long def initialize(address) super(address) end class_module.module_eval { const_set_lazy(:STATE_START) { 1 } const_attr_reader :STATE_START const_set_lazy(:STATE_REDIRECTING) { 2 } const_attr_reader :STATE_REDIRECTING const_set_lazy(:STATE_TRANSFERRING) { 4 } const_attr_reader :STATE_TRANSFERRING const_set_lazy(:STATE_NEGOTIATING) { 8 } const_attr_reader :STATE_NEGOTIATING const_set_lazy(:STATE_STOP) { 16 } const_attr_reader :STATE_STOP const_set_lazy(:STATE_IS_REQUEST) { 65536 } const_attr_reader :STATE_IS_REQUEST const_set_lazy(:STATE_IS_DOCUMENT) { 131072 } const_attr_reader :STATE_IS_DOCUMENT const_set_lazy(:STATE_IS_NETWORK) { 262144 } const_attr_reader :STATE_IS_NETWORK const_set_lazy(:STATE_IS_WINDOW) { 524288 } const_attr_reader :STATE_IS_WINDOW const_set_lazy(:STATE_IS_INSECURE) { 4 } const_attr_reader :STATE_IS_INSECURE const_set_lazy(:STATE_IS_BROKEN) { 1 } const_attr_reader :STATE_IS_BROKEN const_set_lazy(:STATE_IS_SECURE) { 2 } const_attr_reader :STATE_IS_SECURE const_set_lazy(:STATE_SECURE_HIGH) { 262144 } const_attr_reader :STATE_SECURE_HIGH const_set_lazy(:STATE_SECURE_MED) { 65536 } const_attr_reader :STATE_SECURE_MED const_set_lazy(:STATE_SECURE_LOW) { 131072 } const_attr_reader :STATE_SECURE_LOW } typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } # long # long def _on_state_change(a_web_progress, a_request, a_state_flags, a_status) return XPCOM._vtbl_call(NsISupports::LAST_METHOD_ID + 1, get_address, a_web_progress, a_request, a_state_flags, a_status) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } # long # long def _on_progress_change(a_web_progress, a_request, a_cur_self_progress, a_max_self_progress, a_cur_total_progress, a_max_total_progress) return XPCOM._vtbl_call(NsISupports::LAST_METHOD_ID + 2, get_address, a_web_progress, a_request, a_cur_self_progress, a_max_self_progress, a_cur_total_progress, a_max_total_progress) end typesig { [::Java::Int, ::Java::Int, ::Java::Int] } # long # long # long def _on_location_change(a_web_progress, a_request, location) return XPCOM._vtbl_call(NsISupports::LAST_METHOD_ID + 3, get_address, a_web_progress, a_request, location) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, Array.typed(::Java::Char)] } # long # long def _on_status_change(a_web_progress, a_request, a_status, a_message) return XPCOM._vtbl_call(NsISupports::LAST_METHOD_ID + 4, get_address, a_web_progress, a_request, a_status, a_message) end typesig { [::Java::Int, ::Java::Int, ::Java::Int] } # long # long def _on_security_change(a_web_progress, a_request, state) return XPCOM._vtbl_call(NsISupports::LAST_METHOD_ID + 5, get_address, a_web_progress, a_request, state) end private alias_method :initialize_ns_iweb_progress_listener, :initialize end end
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/core/dom/ExpressionStatement.java
5727
/******************************************************************************* * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core.dom; import java.util.ArrayList; import java.util.List; /** * Expression statement AST node type. * <p> * This kind of node is used to convert an expression (<code>Expression</code>) * into a statement (<code>Statement</code>) by wrapping it. * </p> * <pre> * ExpressionStatement: * StatementExpression <b>;</b> * </pre> * * @since 2.0 * @noinstantiate This class is not intended to be instantiated by clients. */ @SuppressWarnings("rawtypes") public class ExpressionStatement extends Statement { /** * The "expression" structural property of this node type (child type: {@link Expression}). * @since 3.0 */ public static final ChildPropertyDescriptor EXPRESSION_PROPERTY = new ChildPropertyDescriptor(ExpressionStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$ /** * A list of property descriptors (element type: * {@link StructuralPropertyDescriptor}), * or null if uninitialized. */ private static final List PROPERTY_DESCRIPTORS; static { List properyList = new ArrayList(2); createPropertyList(ExpressionStatement.class, properyList); addProperty(EXPRESSION_PROPERTY, properyList); PROPERTY_DESCRIPTORS = reapPropertyList(properyList); } /** * Returns a list of structural property descriptors for this node type. * Clients must not modify the result. * * @param apiLevel the API level; one of the * <code>AST.JLS*</code> constants * @return a list of property descriptors (element type: * {@link StructuralPropertyDescriptor}) * @since 3.0 */ public static List propertyDescriptors(int apiLevel) { return PROPERTY_DESCRIPTORS; } /** * The expression; lazily initialized; defaults to a unspecified, but legal, * expression. */ private Expression expression = null; /** * Creates a new unparented expression statement node owned by the given * AST. By default, the expression statement is unspecified, but legal, * method invocation expression. * <p> * N.B. This constructor is package-private. * </p> * * @param ast the AST that is to own this node */ ExpressionStatement(AST ast) { super(ast); } /* (omit javadoc for this method) * Method declared on ASTNode. */ final List internalStructuralPropertiesForType(int apiLevel) { return propertyDescriptors(apiLevel); } /* (omit javadoc for this method) * Method declared on ASTNode. */ final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) { if (property == EXPRESSION_PROPERTY) { if (get) { return getExpression(); } else { setExpression((Expression) child); return null; } } // allow default implementation to flag the error return super.internalGetSetChildProperty(property, get, child); } /* (omit javadoc for this method) * Method declared on ASTNode. */ final int getNodeType0() { return EXPRESSION_STATEMENT; } /* (omit javadoc for this method) * Method declared on ASTNode. */ ASTNode clone0(AST target) { ExpressionStatement result = new ExpressionStatement(target); result.setSourceRange(getStartPosition(), getLength()); result.copyLeadingComment(this); result.setExpression((Expression) getExpression().clone(target)); return result; } /* (omit javadoc for this method) * Method declared on ASTNode. */ final boolean subtreeMatch0(ASTMatcher matcher, Object other) { // dispatch to correct overloaded match method return matcher.match(this, other); } /* (omit javadoc for this method) * Method declared on ASTNode. */ void accept0(ASTVisitor visitor) { boolean visitChildren = visitor.visit(this); if (visitChildren) { acceptChild(visitor, getExpression()); } visitor.endVisit(this); } /** * Returns the expression of this expression statement. * * @return the expression node */ public Expression getExpression() { if (this.expression == null) { // lazy init must be thread-safe for readers synchronized (this) { if (this.expression == null) { preLazyInit(); this.expression = new MethodInvocation(this.ast); postLazyInit(this.expression, EXPRESSION_PROPERTY); } } } return this.expression; } /** * Sets the expression of this expression statement. * * @param expression the new expression node * @exception IllegalArgumentException if: * <ul> * <li>the node belongs to a different AST</li> * <li>the node already has a parent</li> * <li>a cycle in would be created</li> * </ul> */ public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); } /* (omit javadoc for this method) * Method declared on ASTNode. */ int memSize() { return super.memSize() + 1 * 4; } /* (omit javadoc for this method) * Method declared on ASTNode. */ int treeSize() { return memSize() + (this.expression == null ? 0 : getExpression().treeSize()); } }
epl-1.0
theanuradha/debrief
org.mwc.cmap.grideditor/src/org/mwc/cmap/grideditor/table/actons/ExportToClipboardAction.java
2757
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.cmap.grideditor.table.actons; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.TableItem; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.grideditor.GridEditorPlugin; import org.mwc.cmap.grideditor.table.GridEditorTable; import org.mwc.cmap.gridharness.data.GriddableItemDescriptor; public class ExportToClipboardAction extends Action { private static final String ACTION_TEXT = "Export data to clipboard"; private final GridEditorTable myTableUI; private final ImageDescriptor exportImage; public ExportToClipboardAction(final GridEditorTable tableUI) { super(ACTION_TEXT, AS_PUSH_BUTTON); myTableUI = tableUI; exportImage = loadImageDescriptor(GridEditorPlugin.IMG_EXPORT); setToolTipText(ACTION_TEXT); setEnabled(true); refreshWithTableUI(); } @Override public void run() { final int colCount = myTableUI.getTableViewer().getTable().getColumnCount(); final String newline = System.getProperty("line.separator"); final StringBuffer outS = new StringBuffer(); // headings for (int j = 1; j < colCount; j++) { final GriddableItemDescriptor descriptor = myTableUI.getTableModel() .getColumnData(j).getDescriptor(); String name = "Time"; if (descriptor != null) { name = descriptor.getName(); } outS.append(name + ","); } outS.append(newline); // ok, try to get teh data final TableItem[] data = myTableUI.getTableViewer().getTable().getItems(); for (int i = data.length - 1; i >= 0; i--) { final TableItem tableItem = data[i]; for (int j = 1; j < colCount; j++) { outS.append(tableItem.getText(j) + ","); } outS.append(newline); } // put the string on the clipboard CorePlugin.writeToClipboard(outS.toString()); } public void refreshWithTableUI() { final boolean isVis = myTableUI.isOnlyShowVisible(); setChecked(isVis); setImageDescriptor(exportImage); } protected static final ImageDescriptor loadImageDescriptor(final String key) { return GridEditorPlugin.getInstance().getImageRegistry().getDescriptor(key); } }
epl-1.0
Soeldner/modified-inkl-bootstrap-by-karl
lang/german/modules/shipping/dhl.php
39806
<?php /* ----------------------------------------------------------------------------------------- $Id: dhl.php 899 2005-04-29 02:40:57Z hhgag $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(dhl.php,v 1.02 2003/02/18 03:37:00); www.oscommerce.com (c) 2003 nextcommerce (dhl.php,v 1.4 2003/08/13); www.nextcommerce.org Released under the GNU General Public License ----------------------------------------------------------------------------------------- Third Party contributions: dhl_austria_1.02 Autor: Copyright (C) 2002 - 2003 TheMedia, Dipl.-Ing Thomas Plänkers | http://www.themedia.at & http://www.oscommerce.at Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ define('MODULE_SHIPPING_DHL_TEXT_TITLE', 'DHL &Ouml;sterreich'); define('MODULE_SHIPPING_DHL_TEXT_DESCRIPTION', 'DHL WORLDWIDE EXPRESS &Ouml;sterreich'); define('MODULE_SHIPPING_DHL_TEXT_WAY', 'Versand nach'); define('MODULE_SHIPPING_DHL_TEXT_UNITS', 'kg'); define('MODULE_SHIPPING_DHL_INVALID_ZONE', 'Es ist leider kein Versand in dieses Land m&ouml;glich'); define('MODULE_SHIPPING_DHL_UNDEFINED_RATE', 'Die Versandkosten k&ouml;nnen im Moment nicht errechnet werden'); define('MODULE_SHIPPING_DHL_STATUS_TITLE' , 'DHL WORLDWIDE EXPRESS &Ouuml;sterreich'); define('MODULE_SHIPPING_DHL_STATUS_DESC' , 'Wollen Sie den Versand &uuml;ber DHL WORLDWIDE EXPRESS &Ouml;sterreich anbieten?'); define('MODULE_SHIPPING_DHL_HANDLING_TITLE' , 'Handling Fee'); define('MODULE_SHIPPING_DHL_HANDLING_DESC' , 'Bearbeitungsgeb&uuml;hr f&uuml;r diese Versandart in Euro'); define('MODULE_SHIPPING_DHL_TAX_CLASS_TITLE' , 'Steuersatz'); define('MODULE_SHIPPING_DHL_TAX_CLASS_DESC' , 'W&auml;hlen Sie den MwSt.-Satz f&uuml;r diese Versandart aus.'); define('MODULE_SHIPPING_DHL_ZONE_TITLE' , 'Versand Zone'); define('MODULE_SHIPPING_DHL_ZONE_DESC' , 'Wenn Sie eine Zone ausw&auml;hlen, wird diese Versandart nur in dieser Zone angeboten.'); define('MODULE_SHIPPING_DHL_SORT_ORDER_TITLE' , 'Reihenfolge der Anzeige'); define('MODULE_SHIPPING_DHL_SORT_ORDER_DESC' , 'Niedrigste wird zuerst angezeigt.'); define('MODULE_SHIPPING_DHL_ALLOWED_TITLE' , 'Einzelne Versandzonen'); define('MODULE_SHIPPING_DHL_ALLOWED_DESC' , 'Geben Sie <b>einzeln</b> die Zonen an, in welche ein Versand m&ouml;glich sein soll. zb AT,DE'); define('MODULE_SHIPPING_DHL_COUNTRIES_1_TITLE' , 'Tarifzone 0 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_1_DESC' , 'Inlandszone'); define('MODULE_SHIPPING_DHL_COST_ECX_1_TITLE' , 'Tariftabelle f&uuml;r Zone 0 bis 10 kg ECX'); define('MODULE_SHIPPING_DHL_COST_ECX_1_DESC' , 'Tarif Tabelle f&uuml;r die Zone 0, auf <b>\'ECX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_1_TITLE' , 'Tariftabelle f&uuml;r Zone 0 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_1_DESC' , 'Tarif Tabelle f&uuml;r die Zone 0, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_1_TITLE' , 'Tariftabelle f&uuml;r Zone 0 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_1_DESC' , 'Tarif Tabelle f&uuml;r die Zone 0, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_1_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_1_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_1_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_1_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_1_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_1_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_1_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_1_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_1_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_1_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_1_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_1_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_1_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_2_TITLE' , 'Tarifzone 1 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_2_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 1 sind.'); define('MODULE_SHIPPING_DHL_COST_ECX_2_TITLE' , 'Tariftabelle f&uuml;r Zone 1 bis 10 kg ECX'); define('MODULE_SHIPPING_DHL_COST_ECX_2_DESC' , 'Tarif Tabelle f&uuml;r die Zone 1, auf <b>\'ECX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_2_TITLE' , 'Tariftabelle f&uuml;r Zone 1 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_2_DESC' , 'Tarif Tabelle f&uuml;r die Zone 1, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_2_TITLE' , 'Tariftabelle f&uuml;r Zone 1 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_2_DESC' , 'Tarif Tabelle f&uuml;r die Zone 1, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_2_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_2_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_2_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_2_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_2_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_2_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_2_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_2_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_2_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_2_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_2_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_2_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_2_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_3_TITLE' , 'Tarifzone 2 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_3_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 2 sind.'); define('MODULE_SHIPPING_DHL_COST_ECX_3_TITLE' , 'Tariftabelle f&uuml;r Zone 2 bis 10 kg ECX'); define('MODULE_SHIPPING_DHL_COST_ECX_3_DESC' , 'Tarif Tabelle f&uuml;r die Zone 2, auf <b>\'ECX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_3_TITLE' , 'Tariftabelle f&uuml;r Zone 2 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_3_DESC' , 'Tarif Tabelle f&uuml;r die Zone 2, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_3_TITLE' , 'Tariftabelle f&uuml;r Zone 2 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_3_DESC' , 'Tarif Tabelle f&uuml;r die Zone 2, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_3_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_20_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_3_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_30_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_3_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_50_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_3_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg ECX'); define('MODULE_SHIPPING_DHL_STEP_ECX_51_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_3_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_3_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_3_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_3_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_3_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_3_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_3_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_3_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_3_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_4_TITLE' , 'Tarifzone 3 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_4_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 3 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_4_TITLE' , 'Tariftabelle f&uuml;r Zone 3 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_4_DESC' , 'Tarif Tabelle f&uuml;r die Zone 3, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_4_TITLE' , 'Tariftabelle f&uuml;r Zone 3 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_4_DESC' , 'Tarif Tabelle f&uuml;r die Zone 3, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_4_TITLE' , 'Tariftabelle f&uuml;r Zone 3 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_4_DESC' , 'Tarif Tabelle f&uuml;r die Zone 3, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_4_TITLE' , 'Tariftabelle f&uuml;r Zone 3 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_4_DESC' , 'Tarif Tabelle f&uuml;r die Zone 3, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_4_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_4_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_4_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_4_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_4_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_4_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_4_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_4_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_4_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_4_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_4_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_4_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_4_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_4_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_4_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_4_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_4_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_5_TITLE' , 'Tarifzone 4 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_5_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 4 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_5_TITLE' , 'Tariftabelle f&uuml;r Zone 4 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_5_DESC' , 'Tarif Tabelle f&uuml;r die Zone 4, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_5_TITLE' , 'Tariftabelle f&uuml;r Zone 4 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_5_DESC' , 'Tarif Tabelle f&uuml;r die Zone 4, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_5_TITLE' , 'Tariftabelle f&uuml;r Zone 4 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_5_DESC' , 'Tarif Tabelle f&uuml;r die Zone 4, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_5_TITLE' , 'Tariftabelle f&uuml;r Zone 4 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_5_DESC' , 'Tarif Tabelle f&uuml;r die Zone 4, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_5_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_5_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_5_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_5_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_5_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_5_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_5_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_5_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_5_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_5_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_5_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_5_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_5_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_5_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_5_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_5_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_5_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_6_TITLE' , 'Tarifzone 5 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_6_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 5 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_6_TITLE' , 'Tariftabelle f&uuml;r Zone 5 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_6_DESC' , 'Tarif Tabelle f&uuml;r die Zone 5, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_6_TITLE' , 'Tariftabelle f&uuml;r Zone 5 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_6_DESC' , 'Tarif Tabelle f&uuml;r die Zone 5, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_6_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_6_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_6_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_6_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_6_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_6_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_6_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_6_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_6_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_7_TITLE' , 'Tarifzone 6 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_7_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 6 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_7_TITLE' , 'Tariftabelle f&uuml;r Zone 6 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_7_DESC' , 'Tarif Tabelle f&uuml;r die Zone 6, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_7_TITLE' , 'Tariftabelle f&uuml;r Zone 6 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_7_DESC' , 'Tarif Tabelle f&uuml;r die Zone 6, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_7_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_7_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_7_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_7_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_7_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_7_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_7_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_7_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_7_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_8_TITLE' , 'Tarifzone 7 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_8_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 7 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_8_TITLE' , 'Tariftabelle f&uuml;r Zone 7 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_8_DESC' , 'Tarif Tabelle f&uuml;r die Zone 7, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_8_TITLE' , 'Tariftabelle f&uuml;r Zone 7 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_8_DESC' , 'Tarif Tabelle f&uuml;r die Zone 7, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_8_TITLE' , 'Tariftabelle f&uuml;r Zone 7 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_8_DESC' , 'Tarif Tabelle f&uuml;r die Zone 7, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_8_TITLE' , 'Tariftabelle f&uuml;r Zone 7 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_8_DESC' , 'Tarif Tabelle f&uuml;r die Zone 7, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_8_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_8_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_8_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_8_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_8_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_8_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_8_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_8_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_8_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_8_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_8_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_8_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_8_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_8_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_8_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_8_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_8_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_9_TITLE' , 'Tarifzone 8 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_9_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 8 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_9_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_9_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_9_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_9_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_9_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_9_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_9_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_9_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_9_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_9_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_9_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_9_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_9_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_9_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_9_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_9_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_9_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_9_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_9_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_9_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_9_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_9_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_9_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_9_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_9_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_COUNTRIES_10_TITLE' , 'Tarifzone 8 L&auml;nder'); define('MODULE_SHIPPING_DHL_COUNTRIES_10_DESC' , 'Durch Komma getrennt Liste der L&auml;nder als zwei Zeichen ISO-Code Landeskennzahlen, die Teil der Zone 8 sind.'); define('MODULE_SHIPPING_DHL_COST_DOX_10_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg DOX'); define('MODULE_SHIPPING_DHL_COST_DOX_10_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'DOX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_WPX_10_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg WPX'); define('MODULE_SHIPPING_DHL_COST_WPX_10_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'WPX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_MDX_10_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg MDX'); define('MODULE_SHIPPING_DHL_COST_MDX_10_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'MDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_COST_SDX_10_TITLE' , 'Tariftabelle f&uuml;r Zone 8 bis 10 kg SDX'); define('MODULE_SHIPPING_DHL_COST_SDX_10_DESC' , 'Tarif Tabelle f&uuml;r die Zone 8, auf <b>\'SDX\'</b> bis 10 kg Versandgewicht.'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_10_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_20_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_10_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_30_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_10_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_50_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_10_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg DOX'); define('MODULE_SHIPPING_DHL_STEP_DOX_51_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_10_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_20_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_10_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_30_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_10_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_50_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_10_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg WPX'); define('MODULE_SHIPPING_DHL_STEP_WPX_51_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_10_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_20_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_10_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_30_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_10_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_50_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_10_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg MDX'); define('MODULE_SHIPPING_DHL_STEP_MDX_51_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_10_TITLE' , 'Erh&ouml;hungszuschlag bis 20 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_20_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_10_TITLE' , 'Erh&ouml;hungszuschlag bis 30 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_30_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_10_TITLE' , 'Erh&ouml;hungszuschlag bis 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_50_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_10_TITLE' , 'Erh&ouml;hungszuschlag ab 50 kg SDX'); define('MODULE_SHIPPING_DHL_STEP_SDX_51_10_DESC' , 'Erh&ouml;hungszuschlag pro &uuml;bersteigende 0,50 kg in EUR'); ?>
gpl-2.0
openjdk/jdk8u
jdk/src/share/classes/sun/security/x509/X509Key.java
16227
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.x509; import java.io.*; import java.util.Arrays; import java.util.Properties; import java.security.Key; import java.security.PublicKey; import java.security.KeyFactory; import java.security.Security; import java.security.Provider; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import sun.misc.HexDumpEncoder; import sun.security.util.*; /** * Holds an X.509 key, for example a public key found in an X.509 * certificate. Includes a description of the algorithm to be used * with the key; these keys normally are used as * "SubjectPublicKeyInfo". * * <P>While this class can represent any kind of X.509 key, it may be * desirable to provide subclasses which understand how to parse keying * data. For example, RSA public keys have two members, one for the * public modulus and one for the prime exponent. If such a class is * provided, it is used when parsing X.509 keys. If one is not provided, * the key still parses correctly. * * @author David Brownell */ public class X509Key implements PublicKey { /** use serialVersionUID from JDK 1.1. for interoperability */ private static final long serialVersionUID = -5359250853002055002L; /* The algorithm information (name, parameters, etc). */ protected AlgorithmId algid; /** * The key bytes, without the algorithm information. * @deprecated Use the BitArray form which does not require keys to * be byte aligned. * @see sun.security.x509.X509Key#setKey(BitArray) * @see sun.security.x509.X509Key#getKey() */ @Deprecated protected byte[] key = null; /* * The number of bits unused in the last byte of the key. * Added to keep the byte[] key form consistent with the BitArray * form. Can de deleted when byte[] key is deleted. */ @Deprecated private int unusedBits = 0; /* BitArray form of key */ private BitArray bitStringKey = null; /* The encoding for the key. */ protected byte[] encodedKey; /** * Default constructor. The key constructed must have its key * and algorithm initialized before it may be used, for example * by using <code>decode</code>. */ public X509Key() { } /* * Build and initialize as a "default" key. All X.509 key * data is stored and transmitted losslessly, but no knowledge * about this particular algorithm is available. */ private X509Key(AlgorithmId algid, BitArray key) throws InvalidKeyException { this.algid = algid; setKey(key); encode(); } /** * Sets the key in the BitArray form. */ protected void setKey(BitArray key) { this.bitStringKey = (BitArray)key.clone(); /* * Do this to keep the byte array form consistent with * this. Can delete when byte[] key is deleted. */ this.key = key.toByteArray(); int remaining = key.length() % 8; this.unusedBits = ((remaining == 0) ? 0 : 8 - remaining); } /** * Gets the key. The key may or may not be byte aligned. * @return a BitArray containing the key. */ protected BitArray getKey() { /* * Do this for consistency in case a subclass * modifies byte[] key directly. Remove when * byte[] key is deleted. * Note: the consistency checks fail when the subclass * modifies a non byte-aligned key (into a byte-aligned key) * using the deprecated byte[] key field. */ this.bitStringKey = new BitArray( this.key.length * 8 - this.unusedBits, this.key); return (BitArray)bitStringKey.clone(); } /** * Construct X.509 subject public key from a DER value. If * the runtime environment is configured with a specific class for * this kind of key, a subclass is returned. Otherwise, a generic * X509Key object is returned. * * <P>This mechanism gurantees that keys (and algorithms) may be * freely manipulated and transferred, without risk of losing * information. Also, when a key (or algorithm) needs some special * handling, that specific need can be accomodated. * * @param in the DER-encoded SubjectPublicKeyInfo value * @exception IOException on data format errors */ public static PublicKey parse(DerValue in) throws IOException { AlgorithmId algorithm; PublicKey subjectKey; if (in.tag != DerValue.tag_Sequence) throw new IOException("corrupt subject key"); algorithm = AlgorithmId.parse(in.data.getDerValue()); try { subjectKey = buildX509Key(algorithm, in.data.getUnalignedBitString()); } catch (InvalidKeyException e) { throw new IOException("subject key, " + e.getMessage(), e); } if (in.data.available() != 0) throw new IOException("excess subject key"); return subjectKey; } /** * Parse the key bits. This may be redefined by subclasses to take * advantage of structure within the key. For example, RSA public * keys encapsulate two unsigned integers (modulus and exponent) as * DER values within the <code>key</code> bits; Diffie-Hellman and * DSS/DSA keys encapsulate a single unsigned integer. * * <P>This function is called when creating X.509 SubjectPublicKeyInfo * values using the X509Key member functions, such as <code>parse</code> * and <code>decode</code>. * * @exception IOException on parsing errors. * @exception InvalidKeyException on invalid key encodings. */ protected void parseKeyBits() throws IOException, InvalidKeyException { encode(); } /* * Factory interface, building the kind of key associated with this * specific algorithm ID or else returning this generic base class. * See the description above. */ static PublicKey buildX509Key(AlgorithmId algid, BitArray key) throws IOException, InvalidKeyException { /* * Use the algid and key parameters to produce the ASN.1 encoding * of the key, which will then be used as the input to the * key factory. */ DerOutputStream x509EncodedKeyStream = new DerOutputStream(); encode(x509EncodedKeyStream, algid, key); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray()); try { // Instantiate the key factory of the appropriate algorithm KeyFactory keyFac = KeyFactory.getInstance(algid.getName()); // Generate the public key return keyFac.generatePublic(x509KeySpec); } catch (NoSuchAlgorithmException e) { // Return generic X509Key with opaque key data (see below) } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e.getMessage(), e); } /* * Try again using JDK1.1-style for backwards compatibility. */ String classname = ""; try { Properties props; String keytype; Provider sunProvider; sunProvider = Security.getProvider("SUN"); if (sunProvider == null) throw new InstantiationException(); classname = sunProvider.getProperty("PublicKey.X.509." + algid.getName()); if (classname == null) { throw new InstantiationException(); } Class<?> keyClass = null; try { keyClass = Class.forName(classname); } catch (ClassNotFoundException e) { ClassLoader cl = ClassLoader.getSystemClassLoader(); if (cl != null) { keyClass = cl.loadClass(classname); } } Object inst = null; X509Key result; if (keyClass != null) inst = keyClass.newInstance(); if (inst instanceof X509Key) { result = (X509Key) inst; result.algid = algid; result.setKey(key); result.parseKeyBits(); return result; } } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { // this should not happen. throw new IOException (classname + " [internal error]"); } X509Key result = new X509Key(algid, key); return result; } /** * Returns the algorithm to be used with this key. */ public String getAlgorithm() { return algid.getName(); } /** * Returns the algorithm ID to be used with this key. */ public AlgorithmId getAlgorithmId() { return algid; } /** * Encode SubjectPublicKeyInfo sequence on the DER output stream. * * @exception IOException on encoding errors. */ public final void encode(DerOutputStream out) throws IOException { encode(out, this.algid, getKey()); } /** * Returns the DER-encoded form of the key as a byte array. */ public byte[] getEncoded() { try { return getEncodedInternal().clone(); } catch (InvalidKeyException e) { // XXX } return null; } public byte[] getEncodedInternal() throws InvalidKeyException { byte[] encoded = encodedKey; if (encoded == null) { try { DerOutputStream out = new DerOutputStream(); encode(out); encoded = out.toByteArray(); } catch (IOException e) { throw new InvalidKeyException("IOException : " + e.getMessage()); } encodedKey = encoded; } return encoded; } /** * Returns the format for this key: "X.509" */ public String getFormat() { return "X.509"; } /** * Returns the DER-encoded form of the key as a byte array. * * @exception InvalidKeyException on encoding errors. */ public byte[] encode() throws InvalidKeyException { return getEncodedInternal().clone(); } /* * Returns a printable representation of the key */ public String toString() { HexDumpEncoder encoder = new HexDumpEncoder(); return "algorithm = " + algid.toString() + ", unparsed keybits = \n" + encoder.encodeBuffer(key); } /** * Initialize an X509Key object from an input stream. The data on that * input stream must be encoded using DER, obeying the X.509 * <code>SubjectPublicKeyInfo</code> format. That is, the data is a * sequence consisting of an algorithm ID and a bit string which holds * the key. (That bit string is often used to encapsulate another DER * encoded sequence.) * * <P>Subclasses should not normally redefine this method; they should * instead provide a <code>parseKeyBits</code> method to parse any * fields inside the <code>key</code> member. * * <P>The exception to this rule is that since private keys need not * be encoded using the X.509 <code>SubjectPublicKeyInfo</code> format, * private keys may override this method, <code>encode</code>, and * of course <code>getFormat</code>. * * @param in an input stream with a DER-encoded X.509 * SubjectPublicKeyInfo value * @exception InvalidKeyException on parsing errors. */ public void decode(InputStream in) throws InvalidKeyException { DerValue val; try { val = new DerValue(in); if (val.tag != DerValue.tag_Sequence) throw new InvalidKeyException("invalid key format"); algid = AlgorithmId.parse(val.data.getDerValue()); setKey(val.data.getUnalignedBitString()); parseKeyBits(); if (val.data.available() != 0) throw new InvalidKeyException ("excess key data"); } catch (IOException e) { throw new InvalidKeyException("IOException: " + e.getMessage()); } } public void decode(byte[] encodedKey) throws InvalidKeyException { decode(new ByteArrayInputStream(encodedKey)); } /** * Serialization write ... X.509 keys serialize as * themselves, and they're parsed when they get read back. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.write(getEncoded()); } /** * Serialization read ... X.509 keys serialize as * themselves, and they're parsed when they get read back. */ private void readObject(ObjectInputStream stream) throws IOException { try { decode(stream); } catch (InvalidKeyException e) { e.printStackTrace(); throw new IOException("deserialized key is invalid: " + e.getMessage()); } } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Key == false) { return false; } try { byte[] thisEncoded = this.getEncodedInternal(); byte[] otherEncoded; if (obj instanceof X509Key) { otherEncoded = ((X509Key)obj).getEncodedInternal(); } else { otherEncoded = ((Key)obj).getEncoded(); } return Arrays.equals(thisEncoded, otherEncoded); } catch (InvalidKeyException e) { return false; } } /** * Calculates a hash code value for the object. Objects * which are equal will also have the same hashcode. */ public int hashCode() { try { byte[] b1 = getEncodedInternal(); int r = b1.length; for (int i = 0; i < b1.length; i++) { r += (b1[i] & 0xff) * 37; } return r; } catch (InvalidKeyException e) { // should not happen return 0; } } /* * Produce SubjectPublicKey encoding from algorithm id and key material. */ static void encode(DerOutputStream out, AlgorithmId algid, BitArray key) throws IOException { DerOutputStream tmp = new DerOutputStream(); algid.encode(tmp); tmp.putUnalignedBitString(key); out.write(DerValue.tag_Sequence, tmp); } }
gpl-2.0
BaerMitUmlaut/CBA_A3
addons/disposable/CfgMagazines.hpp
216
class CfgMagazines { class CA_LauncherMagazine; class CBA_FakeLauncherMagazine: CA_LauncherMagazine { scope = 1; ammo = "RocketBase"; count = 0; allowedSlots[] = {}; }; };
gpl-2.0
Kevin-010/RemoteTech2
src/RemoteTech2/UI/AntennaWindow.cs
1716
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace RemoteTech { public class AntennaWindow : AbstractWindow { public static Guid Guid = new Guid("39fe8878-d894-4ded-befb-d6e070ddc2c4"); public IAntenna Antenna { get { return mSetAntenna; } set { mSetAntenna = value; if (mAntennaFragment != null) mAntennaFragment.Antenna = value; } } public AntennaFragment mAntennaFragment; private IAntenna mSetAntenna; public AntennaWindow(IAntenna antenna) : base(Guid, "Antenna Configuration", new Rect(100, 100, 300, 500), WindowAlign.Floating) { mSetAntenna = antenna; } public override void Show() { mAntennaFragment = mAntennaFragment ?? new AntennaFragment(mSetAntenna); GameEvents.onVesselChange.Add(OnVesselChange); base.Show(); } public override void Hide() { if (mAntennaFragment != null) { mAntennaFragment.Dispose(); mAntennaFragment = null; } GameEvents.onVesselChange.Remove(OnVesselChange); base.Hide(); } public override void Window(int uid) { if (mAntennaFragment.Antenna == null) { Hide(); return; } GUI.skin = HighLogic.Skin; GUILayout.BeginVertical(GUILayout.Width(300), GUILayout.Height(500)); { mAntennaFragment.Draw(); } GUILayout.EndVertical(); base.Window(uid); } public void OnVesselChange(Vessel v) { Hide(); } } }
gpl-2.0
loveyoupeng/rt
modules/graphics/src/main/java/com/sun/javafx/scene/traversal/Algorithm.java
3251
/* * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.javafx.scene.traversal; import javafx.scene.Node; /** * An algorithm to be used in a traversal engine. * * Note that in order to avoid cycles or dead-ends in traversal the algorithms should respect the following order: * * for NEXT: node -> node's subtree -> node siblings (first sibling then it's subtree) -> NEXT_IN_LINE for node's parent * * for NEXT_IN_LINE: node -> node siblings (first sibling then it's subtree) -> NEXT_IN_LINE for node's parent * * for PREVIOUS: node -> node siblings ( ! first subtree then the node itself ! ) -> PREVIOUS for node's parent * * Basically it ensures that next direction will traverse the same nodes as previous, in the opposite order. * */ public interface Algorithm { /** * Traverse from owner, in direction dir. * Return a the new target Node or null if no suitable target is found. * * Typically, the implementation of override algorithm handles only parent's direct children and looks like this: * 1) Find the nearest parent of the "owner" that is handled by this algorithm (i.e. it's a direct child of the root). * 2) select the next node within this direct child using the context.selectInSubtree() and return it * 2a) if no such node exists, move to the next direct child in the direction (this is where the different order of direct children is defined) * or if direct children are not traversable, the select the first node in the next direct child */ public Node select(Node owner, Direction dir, TraversalContext context); /** * Return the first traversable node for the specified context (root). * @param context the context that contains the root * @return the first node */ public Node selectFirst(TraversalContext context); /** * Return the last traversable node for the specified context (root). * @param context the context that contains the root * @return the last node */ public Node selectLast(TraversalContext context); }
gpl-2.0
Evolix/lilac
importer/engines/nagios/NagiosImportEngine.php
19525
<?php abstract class NagiosImporter extends Importer { private $importJob; private $fileSegment; private $needQueued; public function __construct($engine, $fileSegment) { $this->fileSegment = $fileSegment; parent::__construct($engine); } /** * Enter description here... * * @return NagiosImportFileSegment */ protected function getSegment() { return $this->fileSegment; } abstract function init(); /** * Returns if this importer is valid and able to import. If not, we defer it * */ abstract function valid(); abstract function import(); } class NagiosImportFileSegment { private $values; private $fileName; private $line; public function __construct($fileName) { $this->fileName = $fileName; $this->values = array(); } public function add($lineNum, $key, $value, $line) { if($key === null) { $key = '__nokey__'; // Special key value } if(!isset($this->values[$key])) { $this->values[$key] = array(); } $this->values[$key][] = array( 'value' => $value, 'line' => $lineNum, 'text' => $line ); } public function get($key) { if(isset($this->values[$key])) { return $this->values[$key]; } return null; } /** * Enter description here... * * @return array Copy of lines */ public function getValues() { return $this->values; } public function getFilename() { return $this->fileName; } public function dump() { print("Contents of Values:\n"); var_dump($this->values); } } class NagiosImportEngine extends ImportEngine { private $objectFiles = array(); // Will contain a list of object files to process private $queuedImporters = array(); public function getDisplayName() { return "Nagios Importer"; } public function getDescription() { return "Imports existing configurations from Nagios 2.x and 3.x"; } public function renderConfig() { ?> <p> <fieldset class="checks"> <legend>Options</legend> <p> <input type="checkbox" id="overwrite_main" name="overwrite_main" checked="checked" /> <label for="overwrite_main">Overwrite Main Configuration</label> </p> <p> <input type="checkbox" id="overwrite_cgi" name="overwrite_cgi" checked="checked" /> <label for="overwrite_cgi">Overwrite CGI Configuration</label> </p> <p> <input type="checkbox" id="overwrite_resources" name="overwrite_resources" checked="checked" /> <label for="overwrite_resources">Overwrite Resources (resources.cfg)</label> </p> <p> <input type="checkbox" id="delete_existing" name="delete_existing" checked="checked" /> <label for="delete_existing">Delete Current Objects</label> </p> <p> <input type="checkbox" name="overwrite_existing" id="overwrite_existing" checked="checked" /> <label for="overwrite_existing">Overwrite Existing Objects (Ignored if Deleting Existing Objects)</label> </p> <p> <input type="checkbox" id="continue_error" name="continue_error" /> <label for="continue_error">Attempt to Continue on Errors</label> </p> </fieldset> </p> <p> <fieldset> <legend>File Locations</legend> <p> <label for="config_file">Main Configuration File (nagios.cfg)</label> <input type="text" size="100" maxlength="255" id="config_file" name="config_file" /> </p> <p> <label for="cgi_file">CGI Configuration File (cgi.cfg)</label> <input type="text" size="100" maxlength="255" id="cgi_file" name="cgi_file" /> </p> <p> <label for="resources_file">Resource File (resource.cfg)</label> <input type="text" size="100" maxlength="255" id="resources_file" name="resources_file" /> </p> </fieldset> </p> <?php } public function validateConfig() { $error = false; if(!file_exists($_POST['config_file'])) { $error = "Main configuration file not found at: " . $_POST['config_file']; } else if(isset($_POST['overwrite_cgi']) && !file_exists($_POST['cgi_file'])) { $error = "CGI configuration file not found at: " . $_POST['cgi_file']; } else if(isset($_POST['overwrite_resources']) && !file_exists($_POST['resources_file'])) { $error = "Resources file not found at: " . $_POST['resources_file']; } return $error; } public function buildConfig($config) { $config->setVar("overwrite_main", (isset($_POST['overwrite_main']) ? true : false)); $config->setVar("overwrite_cgi", (isset($_POST['overwrite_cgi']) ? true : false)); $config->setVar("overwrite_resources", (isset($_POST['overwrite_resources']) ? true : false)); $config->setVar("continue_error", (isset($_POST['continue_error']) ? true : false)); $config->setVar("delete_existing", (isset($_POST['delete_existing']) ? true : false)); $config->setVar("overwrite_existing", (isset($_POST['overwrite_existing']) ? true : false)); $config->setVar("config_file", $_POST['config_file']); $config->setVar("cgi_file", $_POST['cgi_file']); $config->setVar("resources_file", $_POST['resources_file']); } public function showJobSupplemental() { ?><ul><?php $config = $this->getConfig(); if($config->getVar("overwrite_main")) { ?><li><strong>Importing Main Configuration</strong></li><?php } if($config->getVar("overwrite_resources")) { ?><li><strong>Importing Resources</strong></li><?php } if($config->getVar("overwrite_cgi")) { ?><li><strong>Importing CGI Configuration</strong></li><?php } if($config->getVar("overwrite_existing")) { ?><li><strong>Overwriting Existing Objects</strong></li><?php } if($config->getVar("continue_error")) { ?><li><strong>Attempting to Continue on Errors</strong></li><?php } ?></ul><?php } public function addQueuedImporter($importer) { $this->queuedImporters[] = $importer; } public function init() { $job = $this->getJob(); $job->addNotice("NagiosImportEngine Starting..."); $config = $this->getConfig(); // Attempt to try and open each config file $job->addNotice("Attempting to open " . $config->GetVar('config_file')); if(!file_exists($config->getVar('config_file')) || !@fopen($config->getVar('config_file'), "r")) { $job->addError("Failed to open " . $config->getVar('config_file')); return false; } $job->addNotice("Attempting to open " . $config->GetVar('cgi_file')); if(!file_exists($config->getVar('cgi_file')) || !@fopen($config->getVar('cgi_file'), "r")) { $job->addError("Failed to open " . $config->getVar('cgi_file')); return false; } $job->addNotice("Attempting to open " . $config->GetVar('resources_file')); if(!file_exists($config->getVar('resources_file')) || !@fopen($config->getVar('resources_file'), "r")) { $job->addError("Failed to open " . $config->getVar('resources_file')); return false; } $job->addNotice("Config passed sanity check for Nagios import. Finished initializing."); if($config->getVar('delete_existing')) { $job->addNotice("Removing existing Nagios objects."); NagiosTimeperiodPeer::doDeleteAll(); NagiosCommandPeer::doDeleteAll(); NagiosContactPeer::doDeleteAll(); NagiosContactGroupPeer::doDeleteAll(); NagiosHostTemplatePeer::doDeleteAll(); NagiosHostPeer::doDeleteAll(); NagiosHostgroupPeer::doDeleteAll(); NagiosServiceGroupPeer::doDeleteAll(); NagiosServiceTemplatePeer::doDeleteAll(); NagiosServicePeer::doDeleteAll(); NagiosDependencyPeer::doDeleteAll(); NagiosDependencyTargetPeer::doDeleteAll(); NagiosEscalationPeer::doDeleteAll(); } return true; } public function import() { $job = $this->getJob(); $job->addNotice("NagiosImportEngine beginning import..."); $config = $this->getConfig(); $fp = fopen($config->getVar('config_file'), 'r'); // We have our file pointer. $segment = $this->buildSegmentFromConfigFile($fp, $config->getVar('config_file')); $importer = new NagiosMainImporter($this, $segment); $importer->init(); if($config->getVar('overwrite_main')) { if(!$importer->valid()) { $this->addQueuedImporter($importer); $job->addNotice("NagiosImportEngine queueing up Main importer until dependencies are valid."); } else { if(!$importer->import()) { if(!$config->getVar('continue_error')) { $job->addError("Failed to import."); return false; } } } } if($config->getVar('overwrite_cgi')) { $fp = fopen($config->getVar('cgi_file'), 'r'); // We have our file pointer. $segment = $this->buildSegmentFromConfigFile($fp, $config->getVar('cgi_file')); $importer = new NagiosCgiImporter($this, $segment); if(!$importer->valid()) { $this->addQueuedImporter($importer); $job->addNotice("NagiosImportEngine queueing up CGI importer until dependencies are valid."); } else { if(!$importer->import()) { if(!$config->getVar('continue_error')) { $job->addError("Failed to import."); return false; } } } } if($config->getVar('overwrite_resources')) { $fp = fopen($config->getVar('resources_file'), 'r'); // We have our file pointer. $segment = $this->buildSegmentFromConfigFile($fp, $config->getVar('resources_file')); $importer = new NagiosResourceImporter($this, $segment); if(!$importer->valid()) { $this->addQueuedImporter($importer); $job->addNotice("NagiosImportEngine queueing up resources importer until dependencies are valid."); } else { if(!$importer->import()) { if(!$config->getVar('continue_error')) { $job->addError("Failed to import."); return false; } } } } $job->addNotice("Beginning to process " . count($this->objectFiles) . " object files."); foreach($this->objectFiles as $fileName) { $job->addNotice("Parsing file: " . $fileName); if(!$this->parse_object_file($fileName, $job)) { return false; } $job->addNotice("Finished Parsing file: " . $fileName); } if(count($this->queuedImporters)) { $completed = false; while(!$completed) { $completedOne = false; $job->addNotice("After initial pass, we have " . count($this->queuedImporters) . " queued importer(s)."); foreach($this->queuedImporters as $key => $importer) { if($importer->valid()) { if($importer->import() === false) { return false; } unset($this->queuedImporters[$key]); $completedOne = true; } } if(!$completedOne) { // We were unable to finish any of the importers that were // queued. break; } if(count($this->queuedImporters) === 0) { $completed = true; } } if(!$completed) { $job->addError("None of the Queued Importers were able to validate."); return false; } } $job->addNotice("NagiosImportEngine finished importing."); return true; } private function buildSegmentFromConfigFile($fp, $fileName) { $segment = new NagiosImportFileSegment($fileName); $counter = 0; while ($line = fgets($fp)) { // Lines better not be over 1024 characters in length $counter++; if (preg_match('/^\s*(|#.*)$/', $line)) { // We read a comment, so let's hop to the next line continue; } if (preg_match('/^\s*([^=]+)\s*=\s*([^#;]+)/', $line, $regs)) { $values = explode(',', $regs[2]); foreach($values as $val) { if(trim($val) != '') { $segment->add($counter, trim($regs[1]), trim($val), $line); } } } else { $segment->add($counter, null, null, $line); } continue; } return $segment; } public function addObjectFile($fileName) { $job = $this->getJob(); $this->objectFiles[] = $fileName; $job->addNotice("NagiosImportEngine: Added " . $fileName . " to list of object config files to parse."); } private function parse_object_file($fileName, $importJob) { $fp = @fopen($fileName, 'r'); $config = unserialize($importJob->getConfig()); if(!$fp ) { $importJob->addLogEntry("Failed to open object file: " . $fileName, ImportLogEntry::TYPE_ERROR); if(!$config->getVar('continue_error')) { return false; } } $lineNumber = 0; while ($line = fgets($fp)) { $lineNumber++; $line = trim($line); if(preg_match('/^\s*(|#.*)$/', $line)) { // This is a comment continue; } // Need to merge lines that have a \ at the end if(preg_match('/\\\$/', $line)) { // We need to merge, so remove the last character of the line, // then merge with next $newLine = substr($line, 0, strlen($line) - 2); do { $line = fgets($fp); $line = trim($line); $newLine .= $line; if(preg_match('/\\\$/', $newLine)) { // Chop off the \ again $newLine = substr($newLine, 0, strlen($newLine) - 2); } } while(preg_match('/\\\$/', $line)); $line = $newLine; } if (preg_match('/^\s*define\s+(\S+)\s*{\s*$/', $line, $regs)) { // Setup object name $objectName = $regs[1]; $segment = new NagiosImportFileSegment($fileName); continue; } if (preg_match('/\s*(\S+)\s+([^#;]+)/', $line, $regs)) { if($regs[1] != ";") { // Check for a blank line (this is ugly, should fix the regex) // See if the line has a \ on the end $values = explode(',', $regs[2]); foreach($values as $val) { if(trim($val) != "") { $segment->add($lineNumber, trim($regs[1]), trim($val), $line); } } } continue; } if (preg_match('/^\s*}/', $line)) { //Completed object End curley bracket must be on it's own line switch($objectName) { case 'contactgroup': $importer = new NagiosContactGroupImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'contact': $importer = new NagiosContactImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'host': $importer = new NagiosHostImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'hostgroup': $importer = new NagiosHostGroupImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'timeperiod': $importer = new NagiosTimeperiodImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'command': $importer = new NagiosCommandImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'service': $importer = new NagiosServiceImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'servicegroup': $importer = new NagiosServiceGroupImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'hostextinfo': $importer = new NagiosHostExtInfoImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'serviceextinfo': $importer = new NagiosServiceExtInfoImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'hostdependency': $importer = new NagiosHostDependencyImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'servicedependency': $importer = new NagiosServiceDependencyImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'hostescalation': $importer = new NagiosHostEscalationImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; case 'serviceescalation': $importer = new NagiosServiceEscalationImporter($this, $segment); if(!$importer->init()) { return false; } if(!$importer->valid()) { $this->addQueuedImporter($importer); } else { if(!$importer->import()) { return false; } } break; } // switch $objectName = ''; $importLines = array(); continue; } } return true; } } $path = dirname(__FILE__) . "/../../"; // Include our importers require_once($path . 'importers/nagios/NagiosMainImporter.php'); require_once($path . 'importers/nagios/NagiosCgiImporter.php'); require_once($path . 'importers/nagios/NagiosResourceImporter.php'); require_once($path . 'importers/nagios/NagiosTimeperiodImporter.php'); require_once($path . 'importers/nagios/NagiosCommandImporter.php'); require_once($path . 'importers/nagios/NagiosContactImporter.php'); require_once($path . 'importers/nagios/NagiosContactGroupImporter.php'); require_once($path . 'importers/nagios/NagiosHostImporter.php'); require_once($path . 'importers/nagios/NagiosHostGroupImporter.php'); require_once($path . 'importers/nagios/NagiosServiceImporter.php'); require_once($path . 'importers/nagios/NagiosServiceGroupImporter.php'); require_once($path . 'importers/nagios/NagiosHostDependencyImporter.php'); require_once($path . 'importers/nagios/NagiosServiceDependencyImporter.php'); require_once($path . 'importers/nagios/NagiosHostEscalationImporter.php'); require_once($path . 'importers/nagios/NagiosServiceEscalationImporter.php'); require_once($path . 'importers/nagios/NagiosHostExtInfoImporter.php'); require_once($path . 'importers/nagios/NagiosServiceExtInfoImporter.php'); ?>
gpl-2.0
ProDataLab/veins-3a2-plus
tests/traci/init.lua
10164
-- -- TraCI Dissector for Wireshark -- Copyright (C) 2013 Christoph Sommer <christoph.sommer@uibk.ac.at> -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- function traci_proto_commandIdToString(id) if id == 0x00 then return "CMD_GETVERSION" end if id == 0x02 then return "CMD_SIMSTEP2" end if id == 0x12 then return "CMD_STOP" end if id == 0x13 then return "CMD_CHANGELANE" end if id == 0x14 then return "CMD_SLOWDOWN" end if id == 0x31 then return "CMD_CHANGETARGET" end if id == 0x74 then return "CMD_ADDVEHICLE" end if id == 0x7F then return "CMD_CLOSE" end if id == 0x80 then return "CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT" end if id == 0xa0 then return "CMD_GET_INDUCTIONLOOP_VARIABLE" end if id == 0xd0 then return "CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE" end if id == 0x81 then return "CMD_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_CONTEXT" end if id == 0xa1 then return "CMD_GET_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE" end if id == 0xd1 then return "CMD_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE" end if id == 0x82 then return "CMD_SUBSCRIBE_TL_CONTEXT" end if id == 0xa2 then return "CMD_GET_TL_VARIABLE" end if id == 0xc2 then return "CMD_SET_TL_VARIABLE" end if id == 0xd2 then return "CMD_SUBSCRIBE_TL_VARIABLE" end if id == 0x83 then return "CMD_SUBSCRIBE_LANE_CONTEXT" end if id == 0xa3 then return "CMD_GET_LANE_VARIABLE" end if id == 0xc3 then return "CMD_SET_LANE_VARIABLE" end if id == 0xd3 then return "CMD_SUBSCRIBE_LANE_VARIABLE" end if id == 0x84 then return "CMD_SUBSCRIBE_VEHICLE_CONTEXT" end if id == 0xa4 then return "CMD_GET_VEHICLE_VARIABLE" end if id == 0xc4 then return "CMD_SET_VEHICLE_VARIABLE" end if id == 0xd4 then return "CMD_SUBSCRIBE_VEHICLE_VARIABLE" end if id == 0x85 then return "CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT" end if id == 0xa5 then return "CMD_GET_VEHICLETYPE_VARIABLE" end if id == 0xc5 then return "CMD_SET_VEHICLETYPE_VARIABLE" end if id == 0xd5 then return "CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE" end if id == 0x86 then return "CMD_SUBSCRIBE_ROUTE_CONTEXT" end if id == 0xa6 then return "CMD_GET_ROUTE_VARIABLE" end if id == 0xc6 then return "CMD_SET_ROUTE_VARIABLE" end if id == 0xd6 then return "CMD_SUBSCRIBE_ROUTE_VARIABLE" end if id == 0x87 then return "CMD_SUBSCRIBE_POI_CONTEXT" end if id == 0xa7 then return "CMD_GET_POI_VARIABLE" end if id == 0xc7 then return "CMD_SET_POI_VARIABLE" end if id == 0xd7 then return "CMD_SUBSCRIBE_POI_VARIABLE" end if id == 0x88 then return "CMD_SUBSCRIBE_POLYGON_CONTEXT" end if id == 0xa8 then return "CMD_GET_POLYGON_VARIABLE" end if id == 0xc8 then return "CMD_SET_POLYGON_VARIABLE" end if id == 0xd8 then return "CMD_SUBSCRIBE_POLYGON_VARIABLE" end if id == 0x89 then return "CMD_SUBSCRIBE_JUNCTION_CONTEXT" end if id == 0xa9 then return "CMD_GET_JUNCTION_VARIABLE" end if id == 0xc9 then return "CMD_SET_JUNCTION_VARIABLE" end if id == 0xd9 then return "CMD_SUBSCRIBE_JUNCTION_VARIABLE" end if id == 0x8a then return "CMD_SUBSCRIBE_EDGE_CONTEXT" end if id == 0xaa then return "CMD_GET_EDGE_VARIABLE" end if id == 0xca then return "CMD_SET_EDGE_VARIABLE" end if id == 0xda then return "CMD_SUBSCRIBE_EDGE_VARIABLE" end if id == 0x8b then return "CMD_SUBSCRIBE_SIM_CONTEXT" end if id == 0xab then return "CMD_GET_SIM_VARIABLE" end if id == 0xcb then return "CMD_SET_SIM_VARIABLE" end if id == 0xdb then return "CMD_SUBSCRIBE_SIM_VARIABLE" end if id == 0x8c then return "CMD_SUBSCRIBE_GUI_CONTEXT" end if id == 0xac then return "CMD_GET_GUI_VARIABLE" end if id == 0xcc then return "CMD_SET_GUI_VARIABLE" end if id == 0xdc then return "CMD_SUBSCRIBE_GUI_VARIABLE" end if id == 0x90 then return "CMD_REROUTE_TRAVELTIME" end if id == 0x91 then return "CMD_REROUTE_EFFORT" end if id == 0x90 then return "RESPONSE_SUBSCRIBE_INDUCTIONLOOP_CONTEXT" end if id == 0xb0 then return "RESPONSE_GET_INDUCTIONLOOP_VARIABLE" end if id == 0xe0 then return "RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE" end if id == 0x91 then return "RESPONSE_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_CONTEXT" end if id == 0xb1 then return "RESPONSE_GET_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE" end if id == 0xe1 then return "RESPONSE_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE" end if id == 0x92 then return "RESPONSE_SUBSCRIBE_TL_CONTEXT" end if id == 0xb2 then return "RESPONSE_GET_TL_VARIABLE" end if id == 0xe2 then return "RESPONSE_SUBSCRIBE_TL_VARIABLE" end if id == 0x93 then return "RESPONSE_SUBSCRIBE_LANE_CONTEXT" end if id == 0xb3 then return "RESPONSE_GET_LANE_VARIABLE" end if id == 0xe3 then return "RESPONSE_SUBSCRIBE_LANE_VARIABLE" end if id == 0x94 then return "RESPONSE_SUBSCRIBE_VEHICLE_CONTEXT" end if id == 0xb4 then return "RESPONSE_GET_VEHICLE_VARIABLE" end if id == 0xe4 then return "RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE" end if id == 0x95 then return "RESPONSE_SUBSCRIBE_VEHICLETYPE_CONTEXT" end if id == 0xb5 then return "RESPONSE_GET_VEHICLETYPE_VARIABLE" end if id == 0xe5 then return "RESPONSE_SUBSCRIBE_VEHICLETYPE_VARIABLE" end if id == 0x96 then return "RESPONSE_SUBSCRIBE_ROUTE_CONTEXT" end if id == 0xb6 then return "RESPONSE_GET_ROUTE_VARIABLE" end if id == 0xe6 then return "RESPONSE_SUBSCRIBE_ROUTE_VARIABLE" end if id == 0x97 then return "RESPONSE_SUBSCRIBE_POI_CONTEXT" end if id == 0xb7 then return "RESPONSE_GET_POI_VARIABLE" end if id == 0xe7 then return "RESPONSE_SUBSCRIBE_POI_VARIABLE" end if id == 0x98 then return "RESPONSE_SUBSCRIBE_POLYGON_CONTEXT" end if id == 0xb8 then return "RESPONSE_GET_POLYGON_VARIABLE" end if id == 0xe8 then return "RESPONSE_SUBSCRIBE_POLYGON_VARIABLE" end if id == 0x99 then return "RESPONSE_SUBSCRIBE_JUNCTION_CONTEXT" end if id == 0xb9 then return "RESPONSE_GET_JUNCTION_VARIABLE" end if id == 0xe9 then return "RESPONSE_SUBSCRIBE_JUNCTION_VARIABLE" end if id == 0x9a then return "RESPONSE_SUBSCRIBE_EDGE_CONTEXT" end if id == 0xba then return "RESPONSE_GET_EDGE_VARIABLE" end if id == 0xea then return "RESPONSE_SUBSCRIBE_EDGE_VARIABLE" end if id == 0x9b then return "RESPONSE_SUBSCRIBE_SIM_CONTEXT" end if id == 0xbb then return "RESPONSE_GET_SIM_VARIABLE" end if id == 0xeb then return "RESPONSE_SUBSCRIBE_SIM_VARIABLE" end if id == 0x9c then return "RESPONSE_SUBSCRIBE_GUI_CONTEXT" end if id == 0xbc then return "RESPONSE_GET_GUI_VARIABLE" end if id == 0xec then return "RESPONSE_SUBSCRIBE_GUI_VARIABLE" end return "unknown" end traci_proto = Proto("TraCI","TraCI (Traffic Control Interface)") function traci_proto.dissector(buffer, pinfo, tree) pinfo.cols.protocol = "TraCI" local msgOffset = 0 while (msgOffset < buffer:len()) do local msg = buffer(msgOffset) if (msg:len() < 4) then -- buffer contains less than 4 Bytes (which we need for reading the message length) -> request to be called again with more packets concatenated to the buffer pinfo.desegment_offset = msgOffset pinfo.desegment_len = 4 - msg:len() return nil end local messageLen = msg(0,4):uint() if (msg:len() < messageLen) then -- buffer contains less Bytes than message length -> request to be called again with more packets concatenated to the buffer pinfo.desegment_offset = msgOffset pinfo.desegment_len = messageLen - msg:len() return nil end -- -- buffer contains (at least) one message -> start parsing message -- local subtreeMsg = tree:add(traci_proto, msg(0, messageLen), "TraCI Message of length " .. messageLen) subtreeMsg:add(msg(0, 4), "Message length: " .. messageLen) cmdOffset = 4 while (cmdOffset < messageLen) do -- read command length local commandLen = tonumber(msg(cmdOffset + 0, 1):uint()) local commandLenExt = 0 local cmdStartOffset = 1 if commandLen == 0 then cmdStartOffset = 5 commandLenExt = tonumber(msg(cmdOffset + 1, 4):uint()) end local commandId = tonumber(msg(cmdOffset + cmdStartOffset, 1):uint()) local subtreeCmd = subtreeMsg:add(traci_proto, msg(cmdOffset + 0, commandLen + commandLenExt), "Command 0x" .. string.format("%X", commandId) .. " (" .. traci_proto_commandIdToString(commandId) .. ")") subtreeCmd:add(msg(cmdOffset + 0, 1), "Command length: " .. commandLen) if commandLenExt > 0 then subtreeCmd:add(msg(cmdOffset + 1, 4), "Command length ext: " .. commandLenExt) end subtreeCmd:add(msg(cmdOffset + cmdStartOffset, 1), "Command id: 0x" .. string.format("%X", commandId) .. " (" .. traci_proto_commandIdToString(commandId) .. ")") if commandLen + commandLenExt - cmdStartOffset - 1 > 0 then subtreeCmd:add(msg(cmdOffset + cmdStartOffset + 1, commandLen + commandLenExt - cmdStartOffset - 1), "Data of length " .. commandLen + commandLenExt - cmdStartOffset - 1) end -- a CMD_SIMSTEP2 returned from the server gets special treatment: it is immediately followed by an (unframed) count of returned subscription results local wasSimstep = (commandId == 2) and (commandLen == 7) and (tonumber(msg(cmdOffset + cmdStartOffset + 1, 1):uint()) == 0) if wasSimstep then local numSubscriptions = tonumber(msg(cmdOffset + commandLen + commandLenExt, 4):uint()) subtreeMsg:add(msg(cmdOffset + commandLen + commandLenExt, 4), "Number of subscription results: " .. numSubscriptions) cmdOffset = cmdOffset + 4 end -- end of command, retry with rest of bytes in this message cmdOffset = cmdOffset + commandLen + commandLenExt end --- end of message, retry with rest of bytes in this packet msgOffset = msgOffset + messageLen end end tcp = DissectorTable.get("tcp.port") tcp:add(9999,traci_proto) -- end
gpl-2.0
visitcasabacardi/backup-nov-08-2015
wp-content/plugins/sociallocker-next-premium/bizpanda/admin/activation.php
5303
<?php /** * Activator for the Business Panda. * * @see Factory325_Activator * @since 1.0.0 */ class OPanda_Activation extends Factory325_Activator { /** * Runs activation actions. * * @since 1.0.0 */ public function activate() { global $bizpanda; do_action('before_bizpanda_activation', $bizpanda, $this); $this->importOptions(); $this->presetOptions(); $this->createPolicies(); $this->createTables(); do_action('after_bizpanda_activation', $bizpanda, $this); } /** * Converts options starting with 'optinpanda_' to 'opanda_'. * * @since 1.0.0 */ protected function importOptions() { global $wpdb; $wpdb->query("UPDATE {$wpdb->options} SET option_name = REPLACE(option_name, 'optinpanda_', 'opanda_') WHERE option_name LIKE 'optinpanda_%'"); $wpdb->query("UPDATE {$wpdb->postmeta} SET meta_key = REPLACE(meta_key, 'optinpanda_', 'opanda_') WHERE meta_key LIKE 'optinpanda_%'"); // Convers options of the Social Locker to the options of the Opt-In Panda $wpdb->query("UPDATE {$wpdb->options} SET option_name = REPLACE(option_name, 'sociallocker_', 'opanda_') WHERE option_name LIKE 'sociallocker_%'"); $wpdb->query("UPDATE {$wpdb->postmeta} SET meta_key = REPLACE(meta_key, 'sociallocker_', 'opanda_') WHERE meta_key LIKE 'sociallocker_%'"); } /** * Presets some options required for the plugin. * * @since 1.0.0 */ protected function presetOptions() { add_option('opanda_facebook_appid', '117100935120196'); add_option('opanda_facebook_version', 'v2.3'); add_option('opanda_lang', 'en_US'); add_option('opanda_short_lang', 'en'); add_option('opanda_tracking', 'true'); add_option('opanda_just_social_buttons', 'false'); add_option('opanda_subscription_service', 'database'); } /** * Creates pages containing the default policies. * * @since 1.0.0 */ protected function createPolicies() { add_option('opanda_terms_enabled', 1); add_option('opanda_terms_use_pages', 0); add_option('opanda_terms_of_use_text', file_get_contents( OPANDA_BIZPANDA_DIR . '/content/terms-of-use.html' )); add_option('opanda_privacy_policy_text', file_get_contents( OPANDA_BIZPANDA_DIR . '/content/privacy-policy.html' )); } /** * Creates table required for the plugin. * * @since 1.0.0 */ protected function createTables() { global $wpdb; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // leads $leads = " CREATE TABLE {$wpdb->prefix}opanda_leads ( ID int(11) UNSIGNED NOT NULL AUTO_INCREMENT, lead_display_name varchar(255) DEFAULT NULL, lead_name varchar(100) DEFAULT NULL, lead_family varchar(100) DEFAULT NULL, lead_email varchar(50) NOT NULL, lead_date int(11) NOT NULL, lead_email_confirmed int(1) NOT NULL DEFAULT 0 COMMENT 'email', lead_subscription_confirmed int(1) NOT NULL DEFAULT 0 COMMENT 'subscription', lead_ip varchar(45) DEFAULT NULL, lead_item_id int(11) DEFAULT NULL, lead_post_id int(11) DEFAULT NULL, lead_item_title varchar(255) DEFAULT NULL, lead_post_title varchar(255) DEFAULT NULL, lead_referer text DEFAULT NULL, PRIMARY KEY (ID), UNIQUE KEY lead_email (lead_email) );"; dbDelta($leads); // leads fields $leadsFields = " CREATE TABLE {$wpdb->prefix}opanda_leads_fields ( lead_id int(10) UNSIGNED NOT NULL, field_name varchar(255) NOT NULL, field_value text NOT NULL, field_custom bit(1) NOT NULL DEFAULT b'0', KEY IDX_wp_opanda_leads_fields_field_name (field_name), UNIQUE KEY UK_wp_opanda_leads_fields (lead_id,field_name) );"; dbDelta($leadsFields); // stats $stats = " CREATE TABLE {$wpdb->prefix}opanda_stats_v2 ( ID bigint(20) NOT NULL AUTO_INCREMENT, aggregate_date date NOT NULL, post_id bigint(20) NOT NULL, item_id int(11) NOT NULL, metric_name varchar(50) NOT NULL, metric_value int(11) NOT NULL DEFAULT 0, PRIMARY KEY (ID), UNIQUE KEY UK_opanda_stats_v2 (aggregate_date,item_id,post_id,metric_name) );"; dbDelta($stats); } } $bizpanda->registerActivation('OPanda_Activation'); function bizpanda_cancel_plugin_deactivation( $cancel ) { if ( !BizPanda::isSinglePlugin() ) return true; return $cancel; } add_filter('factory_cancel_plugin_deactivation_bizpanda', 'bizpanda_cancel_plugin_deactivation');
gpl-2.0
timblepaw/mednafen-rr
src/cdrom/cdromfile.cpp
31958
/* Mednafen - Multi-system Emulator * * Subchannel Q CRC Code: Copyright (C) 1998 Andreas Mueller <mueller@daneb.ping.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef _MSC_VER #include "types.h" #endif #include <sys/types.h> #include <sys/stat.h> #include "../tremor/ivorbisfile.h" #include <string.h> #include <errno.h> #include <time.h> #include <cdio/cdio.h> #include "../mednafen.h" #include "../endian.h" #include "../general.h" #include "cdromif.h" #include "cdromfile.h" #include "dvdisaster.h" #ifndef NO_SNDFILE #include <sndfile.h> #endif static bool LEC_Eval; // lookup table for crc calculation static uint16 subq_crctab[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 }; bool cdrfile_check_subq_checksum(uint8 *SubQBuf) { uint16 crc = 0; uint16 stored_crc = 0; stored_crc = SubQBuf[0xA] << 8; stored_crc |= SubQBuf[0xB]; for(int i = 0; i < 0xA; i++) crc = subq_crctab[(crc >> 8) ^ SubQBuf[i]] ^ (crc << 8); crc = ~crc; return(crc == stored_crc); } // MakeSubQ will OR the simulated Q subchannel data into SubPWBuf. static void MakeSubQ(const CDRFile *p_cdrfile, uint32 lsn, uint8 *SubPWBuf); static char *UnQuotify(char *src, char *dest) { bool in_quote = 0; bool already_normal = 0; while(*src) { if(*src == ' ' || *src == '\t') { if(!in_quote) { if(already_normal) break; else { src++; continue; } } } if(*src == '"') { if(in_quote) { src++; break; } else in_quote = 1; } else { *dest = *src; already_normal = 1; dest++; } src++; } *dest = 0; return(src); } static uint32 GetSectorCount(CDRFILE_TRACK_INFO *track) { // - track->FileOffset is really only meaningful for TOC files if(track->Format == TRACK_FORMAT_DATA) { struct stat stat_buf; if(fstat(fileno(track->fp), &stat_buf)) { //printf("Erra: %m\n", errno); } if(track->IsData2352) { return((stat_buf.st_size - track->FileOffset) / 2352); } else { //printf("%d %d %d\n", (int)stat_buf.st_size, (int)track->FileOffset, (int)stat_buf.st_size - (int)track->FileOffset); return((stat_buf.st_size - track->FileOffset) / 2048); } } else if(track->Format == TRACK_FORMAT_AUDIO) { #ifdef USE_CODECS if(track->sf) { // 2352 / 588 = 4; return(((track->sfinfo.frames * 4) - track->FileOffset) / 2352); } else if(track->ovfile) return(ov_pcm_total(track->ovfile, -1) / 588); else if(track->MPCReaderFile) { return(((track->MPCStreamInfo->frames - 1) * MPC_FRAME_LENGTH + track->MPCStreamInfo->last_frame_samples) / 588); } else #endif //USE_CODECS { struct stat stat_buf; fstat(fileno(track->fp), &stat_buf); //printf("%d %d %d\n", (int)stat_buf.st_size, (int)track->FileOffset, (int)stat_buf.st_size - (int)track->FileOffset); if(track->SubchannelMode) return((stat_buf.st_size - track->FileOffset) / (2352 + 96)); else return((stat_buf.st_size - track->FileOffset) / 2352); } } return(0); } void cdrfile_destroy(CDRFile *p_cdrfile) { if(p_cdrfile->p_cdio) cdio_destroy(p_cdrfile->p_cdio); else { track_t track; for(track = p_cdrfile->FirstTrack; track < (p_cdrfile->FirstTrack + p_cdrfile->NumTracks); track++) { CDRFILE_TRACK_INFO *this_track = &p_cdrfile->Tracks[track]; #ifdef USE_CODECS if(this_track->MPCReaderFile) free(this_track->MPCReaderFile); if(this_track->MPCStreamInfo) free(this_track->MPCStreamInfo); if(this_track->MPCDecoder) free(this_track->MPCDecoder); if(this_track->MPCBuffer) free(this_track->MPCBuffer); if(p_cdrfile->Tracks[track].sf) { sf_close(p_cdrfile->Tracks[track].sf); } if(p_cdrfile->Tracks[track].ovfile) { ov_clear(p_cdrfile->Tracks[track].ovfile); free(p_cdrfile->Tracks[track].ovfile); } else #endif USE_CODECS { if(this_track->FirstFileInstance) fclose(this_track->fp); } } } free(p_cdrfile); } static bool ParseTOCFileLineInfo(CDRFILE_TRACK_INFO *track, const int tracknum, const char *filename, const char *binoffset, const char *msfoffset, const char *length) { long offset = 0; // In bytes! long tmp_long; int m, s, f; uint32 sector_mult; long sectors; std::string efn = MDFN_MakeFName(MDFNMKF_AUX, 0, filename); if(NULL == (track->fp = fopen(efn.c_str(), "rb"))) { MDFN_printf(_("Could not open referenced file \"%s\": %m\n"), efn.c_str(), errno); return(0); } #ifdef USE_CODECS if(strlen(filename) >= 4 && !strcasecmp(filename + strlen(filename) - 4, ".wav")) { if((track->sf = sf_open_fd(fileno(track->fp), SFM_READ, &track->sfinfo, 0))) { } } #endif //USE_CODECS if(track->Format == TRACK_FORMAT_AUDIO || track->IsData2352) sector_mult = 2352; else sector_mult = 2048; if(track->SubchannelMode) sector_mult += 96; if(binoffset && sscanf(binoffset, "%ld", &tmp_long) == 1) { offset += tmp_long; } if(msfoffset && sscanf(msfoffset, "%d:%d:%d", &m, &s, &f) == 3) { offset += ((m * 60 + s) * 75 + f) * sector_mult; } track->FileOffset = offset; // Make sure this is set before calling GetSectorCount()! sectors = GetSectorCount(track); //printf("Track: %d, offset: %ld, %ld\n", tracknum, offset, sectors); if(length) { tmp_long = sectors; if(sscanf(length, "%d:%d:%d", &m, &s, &f) == 3) tmp_long = (m * 60 + s) * 75 + f; else if(track->Format == TRACK_FORMAT_AUDIO) { char *endptr = NULL; tmp_long = strtol(length, &endptr, 10); // Error? if(endptr == length) { tmp_long = sectors; } else tmp_long /= 588; } if(tmp_long > sectors) { MDFN_printf(_("Length specified in TOC file for track %d is too large by %d sectors!\n"), tracknum, tmp_long - sectors); return(FALSE); } sectors = tmp_long; } track->FirstFileInstance = 1; track->sectors = sectors; return(TRUE); } CDRFile *cdrfile_open(const char *path) { CDRFile *ret = (CDRFile *)calloc(1, sizeof(CDRFile)); struct stat stat_buf; if(path == NULL || stat(path, &stat_buf) || !S_ISREG(stat_buf.st_mode)) { CdIo *p_cdio; //char **devices; //adelikat: commenting out an unused variable, since the code is used in is commented out //char **parseit; //adelikat: ditto cdio_init(); GetFileBase("cdrom"); /* devices = cdio_get_devices(DRIVER_UNKNOWN); parseit = devices; if(parseit) { MDFN_printf(_("Connected physical devices:\n")); MDFN_indent(1); while(*parseit) { MDFN_printf("%s\n", *parseit); parseit++; } MDFN_indent(-1); } if(!parseit || parseit == devices) { MDFN_PrintError(_("No CDROM drives detected(or no disc present).")); if(devices) cdio_free_device_list(devices); free(ret); return(NULL); } if(devices) cdio_free_device_list(devices);*/ p_cdio = cdio_open_cd(path); //, DRIVER_UNKNOWN); //NULL, DRIVER_UNKNOWN); if(!p_cdio) { free(ret); return(NULL); } ret->p_cdio = p_cdio; ret->FirstTrack = cdio_get_first_track_num(ret->p_cdio); ret->NumTracks = cdio_get_num_tracks(ret->p_cdio); ret->total_sectors = cdio_stat_size(ret->p_cdio); for(track_t track = ret->FirstTrack; track < (ret->FirstTrack + ret->NumTracks); track++) { memset(&ret->Tracks[track], 0, sizeof(CDRFILE_TRACK_INFO)); ret->Tracks[track].sectors = cdio_get_track_sec_count(ret->p_cdio, track); ret->Tracks[track].LSN = cdio_get_track_lsn(ret->p_cdio, track); ret->Tracks[track].Format = cdio_get_track_format(ret->p_cdio, track); } return(ret); } FILE *fp = fopen(path, "rb"); bool IsTOC = FALSE; // Assign opposite maximum values so our tests will work! int FirstTrack = 99; int LastTrack = 0; if(!fp) { MDFN_PrintError(_("Error opening CUE sheet/TOC \"%s\": %m\n"), path, errno); free(ret); return(NULL); } GetFileBase(path); char linebuf[512]; int32 active_track = -1; int32 AutoTrackInc = 1; // For TOC CDRFILE_TRACK_INFO TmpTrack; memset(&TmpTrack, 0, sizeof(TmpTrack)); while(fgets(linebuf, 512, fp) > 0) { char cmdbuf[512], raw_args[512], args[4][512]; int argcount = 0; raw_args[0] = 0; cmdbuf[0] = 0; args[0][0] = args[1][0] = args[2][0] = args[3][0] = 0; if(!strncasecmp(linebuf, "CD_ROM", 6) || !strncasecmp(linebuf, "CD_DA", 5) || !strncasecmp(linebuf, "CD_ROM_XA", 9)) { IsTOC = TRUE; puts("TOC file detected."); } if(IsTOC) { char *ss_loc = strstr(linebuf, "//"); if(ss_loc) { ss_loc[0] = '\n'; // For consistency! ss_loc[1] = 0; } } sscanf(linebuf, "%s %[^\r\n]", cmdbuf, raw_args); if(!strcasecmp(cmdbuf, "CD_ROM") || !strcasecmp(cmdbuf, "CD_DA")) IsTOC = TRUE; UnQuotify(UnQuotify(UnQuotify(UnQuotify(raw_args, args[0]), args[1]), args[2]), args[3]); if(args[0][0]) { argcount++; if(args[1][0]) { argcount++; if(args[2][0]) { argcount++; if(args[3][0]) { argcount++; } } } } if(IsTOC) { if(!strcasecmp(cmdbuf, "TRACK")) { if(active_track >= 0) { memcpy(&ret->Tracks[active_track], &TmpTrack, sizeof(TmpTrack)); memset(&TmpTrack, 0, sizeof(TmpTrack)); active_track = -1; } if(AutoTrackInc > 99) { MDFN_printf(_("Invalid track number: %d\n"), AutoTrackInc); free(ret); return(NULL); } active_track = AutoTrackInc++; if(active_track < FirstTrack) FirstTrack = active_track; if(active_track > LastTrack) LastTrack = active_track; if(!strcasecmp(args[0], "AUDIO")) { TmpTrack.Format = TRACK_FORMAT_AUDIO; TmpTrack.RawAudioMSBFirst = TRUE; // Silly cdrdao... } else if(!strcasecmp(args[0], "MODE1")) { TmpTrack.Format = TRACK_FORMAT_DATA; TmpTrack.IsData2352 = 0; } else if(!strcasecmp(args[0], "MODE1_RAW")) { TmpTrack.Format = TRACK_FORMAT_DATA; TmpTrack.IsData2352 = 1; } if(!strcasecmp(args[1], "RW")) { TmpTrack.SubchannelMode = CDRF_SUBM_RW; MDFN_printf(_("\"RW\" format subchannel data not supported, only \"RW_RAW\" is!\n")); free(ret); return(0); } else if(!strcasecmp(args[1], "RW_RAW")) TmpTrack.SubchannelMode = CDRF_SUBM_RW_RAW; } // end to TRACK else if(!strcasecmp(cmdbuf, "SILENCE")) { } else if(!strcasecmp(cmdbuf, "ZERO")) { } else if(!strcasecmp(cmdbuf, "FILE") || !strcasecmp(cmdbuf, "AUDIOFILE")) { const char *binoffset = NULL; const char *msfoffset = NULL; const char *length = NULL; if(args[1][0] == '#') { binoffset = args[1] + 1; msfoffset = args[2]; length = args[3]; } else { msfoffset = args[1]; length = args[2]; } //printf("%s, %s, %s, %s\n", args[0], binoffset, msfoffset, length); if(!ParseTOCFileLineInfo(&TmpTrack, active_track, args[0], binoffset, msfoffset, length)) { free(ret); return(0); } } else if(!strcasecmp(cmdbuf, "DATAFILE")) { const char *binoffset = NULL; const char *length = NULL; if(args[1][0] == '#') { binoffset = args[1] + 1; length = args[2]; } else length = args[1]; if(!ParseTOCFileLineInfo(&TmpTrack, active_track, args[0], binoffset, NULL, length)) { free(ret); return(0); } } else if(!strcasecmp(cmdbuf, "INDEX")) { } else if(!strcasecmp(cmdbuf, "PREGAP")) { if(active_track < 0) { MDFN_printf(_("Command %s is outside of a TRACK definition!\n"), cmdbuf); free(ret); return(NULL); } int m,s,f; sscanf(args[0], "%d:%d:%d", &m, &s, &f); TmpTrack.pregap = (m * 60 + s) * 75 + f; } // end to PREGAP else if(!strcasecmp(cmdbuf, "START")) { if(active_track < 0) { MDFN_printf(_("Command %s is outside of a TRACK definition!\n"), cmdbuf); free(ret); return(NULL); } int m,s,f; sscanf(args[0], "%d:%d:%d", &m, &s, &f); TmpTrack.pregap = (m * 60 + s) * 75 + f; } } /*********** END TOC HANDLING ************/ else // now for CUE sheet handling { if(!strcasecmp(cmdbuf, "FILE")) { if(active_track >= 0) { memcpy(&ret->Tracks[active_track], &TmpTrack, sizeof(TmpTrack)); memset(&TmpTrack, 0, sizeof(TmpTrack)); active_track = -1; } std::string efn = MDFN_MakeFName(MDFNMKF_AUX, 0, args[0]); if(NULL == (TmpTrack.fp = fopen(efn.c_str(), "rb"))) { MDFN_printf(_("Could not open referenced file \"%s\": %m\n"), efn.c_str(), errno); free(ret); return(0); } TmpTrack.FirstFileInstance = 1; if(!strcasecmp(args[1], "BINARY")) { //TmpTrack.Format = TRACK_FORMAT_DATA; //struct stat stat_buf; //fstat(fileno(TmpTrack.fp), &stat_buf); //TmpTrack.sectors = stat_buf.st_size; // / 2048; } #ifdef USE_CODECS else if(!strcasecmp(args[1], "OGG") || !strcasecmp(args[1], "VORBIS") || !strcasecmp(args[1], "WAVE") || !strcasecmp(args[1], "WAV") || !strcasecmp(args[1], "PCM") || !strcasecmp(args[1], "MPC") || !strcasecmp(args[1], "MP+")) { TmpTrack.ovfile = (OggVorbis_File *) calloc(1, sizeof(OggVorbis_File)); if((TmpTrack.sf = sf_open_fd(fileno(TmpTrack.fp), SFM_READ, &TmpTrack.sfinfo, 0))) { free(TmpTrack.ovfile); TmpTrack.ovfile = NULL; } else if(!lseek(fileno(TmpTrack.fp), 0, SEEK_SET) && !ov_open(TmpTrack.fp, TmpTrack.ovfile, NULL, 0)) { //TmpTrack.Format = TRACK_FORMAT_AUDIO; //TmpTrack.sectors = ov_pcm_total(&TmpTrack.ovfile, -1) / 588; } else { free(TmpTrack.ovfile); TmpTrack.ovfile = NULL; fseek(TmpTrack.fp, 0, SEEK_SET); TmpTrack.MPCReaderFile = (mpc_reader_file *)calloc(1, sizeof(mpc_reader_file)); TmpTrack.MPCStreamInfo = (mpc_streaminfo *)calloc(1, sizeof(mpc_streaminfo)); TmpTrack.MPCDecoder = (mpc_decoder *)calloc(1, sizeof(mpc_decoder)); TmpTrack.MPCBuffer = (MPC_SAMPLE_FORMAT *)calloc(MPC_DECODER_BUFFER_LENGTH, sizeof(MPC_SAMPLE_FORMAT)); mpc_streaminfo_init(TmpTrack.MPCStreamInfo); mpc_reader_setup_file_reader(TmpTrack.MPCReaderFile, TmpTrack.fp); if(mpc_streaminfo_read(TmpTrack.MPCStreamInfo, &TmpTrack.MPCReaderFile->reader) != ERROR_CODE_OK) { MDFN_printf(_("Unsupported audio track file format: %s\n"), args[0]); free(TmpTrack.MPCReaderFile); free(TmpTrack.MPCStreamInfo); free(TmpTrack.MPCDecoder); free(TmpTrack.MPCBuffer); free(ret); return(0); } mpc_decoder_setup(TmpTrack.MPCDecoder, &TmpTrack.MPCReaderFile->reader); if(!mpc_decoder_initialize(TmpTrack.MPCDecoder, TmpTrack.MPCStreamInfo)) { MDFN_printf(_("Error initializing MusePack decoder: %s!\n"), args[0]); free(TmpTrack.MPCReaderFile); free(TmpTrack.MPCStreamInfo); free(TmpTrack.MPCDecoder); free(TmpTrack.MPCBuffer); free(ret); return(0); } } } #endif //USE_CODECS else { MDFN_printf(_("Unsupported track format: %s\n"), args[1]); free(ret); return(0); } } else if(!strcasecmp(cmdbuf, "TRACK")) { if(active_track >= 0) { memcpy(&ret->Tracks[active_track], &TmpTrack, sizeof(TmpTrack)); TmpTrack.FirstFileInstance = 0; TmpTrack.pregap = 0; } active_track = atoi(args[0]); if(active_track < FirstTrack) FirstTrack = active_track; if(active_track > LastTrack) LastTrack = active_track; if(!strcasecmp(args[1], "AUDIO")) TmpTrack.Format = TRACK_FORMAT_AUDIO; else if(!strcasecmp(args[1], "MODE1/2048")) { TmpTrack.Format = TRACK_FORMAT_DATA; TmpTrack.IsData2352 = 0; } else if(!strcasecmp(args[1], "MODE1/2352")) { TmpTrack.Format = TRACK_FORMAT_DATA; TmpTrack.IsData2352 = 1; } TmpTrack.sectors = GetSectorCount(&TmpTrack); if(active_track < 0 || active_track > 99) { MDFN_printf(_("Invalid track number: %d\n"), active_track); return(0); } } else if(!strcasecmp(cmdbuf, "INDEX")) { if(active_track >= 0 && (!strcasecmp(args[0], "01") || !strcasecmp(args[0], "1"))) { int m,s,f; sscanf(args[1], "%d:%d:%d", &m, &s, &f); TmpTrack.index = (m * 60 + s) * 75 + f; } } else if(!strcasecmp(cmdbuf, "PREGAP")) { if(active_track >= 0) { int m,s,f; sscanf(args[0], "%d:%d:%d", &m, &s, &f); TmpTrack.pregap = (m * 60 + s) * 75 + f; } } } // end of CUE sheet handling } // end of fgets() loop if(ferror(fp)) { if(IsTOC) MDFN_printf(_("Error reading TOC file: %m\n"), errno); else MDFN_printf(_("Error reading CUE sheet: %m\n"), errno); return(0); } if(active_track >= 0) memcpy(&ret->Tracks[active_track], &TmpTrack, sizeof(TmpTrack)); if(FirstTrack > LastTrack) { MDFN_printf(_("No tracks found!\n")); return(0); } ret->FirstTrack = FirstTrack; ret->NumTracks = 1 + LastTrack - FirstTrack; lsn_t RunningLSN = 0; lsn_t LastIndex = 0; long FileOffset = 0; for(int x = ret->FirstTrack; x < (ret->FirstTrack + ret->NumTracks); x++) { if(IsTOC) { RunningLSN += ret->Tracks[x].pregap; ret->Tracks[x].LSN = RunningLSN; RunningLSN += ret->Tracks[x].sectors; } else // else handle CUE sheet... { if(ret->Tracks[x].FirstFileInstance) { LastIndex = 0; FileOffset = 0; } RunningLSN += ret->Tracks[x].pregap; ret->Tracks[x].LSN = RunningLSN; if((x+1) >= (ret->FirstTrack + ret->NumTracks)) { if(!(ret->Tracks[x].FirstFileInstance)) { // This will fix the last sector count for CUE+BIN ret->Tracks[x].sectors = GetSectorCount(&ret->Tracks[x]) - ret->Tracks[x - 1].index; } } else if(ret->Tracks[x+1].FirstFileInstance) { //RunningLSN += ret->Tracks[x].sectors; } else { // Fix the sector count if we're CUE+BIN ret->Tracks[x].sectors = ret->Tracks[x + 1].index - ret->Tracks[x].index; } //printf("Poo: %d %d\n", x, ret->Tracks[x].sectors); RunningLSN += ret->Tracks[x].sectors; //printf("%d, %ld %d %d %d %d\n", x, FileOffset, ret->Tracks[x].index, ret->Tracks[x].pregap, ret->Tracks[x].sectors, ret->Tracks[x].LSN); ret->Tracks[x].FileOffset = FileOffset; if(ret->Tracks[x].Format == TRACK_FORMAT_AUDIO || TmpTrack.IsData2352) FileOffset += ret->Tracks[x].sectors * 2352; else FileOffset += ret->Tracks[x].sectors * 2048; } // end to cue sheet handling } // end to track loop LEC_Eval = MDFN_GetSettingB("cdrom.lec_eval"); if(LEC_Eval) { Init_LEC_Correct(); } MDFN_printf(_("Raw rip data correction using L-EC: %s\n\n"), LEC_Eval ? _("Enabled") : _("Disabled")); ret->total_sectors = RunningLSN; // Running LBA? Running LSN? arghafsdf...LSNBAN!#!$ -_- return(ret); } lsn_t cdrfile_get_track_lsn(const CDRFile *p_cdrfile, track_t i_track) { return(p_cdrfile->Tracks[i_track].LSN); } int cdrfile_read_audio_sector(CDRFile *p_cdrfile, void *buf, uint8 *SubPWBuf, lsn_t lsn) { if(SubPWBuf) { memset(SubPWBuf, 0, 96); MakeSubQ(p_cdrfile, lsn, SubPWBuf); } if(p_cdrfile->p_cdio) { if(cdio_read_audio_sector(p_cdrfile->p_cdio, buf, lsn) < 0) { memset(buf, 0, 2352); return(0); } Endian_A16_LE_to_NE(buf, 588 * 2); return(1); } else { track_t track; for(track = p_cdrfile->FirstTrack; track < (p_cdrfile->FirstTrack + p_cdrfile->NumTracks); track++) { if(lsn >= (p_cdrfile->Tracks[track].LSN - p_cdrfile->Tracks[track].pregap) && lsn < (p_cdrfile->Tracks[track].LSN + p_cdrfile->Tracks[track].sectors)) { if(lsn < p_cdrfile->Tracks[track].LSN) { //puts("Pregap read"); memset(buf, 0, 2352); } else { #ifdef USE_CODECS if(p_cdrfile->Tracks[track].sf) { long SeekPos = (p_cdrfile->Tracks[track].FileOffset / 4) + (lsn - p_cdrfile->Tracks[track].LSN) * 588; //printf("%d, %d\n", lsn, p_cdrfile->Tracks[track].LSN); if(p_cdrfile->Tracks[track].LastSamplePos != SeekPos) { //printf("Seek: %d %d\n", SeekPos, p_cdrfile->Tracks[track].LastSamplePos); sf_seek(p_cdrfile->Tracks[track].sf, SeekPos, SEEK_SET); p_cdrfile->Tracks[track].LastSamplePos = SeekPos; } sf_count_t readcount = sf_read_short(p_cdrfile->Tracks[track].sf, (short*)buf, 588 * 2); p_cdrfile->Tracks[track].LastSamplePos += readcount / 2; } else if(p_cdrfile->Tracks[track].ovfile)// vorbis { int cursection = 0; if(p_cdrfile->Tracks[track].LastSamplePos != 588 * (lsn - p_cdrfile->Tracks[track].LSN)) { ov_pcm_seek((OggVorbis_File *)p_cdrfile->Tracks[track].ovfile, (lsn - p_cdrfile->Tracks[track].LSN) * 588); p_cdrfile->Tracks[track].LastSamplePos = 588 * (lsn - p_cdrfile->Tracks[track].LSN); } long toread = 2352; while(toread > 0) { long didread = ov_read((OggVorbis_File *)p_cdrfile->Tracks[track].ovfile, (char*)buf, toread, &cursection); if(didread == 0) { memset(buf, 0, toread); toread = 0; break; } buf = (uint8 *)buf + didread; toread -= didread; p_cdrfile->Tracks[track].LastSamplePos += didread / 4; } } // end if vorbis else if(p_cdrfile->Tracks[track].MPCReaderFile) // MPC { //printf("%d %d\n", (lsn - p_cdrfile->Tracks[track].LSN), p_cdrfile->Tracks[track].LastSamplePos); if(p_cdrfile->Tracks[track].LastSamplePos != 1176 * (lsn - p_cdrfile->Tracks[track].LSN)) { mpc_decoder_seek_sample(p_cdrfile->Tracks[track].MPCDecoder, 588 * (lsn - p_cdrfile->Tracks[track].LSN)); p_cdrfile->Tracks[track].LastSamplePos = 1176 * (lsn - p_cdrfile->Tracks[track].LSN); } //MPC_SAMPLE_FORMAT sample_buffer[MPC_DECODER_BUFFER_LENGTH]; // MPC_SAMPLE_FORMAT MPCBuffer[MPC_DECODER_BUFFER_LENGTH]; // uint32 MPCBufferIn; int16 *cowbuf = (int16 *)buf; int32 toread = 1176; while(toread) { int32 tmplen; if(!p_cdrfile->Tracks[track].MPCBufferIn) { int status = mpc_decoder_decode(p_cdrfile->Tracks[track].MPCDecoder, p_cdrfile->Tracks[track].MPCBuffer, 0, 0); if(status < 0) { printf("Bah\n"); break; } p_cdrfile->Tracks[track].MPCBufferIn = status * 2; p_cdrfile->Tracks[track].MPCBufferOffs = 0; } tmplen = p_cdrfile->Tracks[track].MPCBufferIn; if(tmplen >= toread) tmplen = toread; for(int x = 0; x < tmplen; x++) { int32 samp = p_cdrfile->Tracks[track].MPCBuffer[p_cdrfile->Tracks[track].MPCBufferOffs + x] >> 14; //if(samp < - 32768 || samp > 32767) // This happens with some MPCs of ripped games I've tested, and it's not just 1 or 2 over, and I don't know why! // printf("MPC Sample out of range: %d\n", samp); *cowbuf = (int16)samp; cowbuf++; } p_cdrfile->Tracks[track].MPCBufferOffs += tmplen; toread -= tmplen; p_cdrfile->Tracks[track].LastSamplePos += tmplen; p_cdrfile->Tracks[track].MPCBufferIn -= tmplen; } } else // Binary, woo. #endif //use codecs { long SeekPos = p_cdrfile->Tracks[track].FileOffset + 2352 * (lsn - p_cdrfile->Tracks[track].LSN); //(lsn - p_cdrfile->Tracks[track].index - p_cdrfile->Tracks[track].pregap); if(p_cdrfile->Tracks[track].SubchannelMode) SeekPos += 96 * (lsn - p_cdrfile->Tracks[track].LSN); if(!fseek(p_cdrfile->Tracks[track].fp, SeekPos, SEEK_SET)) { size_t didread = fread(buf, 1, 2352, p_cdrfile->Tracks[track].fp); if(didread != 2352) { if(didread < 0) didread = 0; memset((uint8*)buf + didread, 0, 2352 - didread); } if(SubPWBuf && p_cdrfile->Tracks[track].SubchannelMode) { fread(SubPWBuf, 1, 96, p_cdrfile->Tracks[track].fp); } if(p_cdrfile->Tracks[track].RawAudioMSBFirst) Endian_A16_BE_to_NE(buf, 588 * 2); else Endian_A16_LE_to_NE(buf, 588 * 2); } else memset(buf, 0, 2352); } } // end if audible part of audio track read. break; } // End if LSN is in range } // end track search loop if(track == (p_cdrfile->FirstTrack + p_cdrfile->NumTracks)) { memset(buf, 0, 2352); return(0); } return(1); } } track_t cdrfile_get_num_tracks (const CDRFile *p_cdrfile) { return(p_cdrfile->NumTracks); } track_format_t cdrfile_get_track_format(const CDRFile *p_cdrfile, track_t i_track) { return(p_cdrfile->Tracks[i_track].Format); } unsigned int cdrfile_get_track_sec_count(const CDRFile *p_cdrfile, track_t i_track) { return(p_cdrfile->Tracks[i_track].sectors); } track_t cdrfile_get_first_track_num(const CDRFile *p_cdrfile) { return(p_cdrfile->FirstTrack); } static void MakeSubQ(const CDRFile *p_cdrfile, uint32 lsn, uint8 *SubPWBuf) { uint8 buf[0xC]; track_t track; track_format_t tf; uint32 lsn_relative; uint32 ma, sa, fa; uint32 m, s, f; bool track_found = FALSE; for(track = p_cdrfile->FirstTrack; track < (p_cdrfile->FirstTrack + p_cdrfile->NumTracks); track++) { if((int)lsn >= (p_cdrfile->Tracks[track].LSN - p_cdrfile->Tracks[track].pregap) && (int)lsn < (p_cdrfile->Tracks[track].LSN + p_cdrfile->Tracks[track].sectors)) { track_found = true; break; } } if(!track_found) { puts("MakeSubQ error!"); track = p_cdrfile->FirstTrack; } tf = p_cdrfile->Tracks[track].Format; lsn_relative = abs((int32)lsn - p_cdrfile->Tracks[track].LSN); f = (lsn_relative % 75); s = ((lsn_relative / 75) % 60); m = (lsn_relative / 75 / 60); fa = (lsn + 150) % 75; sa = ((lsn + 150) / 75) % 60; ma = ((lsn + 150) / 75 / 60); uint8 adr = 0x1; // Q channel data encodes position uint8 control = (tf == TRACK_FORMAT_AUDIO) ? 0x00 : 0x04; buf[0] = (adr << 0) | (control << 4); buf[1] = INT_TO_BCD(track); if((int)lsn < p_cdrfile->Tracks[track].LSN) // Index is 00 in pregap buf[2] = INT_TO_BCD(0x00); else buf[2] = INT_TO_BCD(0x01); // Track relative MSF address buf[3] = INT_TO_BCD(m); buf[4] = INT_TO_BCD(s); buf[5] = INT_TO_BCD(f); buf[6] = 0; // Zerroooo // Absolute MSF address buf[7] = INT_TO_BCD(ma); buf[8] = INT_TO_BCD(sa); buf[9] = INT_TO_BCD(fa); uint16 crc = 0; for(int i = 0; i < 0xA; i++) crc = subq_crctab[(crc >> 8) ^ buf[i]] ^ (crc << 8); // Checksum buf[0xa] = ~(crc >> 8); buf[0xb] = ~(crc); for(int i = 0; i < 96; i++) SubPWBuf[i] |= ((buf[i >> 3] >> (7 - (i & 0x7))) & 1) ? 0x40 : 0x00; } int cdrfile_read_mode1_sectors (const CDRFile *p_cdrfile, void *buf, uint8 *SubPWBuf, lsn_t lsn, bool b_form2, unsigned int i_sectors) { if(SubPWBuf) { memset(SubPWBuf, 0, 96); MakeSubQ(p_cdrfile, lsn, SubPWBuf); } if(p_cdrfile->p_cdio) { while(cdio_read_mode1_sectors(p_cdrfile->p_cdio, buf, lsn, b_form2, i_sectors) < 0) { if(MDFND_ExitBlockingLoop()) return(0); } return(1); } else { lsn_t end_lsn = lsn + i_sectors - 1; for(;lsn <= end_lsn; lsn++) { track_t track; for(track = p_cdrfile->FirstTrack; track < (p_cdrfile->FirstTrack + p_cdrfile->NumTracks); track++) { unsigned int lt_lsn; // = p_cdrfile->Tracks[track].LSN + p_cdrfile->Tracks[track].sectors; if((track + 1) < (p_cdrfile->FirstTrack + p_cdrfile->NumTracks)) lt_lsn = p_cdrfile->Tracks[track + 1].LSN; else lt_lsn = ~0; if(lsn >= (p_cdrfile->Tracks[track].LSN - p_cdrfile->Tracks[track].pregap) && lsn < (int)lt_lsn) { if(lsn < p_cdrfile->Tracks[track].LSN) { MDFN_printf("PREGAPREAD!!! mode1 sector read out of range!\n"); memset(buf, 0x00, 2048); } else { long SeekPos = p_cdrfile->Tracks[track].FileOffset; long LSNRelPos = lsn - p_cdrfile->Tracks[track].LSN; //lsn - p_cdrfile->Tracks[track].index - p_cdrfile->Tracks[track].pregap; uint8 raw_read_buf[2352 * 6]; if(p_cdrfile->Tracks[track].IsData2352) SeekPos += LSNRelPos * 2352; else SeekPos += LSNRelPos * 2048; if(p_cdrfile->Tracks[track].SubchannelMode) SeekPos += 96 * (lsn - p_cdrfile->Tracks[track].LSN); fseek(p_cdrfile->Tracks[track].fp, SeekPos, SEEK_SET); if(p_cdrfile->Tracks[track].IsData2352) { // + 12 + 3 + 1; fread(raw_read_buf, 1, 2352, p_cdrfile->Tracks[track].fp); if(LEC_Eval) { if(!ValidateRawSector(raw_read_buf, FALSE)) { MDFN_DispMessage((UTF8*)_("Uncorrectable data at sector %d"), lsn); MDFN_PrintError(_("Uncorrectable data at sector %d"), lsn); } } memcpy(buf, raw_read_buf + 12 + 3 + 1, 2048); } else fread(buf, 1, 2048, p_cdrfile->Tracks[track].fp); if(SubPWBuf && p_cdrfile->Tracks[track].SubchannelMode) { if(p_cdrfile->Tracks[track].IsData2352) fseek(p_cdrfile->Tracks[track].fp, 2352 - (12 + 3 + 1 + 2048), SEEK_CUR); fread(SubPWBuf, 1, 96, p_cdrfile->Tracks[track].fp); } } break; } } if(track == (p_cdrfile->FirstTrack + p_cdrfile->NumTracks)) { MDFN_printf("mode1 sector read out of range!\n"); memset(buf, 0x00, 2048); } buf = (uint8*)buf + 2048; } return(1); } } uint32_t cdrfile_stat_size (const CDRFile *p_cdrfile) { return(p_cdrfile->total_sectors); }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/compiler/graalunit/JttReflectAETest.java
1604
/* * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @summary * @requires vm.jvmci * * @modules jdk.internal.vm.compiler * * @library /test/lib /compiler/graalunit / * * @build compiler.graalunit.common.GraalUnitTestLauncher * * @run driver jdk.test.lib.FileInstaller ../../ProblemList-graal.txt ExcludeList.txt * * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI compiler.graalunit.common.GraalUnitTestLauncher -prefix org.graalvm.compiler.jtt.reflect.[a-eA-E] -exclude ExcludeList.txt */ /* DO NOT MODIFY THIS FILE. GENERATED BY generateTests.sh */
gpl-2.0
hardvain/mono-compiler
class/System.ServiceModel/System.ServiceModel/HttpBindingBase.cs
4275
// // HttpBindingBase.cs // // Authors: // Atsushi Enomoto <atsushi@ximian.com> // Martin Baulig <martin.baulig@xamarin.com> // // Copyright (C) 2005-2006 Novell, Inc. http://www.novell.com // Copyright 2011-2012 Xamarin Inc (http://www.xamarin.com). // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Net; using System.Net.Security; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.Text; using System.Xml; using System.ServiceModel.Configuration; namespace System.ServiceModel { public abstract class HttpBindingBase : Binding, IBindingRuntimePreferences { bool allow_cookies, bypass_proxy_on_local; HostNameComparisonMode host_name_comparison_mode = HostNameComparisonMode.StrongWildcard; long max_buffer_pool_size = 0x80000; int max_buffer_size = 0x10000; long max_recv_message_size = 0x10000; Uri proxy_address; XmlDictionaryReaderQuotas reader_quotas = new XmlDictionaryReaderQuotas (); EnvelopeVersion env_version = EnvelopeVersion.Soap11; Encoding text_encoding = default_text_encoding; static readonly Encoding default_text_encoding = new UTF8Encoding (); TransferMode transfer_mode = TransferMode.Buffered; bool use_default_web_proxy = true; public bool AllowCookies { get { return allow_cookies; } set { allow_cookies = value; } } public bool BypassProxyOnLocal { get { return bypass_proxy_on_local; } set { bypass_proxy_on_local = value; } } public HostNameComparisonMode HostNameComparisonMode { get { return host_name_comparison_mode; } set { host_name_comparison_mode = value; } } public long MaxBufferPoolSize { get { return max_buffer_pool_size; } set { if (value <= 0) throw new ArgumentOutOfRangeException (); max_buffer_pool_size = value; } } public int MaxBufferSize { get { return max_buffer_size; } set { if (value <= 0) throw new ArgumentOutOfRangeException (); max_buffer_size = value; } } public long MaxReceivedMessageSize { get { return max_recv_message_size; } set { if (value <= 0) throw new ArgumentOutOfRangeException (); max_recv_message_size = value; } } public Uri ProxyAddress { get { return proxy_address; } set { proxy_address = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return reader_quotas; } set { reader_quotas = value; } } public override abstract string Scheme { get; } public EnvelopeVersion EnvelopeVersion { get { return env_version; } } internal static Encoding DefaultTextEncoding { get { return default_text_encoding; } } public Encoding TextEncoding { get { return text_encoding; } set { text_encoding = value; } } public TransferMode TransferMode { get { return transfer_mode; } set { transfer_mode = value; } } public bool UseDefaultWebProxy { get { return use_default_web_proxy; } set { use_default_web_proxy = value; } } public override abstract BindingElementCollection CreateBindingElements (); // explicit interface implementations bool IBindingRuntimePreferences.ReceiveSynchronously { get { return false; } } } }
gpl-2.0
arodchen/MaxSim
graal/graal/com.oracle.graal.jtt/src/com/oracle/graal/jtt/except/Catch_Unresolved02.java
2655
/* * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.jtt.except; import com.oracle.graal.jtt.*; import org.junit.*; /* */ public class Catch_Unresolved02 extends JTTTest { public static boolean executed; public static int value; public static int test(int arg) { executed = false; int result = 0; try { result = value + helper1(arg) + helper2(arg); } catch (Catch_Unresolved02_Exception1 e) { return 1 + result; } catch (Catch_Unresolved02_Exception2 e) { return 2 + result; } return result; } private static int helper1(int arg) { if (executed) { throw new IllegalStateException("helper1 may only be called once"); } executed = true; if (arg == 1) { throw new Catch_Unresolved02_Exception1(); } else if (arg == 2) { throw new Catch_Unresolved02_Exception2(); } return 0; } private static int helper2(int arg) { if (arg != 0) { throw new IllegalStateException("helper2 can only be called if arg==0"); } return 0; } @Test public void run0() throws Throwable { runTest("test", 0); } @Test public void run1() throws Throwable { runTest("test", 1); } @Test public void run2() throws Throwable { runTest("test", 2); } } @SuppressWarnings("serial") class Catch_Unresolved02_Exception1 extends RuntimeException { } @SuppressWarnings("serial") class Catch_Unresolved02_Exception2 extends RuntimeException { }
gpl-2.0
alpdogan/wtrends
wp-content/themes/detube/widgets/widget-ad.php
4331
<?php /** * DP Ad Widget * * Displays the advertising, supported Plain Text, HTML, PHP or Shortcode. * * @package deTube * @subpackage Widgets * @since deTube 1.0 */ class DP_Widget_Ad extends WP_Widget { function __construct() { $widget_ops = array('classname' => 'widget-ad', 'description' => __('Displays the advertising.', 'dp') ); $control_ops = array('width' => 400, 'height' => 350); parent::__construct("dp-ad", __('(DeDePress) Advertising', 'dp'), $widget_ops, $control_ops ); } function widget($args, $instance) { extract($args); $image = $instance['image']; $url = $instance['url']; $alt = $instance['alt']; $code = $instance['code']; $target = !empty($instance['target']) ? ' target="_blank"' : ''; $nofollow = !empty($instance['nofollow']) ? ' rel="nofollow"' : ''; echo $before_widget; if ( $instance['title'] ) echo $before_title . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $after_title; echo '<div class="ad-widget">'; if(!empty($code)) echo wp_kses_stripslashes($code); else echo '<a'.$target.$nofollow.' href="'.$url.'"><img src="'.$image.'" alt="'.$alt.'" /></a>'; echo '</div>'; echo $after_widget; } function update($new_instance, $old_instance) { $instance = $old_instance; $instance = $new_instance; $instance['target'] = isset($new_instance['target']) ? 1 : 0; $instance['nofollow'] = isset($new_instance['nofollow']) ? 1 : 0; return $instance; } function form($instance) { // Defaults $defaults = array( 'title' => '', 'image' => '', 'url' => '', 'text' => '', 'alt' => '', 'target' => true, 'nofollow' => true, 'code' => '' ); $instance = wp_parse_args( (array) $instance, $defaults); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','dp'); ?></label> <input type="text" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" /> </p> <h4><?php _e('Image Ad','dp'); ?></h4> <p> <label for="<?php echo $this->get_field_id('url'); ?>"><?php _e('Link URL:','dp'); ?></label> <input type="text" name="<?php echo $this->get_field_name('url'); ?>" value="<?php echo $instance['url']; ?>" class="widefat" id="<?php echo $this->get_field_id('url'); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('image'); ?>"><?php _e('Image URL:','dp'); ?></label> <input type="text" name="<?php echo $this->get_field_name('image'); ?>" value="<?php echo $instance['image']; ?>" class="widefat" id="<?php echo $this->get_field_id('image'); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('alt'); ?>"><?php _e('Alternate Text:','dp'); ?></label> <input type="text" name="<?php echo $this->get_field_name('alt'); ?>" value="<?php echo $instance['alt']; ?>" class="widefat" id="<?php echo $this->get_field_id('alt'); ?>" /> </p> <p> <input type="checkbox" value="1" name="<?php echo $this->get_field_name('target'); ?>" id="<?php echo $this->get_field_id('target'); ?>" <?php checked($instance['target'], true); ?> /> <label for="<?php echo $this->get_field_id('target'); ?>"><?php _e('Open link in new window or tab?', 'dp'); ?></label> </p> <p> <input type="checkbox" value="1" name="<?php echo $this->get_field_name('nofollow'); ?>" id="<?php echo $this->get_field_id('nofollow'); ?>" <?php checked($instance['nofollow'], true); ?> /> <label for="<?php echo $this->get_field_id('nofollow'); ?>"><?php _e('Add nofollow attribute to the link?', 'dp'); ?></label> </p> <h4><?php _e('or Ad Code','dp'); ?></h4> <p> <label for="<?php echo $this->get_field_id('code'); ?>"><?php _e('Ad code:','dp'); ?></label> <textarea name="<?php echo $this->get_field_name('code'); ?>" rows="10" class="widefat" id="<?php echo $this->get_field_id('code'); ?>"><?php echo $instance['code']; ?></textarea> </p> <?php } } // Register Widget add_action('widgets_init', 'register_dp_widget_ad'); function register_dp_widget_ad() { register_widget('DP_Widget_Ad'); } ?>
gpl-2.0
md-5/jdk10
test/jdk/jdk/jfr/api/consumer/recordingstream/TestSetMaxSize.java
2168
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.consumer.recordingstream; import jdk.jfr.consumer.RecordingStream; import jdk.test.lib.jfr.EventNames; /** * @test * @summary Tests RecordingStrream::setMaxSize * @key jfr * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.api.consumer.recordingstream.TestSetMaxSize */ public class TestSetMaxSize { public static void main(String... args) throws Exception { long testSize = 123456789; try (RecordingStream r = new RecordingStream()) { r.setMaxSize(123456789); r.enable(EventNames.ActiveRecording); r.onEvent(e -> { System.out.println(e); long size= e.getLong("maxSize"); if (size == testSize) { r.close(); return; } System.out.println("Max size not set, was " + size + ", but expected " + testSize); }); r.start(); } } }
gpl-2.0
glaudiston/project-bianca
arduino/code/myrobotlab-1.0.119/src/org/myrobotlab/framework/repo/Dependency.java
1355
package org.myrobotlab.framework.repo; import java.io.Serializable; import java.util.Comparator; public class Dependency implements Serializable, Comparator<Dependency> { private static final long serialVersionUID = 1L; private String org; private String revision; private boolean installed = false; public Dependency() { this(null, null, true); } public Dependency(String organisation, String version) { this.org = organisation; this.revision = version; } public Dependency(String organisation, String version, boolean released) { this.org = organisation; this.revision = version; } @Override public int compare(Dependency o1, Dependency o2) { return o1.getOrg().compareTo(o2.getOrg()); } public String getModule() { if (org == null) { return null; } int p = org.lastIndexOf("."); if (p == -1) { return org; } else { return org.substring(p + 1); } } public String getOrg() { return org; } public String getRevision() { return revision; } public boolean isInstalled() { return installed; } public boolean isResolved() { return installed; } public void setResolved(boolean b) { installed = b; } public void setRevision(String revision2) { revision = revision2; } @Override public String toString() { return String.format("%s %s %b", org, revision, installed); } }
gpl-2.0
ThibautShr/ScrumBoard
client/components/auth/user.service.js
391
'use strict'; angular.module('scrumBoardApp') .factory('User', function ($resource) { return $resource('/api/users/:id/:controller', { id: '@_id' }, { changePassword: { method: 'PUT', params: { controller:'password' } }, get: { method: 'GET', params: { id:'me' } } }); });
gpl-2.0
ThomasXBMC/XCSoar
src/Dialogs/Settings/Panels/SiteConfigPanel.cpp
4803
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2015 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Profile/ProfileKeys.hpp" #include "Language/Language.hpp" #include "Dialogs/Dialogs.h" #include "LocalPath.hpp" #include "UtilsSettings.hpp" #include "ConfigPanel.hpp" #include "SiteConfigPanel.hpp" #include "Widget/RowFormWidget.hpp" #include "UIGlobals.hpp" #include "Waypoint/Patterns.hpp" #include "Form/DataField/File.hpp" enum ControlIndex { DataPath, MapFile, WaypointFile, AdditionalWaypointFile, WatchedWaypointFile, AirspaceFile, AdditionalAirspaceFile, AirfieldFile }; class SiteConfigPanel final : public RowFormWidget { enum Buttons { WAYPOINT_EDITOR, }; public: SiteConfigPanel() :RowFormWidget(UIGlobals::GetDialogLook()) {} public: virtual void Prepare(ContainerWindow &parent, const PixelRect &rc) override; virtual bool Save(bool &changed) override; }; void SiteConfigPanel::Prepare(ContainerWindow &parent, const PixelRect &rc) { WndProperty *wp = Add(_T(""), 0, true); wp->SetText(GetPrimaryDataPath()); wp->SetEnabled(false); AddFile(_("Map database"), _("The name of the file (.xcm) containing terrain, topography, and optionally " "waypoints, their details and airspaces."), ProfileKeys::MapFile, _T("*.xcm\0*.lkm\0"), FileType::MAP); AddFile(_("Waypoints"), _("Primary waypoints file. Supported file types are Cambridge/WinPilot files (.dat), " "Zander files (.wpz) or SeeYou files (.cup)."), ProfileKeys::WaypointFile, WAYPOINT_FILE_PATTERNS, FileType::WAYPOINT); AddFile(_("More waypoints"), _("Secondary waypoints file. This may be used to add waypoints for a competition."), ProfileKeys::AdditionalWaypointFile, WAYPOINT_FILE_PATTERNS, FileType::WAYPOINT); SetExpertRow(AdditionalWaypointFile); AddFile(_("Watched waypoints"), _("Waypoint file containing special waypoints for which additional computations like " "calculation of arrival height in map display always takes place. Useful for " "waypoints like known reliable thermal sources (e.g. powerplants) or mountain passes."), ProfileKeys::WatchedWaypointFile, WAYPOINT_FILE_PATTERNS, FileType::WAYPOINT); SetExpertRow(WatchedWaypointFile); AddFile(_("Airspaces"), _("The file name of the primary airspace file."), ProfileKeys::AirspaceFile, _T("*.txt\0*.air\0*.sua\0"), FileType::AIRSPACE); AddFile(_("More airspaces"), _("The file name of the secondary airspace file."), ProfileKeys::AdditionalAirspaceFile, _T("*.txt\0*.air\0*.sua\0"), FileType::AIRSPACE); SetExpertRow(AdditionalAirspaceFile); AddFile(_("Waypoint details"), _("The file may contain extracts from enroute supplements or other contributed " "information about individual waypoints and airfields."), ProfileKeys::AirfieldFile, _T("*.txt\0")); SetExpertRow(AirfieldFile); } bool SiteConfigPanel::Save(bool &_changed) { bool changed = false; MapFileChanged = SaveValueFileReader(MapFile, ProfileKeys::MapFile); // WaypointFileChanged has already a meaningful value WaypointFileChanged |= SaveValueFileReader(WaypointFile, ProfileKeys::WaypointFile); WaypointFileChanged |= SaveValueFileReader(AdditionalWaypointFile, ProfileKeys::AdditionalWaypointFile); WaypointFileChanged |= SaveValueFileReader(WatchedWaypointFile, ProfileKeys::WatchedWaypointFile); AirspaceFileChanged = SaveValueFileReader(AirspaceFile, ProfileKeys::AirspaceFile); AirspaceFileChanged |= SaveValueFileReader(AdditionalAirspaceFile, ProfileKeys::AdditionalAirspaceFile); AirfieldFileChanged = SaveValueFileReader(AirfieldFile, ProfileKeys::AirfieldFile); changed = WaypointFileChanged || AirfieldFileChanged || MapFileChanged; _changed |= changed; return true; } Widget * CreateSiteConfigPanel() { return new SiteConfigPanel(); }
gpl-2.0
cjk/biorder
cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java
2478
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova; import android.app.Activity; import android.content.Intent; import org.apache.cordova.CordovaPlugin; import java.util.concurrent.ExecutorService; /** * The Activity interface that is implemented by CordovaActivity. * It is used to isolate plugin development, and remove dependency on entire Cordova library. */ public interface CordovaInterface { /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ abstract public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode); /** * Set the plugin to be called when a sub-activity exits. * * @param plugin The plugin on which onActivityResult is to be called */ abstract public void setActivityResultCallback(CordovaPlugin plugin); /** * Get the Android activity. * * @return the Activity */ public abstract Activity getActivity(); /** * Called when a message is sent to plugin. * * @param id The message id * @param data The message data * @return Object or null */ public Object onMessage(String id, Object data); /** * Returns a shared thread pool that can be used for background tasks. */ public ExecutorService getThreadPool(); }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/rm/fxch_ST1_ST5.java
1778
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.rm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fxch_ST1_ST5 extends Executable { public fxch_ST1_ST5(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double tmp = cpu.fpu.ST(1); cpu.fpu.setST(1, cpu.fpu.ST(5)); cpu.fpu.setST(5, tmp); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
aarontropy/tkendall
wp-content/plugins/mailchimp-for-wp/mailchimp-for-wp.php
2248
<?php /* Plugin Name: MailChimp for WordPress Lite Plugin URI: https://mc4wp.com/ Description: Lite version of MailChimp for WordPress. Adds various sign-up methods to your website. Version: 2.1.2 Author: Danny van Kooten Author URI: http://dannyvankooten.com Text Domain: mailchimp-for-wp Domain Path: /languages License: GPL v3 MailChimp for WordPress Copyright (C) 2012-2013, Danny van Kooten, hi@dannyvankooten.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Prevent direct file access if( ! defined( 'ABSPATH' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit; } /** * Loads the MailChimp for WP plugin files * * @return boolean True if the plugin files were loaded, false otherwise. */ function mc4wp_load_plugin() { // don't load plugin if user has the premium version installed and activated if( defined( 'MC4WP_VERSION' ) ) { return false; } // bootstrap the lite plugin define( 'MC4WP_LITE_VERSION', '2.1.2' ); define( 'MC4WP_LITE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'MC4WP_LITE_PLUGIN_URL', plugins_url( '/' , __FILE__ ) ); define( 'MC4WP_LITE_PLUGIN_FILE', __FILE__ ); require_once MC4WP_LITE_PLUGIN_DIR . 'includes/functions/general.php'; require_once MC4WP_LITE_PLUGIN_DIR . 'includes/functions/template.php'; require_once MC4WP_LITE_PLUGIN_DIR . 'includes/class-plugin.php'; $GLOBALS['mc4wp'] = new MC4WP_Lite(); if( is_admin() && ( false === defined( 'DOING_AJAX' ) || false === DOING_AJAX ) ) { // ADMIN require_once MC4WP_LITE_PLUGIN_DIR . 'includes/class-admin.php'; new MC4WP_Lite_Admin(); } return true; } add_action( 'plugins_loaded', 'mc4wp_load_plugin', 20 );
gpl-2.0