text
stringlengths
2
1.04M
meta
dict
/** * Simulator process * Pokemon Showdown - http://pokemonshowdown.com/ * * This file is where the battle simulation itself happens. * * The most important part of the simulation happens in runEvent - * see that function's definition for details. * * @license MIT license */ 'use strict'; require('sugar'); global.Config = require('./config/config.js'); if (Config.crashguard) { // graceful crash - allow current battles to finish before restarting process.on('uncaughtException', err => { require('./crashlogger.js')(err, 'A simulator process'); /* let stack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); if (Rooms.lobby) { Rooms.lobby.addRaw('<div><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>'); Rooms.lobby.addRaw('<div>You will not be able to talk in the lobby or start new battles until the server restarts.</div>'); } Rooms.global.lockdown = true; */ }); } global.Tools = require('./tools.js').includeMods(); global.toId = Tools.getId; let Battle, BattleSide, BattlePokemon; let Battles = Object.create(null); require('./repl.js').start('battle-engine-', process.pid, cmd => eval(cmd)); // Receive and process a message sent using Simulator.prototype.send in // another process. process.on('message', message => { //console.log('CHILD MESSAGE RECV: "' + message + '"'); let nlIndex = message.indexOf("\n"); let more = ''; if (nlIndex > 0) { more = message.substr(nlIndex + 1); message = message.substr(0, nlIndex); } let data = message.split('|'); if (data[1] === 'init') { if (!Battles[data[0]]) { try { Battles[data[0]] = Battle.construct(data[0], data[2], data[3]); } catch (err) { if (require('./crashlogger.js')(err, 'A battle', { message: message, }) === 'lockdown') { let ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); process.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>A BATTLE PROCESS HAS CRASHED:</b> ' + ministack + '</div>'); } else { process.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>The battle crashed!</b><br />Don\'t worry, we\'re working on fixing it.</div>'); } } } } else if (data[1] === 'dealloc') { if (Battles[data[0]] && Battles[data[0]].destroy) { Battles[data[0]].destroy(); } else { require('./crashlogger.js')(new Error("Invalid dealloc"), 'A battle', { message: message, }); } delete Battles[data[0]]; } else { let battle = Battles[data[0]]; if (battle) { let prevRequest = battle.currentRequest; let prevRequestDetails = battle.currentRequestDetails || ''; try { battle.receive(data, more); } catch (err) { require('./crashlogger.js')(err, 'A battle', { message: message, currentRequest: prevRequest, log: '\n' + battle.log.join('\n').replace(/\n\|split\n[^\n]*\n[^\n]*\n[^\n]*\n/g, '\n'), }); let logPos = battle.log.length; battle.add('html', '<div class="broadcast-red"><b>The battle crashed</b><br />You can keep playing but it might crash again.</div>'); let nestedError; try { battle.makeRequest(prevRequest, prevRequestDetails); } catch (e) { nestedError = e; } battle.sendUpdates(logPos); if (nestedError) { throw nestedError; } } } else if (data[1] === 'eval') { try { eval(data[2]); } catch (e) {} } } }); process.on('disconnect', () => { process.exit(); }); BattlePokemon = (() => { function BattlePokemon(set, side) { this.side = side; this.battle = side.battle; let pokemonScripts = this.battle.data.Scripts.pokemon; if (pokemonScripts) Object.merge(this, pokemonScripts); if (typeof set === 'string') set = {name: set}; // "pre-bound" functions for nicer syntax (avoids repeated use of `bind`) this.getHealth = (this.getHealth || BattlePokemon.getHealth).bind(this); this.getDetails = (this.getDetails || BattlePokemon.getDetails).bind(this); this.set = set; this.baseTemplate = this.battle.getTemplate(set.species || set.name); if (!this.baseTemplate.exists) { this.battle.debug('Unidentified species: ' + this.species); this.baseTemplate = this.battle.getTemplate('Unown'); } this.species = this.baseTemplate.species; if (set.name === set.species || !set.name) { set.name = this.baseTemplate.baseSpecies; } this.name = set.name.substr(0, 20); this.speciesid = toId(this.species); this.template = this.baseTemplate; this.moves = []; this.baseMoves = this.moves; this.movepp = {}; this.moveset = []; this.baseMoveset = []; this.level = this.battle.clampIntRange(set.forcedLevel || set.level || 100, 1, 9999); let genders = {M:'M', F:'F', N:'N'}; this.gender = genders[set.gender] || this.template.gender || (Math.random() * 2 < 1 ? 'M' : 'F'); if (this.gender === 'N') this.gender = ''; this.happiness = typeof set.happiness === 'number' ? this.battle.clampIntRange(set.happiness, 0, 255) : 255; this.pokeball = this.set.pokeball || 'pokeball'; this.fullname = this.side.id + ': ' + this.name; this.details = this.species + (this.level === 100 ? '' : ', L' + this.level) + (this.gender === '' ? '' : ', ' + this.gender) + (this.set.shiny ? ', shiny' : ''); this.id = this.fullname; // shouldn't really be used anywhere this.statusData = {}; this.volatiles = {}; this.height = this.template.height; this.heightm = this.template.heightm; this.weight = this.template.weight; this.weightkg = this.template.weightkg; this.baseAbility = toId(set.ability); this.ability = this.baseAbility; this.item = toId(set.item); this.abilityData = {id: this.ability}; this.itemData = {id: this.item}; this.speciesData = {id: this.speciesid}; this.types = this.baseTemplate.types; this.addedType = ''; if (this.set.moves) { for (let i = 0; i < this.set.moves.length; i++) { let move = this.battle.getMove(this.set.moves[i]); if (!move.id) continue; if (move.id === 'hiddenpower' && move.type !== 'Normal') { if (this.battle.gen && this.battle.gen <= 2) { if (!this.set.ivs || Math.min.apply(Math, Object.values(this.set.ivs)) >= 30) { let HPdvs = this.battle.getType(move.type).HPdvs; this.set.ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30}; for (let i in HPdvs) { this.set.ivs[i] = HPdvs[i] * 2; } } } else { if (!this.set.ivs || Object.values(this.set.ivs).every(31)) { this.set.ivs = this.battle.getType(move.type).HPivs; } } move = this.battle.getMove('hiddenpower'); } this.baseMoveset.push({ move: move.name, id: move.id, pp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), maxpp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), target: move.target, disabled: false, disabledSource: '', used: false, }); this.moves.push(move.id); } } this.canMegaEvo = this.battle.canMegaEvo(this); if (!this.set.evs) { this.set.evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0}; } if (!this.set.ivs) { this.set.ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31}; } let stats = {hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31}; for (let i in stats) { if (!this.set.evs[i]) this.set.evs[i] = 0; if (!this.set.ivs[i] && this.set.ivs[i] !== 0) this.set.ivs[i] = 31; } for (let i in this.set.evs) { this.set.evs[i] = this.battle.clampIntRange(this.set.evs[i], 0, 255); } for (let i in this.set.ivs) { this.set.ivs[i] = this.battle.clampIntRange(this.set.ivs[i], 0, 31); } if (this.battle.gen && this.battle.gen <= 2) { // We represent DVs using even IVs. Ensure they are in fact even. for (let i in this.set.ivs) { this.set.ivs[i] &= 30; } } let hpTypes = ['Fighting', 'Flying', 'Poison', 'Ground', 'Rock', 'Bug', 'Ghost', 'Steel', 'Fire', 'Water', 'Grass', 'Electric', 'Psychic', 'Ice', 'Dragon', 'Dark']; if (this.battle.gen && this.battle.gen === 2) { // Gen 2 specific Hidden Power check. IVs are still treated 0-31 so we get them 0-15 let atkDV = Math.floor(this.set.ivs.atk / 2); let defDV = Math.floor(this.set.ivs.def / 2); let speDV = Math.floor(this.set.ivs.spe / 2); let spcDV = Math.floor(this.set.ivs.spa / 2); this.hpType = hpTypes[4 * (atkDV % 4) + (defDV % 4)]; this.hpPower = Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV > 2 ? 3 : spcDV)) / 2 + 31); } else { // Hidden Power check for gen 3 onwards let hpTypeX = 0, hpPowerX = 0; let i = 1; for (let s in stats) { hpTypeX += i * (this.set.ivs[s] % 2); hpPowerX += i * (Math.floor(this.set.ivs[s] / 2) % 2); i *= 2; } this.hpType = hpTypes[Math.floor(hpTypeX * 15 / 63)]; // In Gen 6, Hidden Power is always 60 base power this.hpPower = (this.battle.gen && this.battle.gen < 6) ? Math.floor(hpPowerX * 40 / 63) + 30 : 60; } this.boosts = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0}; this.stats = {atk:0, def:0, spa:0, spd:0, spe:0}; this.baseStats = {atk:10, def:10, spa:10, spd:10, spe:10}; // This is used in gen 1 only, here to avoid code repetition. // Only declared if gen 1 to avoid declaring an object we aren't going to need. if (this.battle.gen === 1) this.modifiedStats = {atk:0, def:0, spa:0, spd:0, spe:0}; for (let statName in this.baseStats) { let stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); let nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = Math.floor(stat); } this.maxhp = Math.floor(Math.floor(2 * this.template.baseStats['hp'] + this.set.ivs['hp'] + Math.floor(this.set.evs['hp'] / 4) + 100) * this.level / 100 + 10); if (this.template.baseStats['hp'] === 1) this.maxhp = 1; // shedinja this.hp = this.hp || this.maxhp; this.isStale = 0; this.isStaleCon = 0; this.isStaleHP = this.maxhp; this.isStalePPTurns = 0; // Transform copies IVs in gen 4 and earlier, so we track the base IVs/HP-type/power this.baseIvs = this.set.ivs; this.baseHpType = this.hpType; this.baseHpPower = this.hpPower; this.clearVolatile(true); } BattlePokemon.prototype.trapped = false; BattlePokemon.prototype.maybeTrapped = false; BattlePokemon.prototype.maybeDisabled = false; BattlePokemon.prototype.hp = 0; BattlePokemon.prototype.maxhp = 100; BattlePokemon.prototype.illusion = null; BattlePokemon.prototype.fainted = false; BattlePokemon.prototype.faintQueued = false; BattlePokemon.prototype.lastItem = ''; BattlePokemon.prototype.ateBerry = false; BattlePokemon.prototype.status = ''; BattlePokemon.prototype.position = 0; BattlePokemon.prototype.lastMove = ''; BattlePokemon.prototype.moveThisTurn = ''; BattlePokemon.prototype.lastDamage = 0; BattlePokemon.prototype.lastAttackedBy = null; BattlePokemon.prototype.usedItemThisTurn = false; BattlePokemon.prototype.newlySwitched = false; BattlePokemon.prototype.beingCalledBack = false; BattlePokemon.prototype.isActive = false; BattlePokemon.prototype.isStarted = false; // has this pokemon's Start events run yet? BattlePokemon.prototype.transformed = false; BattlePokemon.prototype.duringMove = false; BattlePokemon.prototype.hpType = 'Dark'; BattlePokemon.prototype.hpPower = 60; BattlePokemon.prototype.speed = 0; BattlePokemon.prototype.abilityOrder = 0; BattlePokemon.prototype.toString = function () { let fullname = this.fullname; if (this.illusion) fullname = this.illusion.fullname; let positionList = 'abcdef'; if (this.isActive) return fullname.substr(0, 2) + positionList[this.position] + fullname.substr(2); return fullname; }; // "static" function BattlePokemon.getDetails = function (side) { if (this.illusion) return this.illusion.details + '|' + this.getHealth(side); return this.details + '|' + this.getHealth(side); }; BattlePokemon.prototype.updateSpeed = function () { this.speed = this.getDecisionSpeed(); }; BattlePokemon.prototype.calculateStat = function (statName, boost, modifier) { statName = toId(statName); if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat let stat = this.stats[statName]; // stat boosts // boost = this.boosts[statName]; let boosts = {}; boosts[statName] = boost; boosts = this.battle.runEvent('ModifyBoost', this, null, null, boosts); boost = boosts[statName]; let boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } // stat modifier stat = this.battle.modify(stat, (modifier || 1)); if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this); } return stat; }; BattlePokemon.prototype.getStat = function (statName, unboosted, unmodified) { statName = toId(statName); if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat let stat = this.stats[statName]; // stat boosts if (!unboosted) { let boosts = this.battle.runEvent('ModifyBoost', this, null, null, Object.clone(this.boosts)); let boost = boosts[statName]; let boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } } // stat modifier effects if (!unmodified) { let statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; stat = this.battle.runEvent('Modify' + statTable[statName], this, null, null, stat); } if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this, unboosted); } return stat; }; BattlePokemon.prototype.getDecisionSpeed = function () { let speed = this.getStat('spe'); if (speed > 10000) speed = 10000; if (this.battle.getPseudoWeather('trickroom')) { speed = 0x2710 - speed; } return speed & 0x1FFF; }; BattlePokemon.prototype.getWeight = function () { let weight = this.template.weightkg; weight = this.battle.runEvent('ModifyWeight', this, null, null, weight); if (weight < 0.1) weight = 0.1; return weight; }; BattlePokemon.prototype.getMoveData = function (move) { move = this.battle.getMove(move); for (let i = 0; i < this.moveset.length; i++) { let moveData = this.moveset[i]; if (moveData.id === move.id) { return moveData; } } return null; }; BattlePokemon.prototype.getMoveTargets = function (move, target) { let targets = []; switch (move.target) { case 'all': case 'foeSide': case 'allySide': case 'allyTeam': if (!move.target.startsWith('foe')) { for (let i = 0; i < this.side.active.length; i++) { if (!this.side.active[i].fainted) { targets.push(this.side.active[i]); } } } if (!move.target.startsWith('ally')) { for (let i = 0; i < this.side.foe.active.length; i++) { if (!this.side.foe.active[i].fainted) { targets.push(this.side.foe.active[i]); } } } break; case 'allAdjacent': case 'allAdjacentFoes': if (move.target === 'allAdjacent') { for (let i = 0; i < this.side.active.length; i++) { if (this.battle.isAdjacent(this, this.side.active[i])) { targets.push(this.side.active[i]); } } } for (let i = 0; i < this.side.foe.active.length; i++) { if (this.battle.isAdjacent(this, this.side.foe.active[i])) { targets.push(this.side.foe.active[i]); } } break; default: if (!target || (target.fainted && target.side !== this.side)) { // If a targeted foe faints, the move is retargeted target = this.battle.resolveTarget(this, move); } if (target.side.active.length > 1) { target = this.battle.priorityEvent('RedirectTarget', this, this, move, target); } targets = [target]; // Resolve apparent targets for Pressure. if (move.pressureTarget) { // At the moment, this is the only supported target. if (move.pressureTarget === 'foeSide') { for (let i = 0; i < this.side.foe.active.length; i++) { if (this.side.foe.active[i] && !this.side.foe.active[i].fainted) { targets.push(this.side.foe.active[i]); } } } } } return targets; }; BattlePokemon.prototype.ignoringAbility = function () { return !!((this.battle.gen >= 5 && !this.isActive) || this.volatiles['gastroacid']); }; BattlePokemon.prototype.ignoringItem = function () { return !!((this.battle.gen >= 5 && !this.isActive) || this.hasAbility('klutz') || this.volatiles['embargo'] || this.battle.pseudoWeather['magicroom']); }; BattlePokemon.prototype.deductPP = function (move, amount, source) { move = this.battle.getMove(move); let ppData = this.getMoveData(move); if (!ppData) return false; ppData.used = true; if (!ppData.pp) return false; ppData.pp -= amount || 1; if (ppData.pp <= 0) { ppData.pp = 0; } if (ppData.virtual) { let foeActive = this.side.foe.active; for (let i = 0; i < foeActive.length; i++) { if (foeActive[i].isStale >= 2) { if (move.selfSwitch) this.isStalePPTurns++; return true; } } } this.isStalePPTurns = 0; return true; }; BattlePokemon.prototype.moveUsed = function (move) { this.lastMove = this.battle.getMove(move).id; this.moveThisTurn = this.lastMove; }; BattlePokemon.prototype.gotAttacked = function (move, damage, source) { if (!damage) damage = 0; move = this.battle.getMove(move); this.lastAttackedBy = { pokemon: source, damage: damage, move: move.id, thisTurn: true, }; }; BattlePokemon.prototype.getLockedMove = function () { let lockedMove = this.battle.runEvent('LockMove', this); if (lockedMove === true) lockedMove = false; return lockedMove; }; BattlePokemon.prototype.getMoves = function (lockedMove, restrictData) { if (lockedMove) { lockedMove = toId(lockedMove); this.trapped = true; if (lockedMove === 'recharge') { return [{ move: 'Recharge', id: 'recharge', }]; } for (let i = 0; i < this.moveset.length; i++) { let moveEntry = this.moveset[i]; if (moveEntry.id !== lockedMove) continue; return [{ move: moveEntry.move, id: moveEntry.id, }]; } // does this happen? return [{ move: this.battle.getMove(lockedMove).name, id: lockedMove, }]; } let moves = []; let hasValidMove = false; for (let i = 0; i < this.moveset.length; i++) { let moveEntry = this.moveset[i]; let disabled = moveEntry.disabled; if (disabled === 'hidden' && restrictData) { disabled = false; } else if (moveEntry.pp <= 0) { disabled = true; } if (!disabled) { hasValidMove = true; } let moveName = moveEntry.move; if (moveEntry.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; if (this.battle.gen < 6) moveName += ' ' + this.hpPower; } let target = moveEntry.target; if (moveEntry.id === 'curse') { if (!this.hasType('Ghost')) { target = this.battle.getMove('curse').nonGhostTarget || moveEntry.target; } } moves.push({ move: moveName, id: moveEntry.id, pp: moveEntry.pp, maxpp: moveEntry.maxpp, target: target, disabled: disabled, }); } if (hasValidMove) return moves; return []; }; BattlePokemon.prototype.getRequestData = function () { let lockedMove = this.getLockedMove(); // Information should be restricted for the last active Pokémon let isLastActive = this.isLastActive(); let moves = this.getMoves(lockedMove, isLastActive); let data = {moves: moves.length ? moves : [{move: 'Struggle', id: 'struggle'}]}; if (isLastActive) { if (this.maybeDisabled) { data.maybeDisabled = true; } if (this.trapped === true) { data.trapped = true; } else if (this.maybeTrapped) { data.maybeTrapped = true; } } else { if (this.trapped) data.trapped = true; } if (this.canMegaEvo && !lockedMove) data.canMegaEvo = true; return data; }; BattlePokemon.prototype.isLastActive = function () { if (!this.isActive) return false; let allyActive = this.side.active; for (let i = this.position + 1; i < allyActive.length; i++) { if (allyActive[i] && !allyActive.fainted) return false; } return true; }; BattlePokemon.prototype.positiveBoosts = function () { let boosts = 0; for (let i in this.boosts) { if (this.boosts[i] > 0) boosts += this.boosts[i]; } return boosts; }; BattlePokemon.prototype.boostBy = function (boost) { let changed = false; for (let i in boost) { let delta = boost[i]; this.boosts[i] += delta; if (this.boosts[i] > 6) { delta -= this.boosts[i] - 6; this.boosts[i] = 6; } if (this.boosts[i] < -6) { delta -= this.boosts[i] - (-6); this.boosts[i] = -6; } if (delta) changed = true; } return changed; }; BattlePokemon.prototype.clearBoosts = function () { for (let i in this.boosts) { this.boosts[i] = 0; } }; BattlePokemon.prototype.setBoost = function (boost) { for (let i in boost) { this.boosts[i] = boost[i]; } }; BattlePokemon.prototype.copyVolatileFrom = function (pokemon) { this.clearVolatile(); this.boosts = pokemon.boosts; for (let i in pokemon.volatiles) { if (this.battle.getEffect(i).noCopy) continue; // shallow clones this.volatiles[i] = Object.clone(pokemon.volatiles[i]); if (this.volatiles[i].linkedPokemon) { delete pokemon.volatiles[i].linkedPokemon; delete pokemon.volatiles[i].linkedStatus; this.volatiles[i].linkedPokemon.volatiles[this.volatiles[i].linkedStatus].linkedPokemon = this; } } pokemon.clearVolatile(); for (let i in this.volatiles) { this.battle.singleEvent('Copy', this.getVolatile(i), this.volatiles[i], this); } }; BattlePokemon.prototype.transformInto = function (pokemon, user, effect) { let template = pokemon.template; if (pokemon.fainted || pokemon.illusion || (pokemon.volatiles['substitute'] && this.battle.gen >= 5)) { return false; } if (!template.abilities || (pokemon && pokemon.transformed && this.battle.gen >= 2) || (user && user.transformed && this.battle.gen >= 5)) { return false; } if (!this.formeChange(template, true)) { return false; } this.transformed = true; this.types = pokemon.types; this.addedType = pokemon.addedType; for (let statName in this.stats) { this.stats[statName] = pokemon.stats[statName]; } this.moveset = []; this.moves = []; this.set.ivs = (this.battle.gen >= 5 ? this.set.ivs : pokemon.set.ivs); this.hpType = (this.battle.gen >= 5 ? this.hpType : pokemon.hpType); this.hpPower = (this.battle.gen >= 5 ? this.hpPower : pokemon.hpPower); for (let i = 0; i < pokemon.moveset.length; i++) { let moveData = pokemon.moveset[i]; let moveName = moveData.move; if (moveData.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; } this.moveset.push({ move: moveName, id: moveData.id, pp: moveData.maxpp === 1 ? 1 : 5, maxpp: this.battle.gen >= 5 ? (moveData.maxpp === 1 ? 1 : 5) : moveData.maxpp, target: moveData.target, disabled: false, used: false, virtual: true, }); this.moves.push(toId(moveName)); } for (let j in pokemon.boosts) { this.boosts[j] = pokemon.boosts[j]; } if (effect) { this.battle.add('-transform', this, pokemon, '[from] ' + effect.fullname); } else { this.battle.add('-transform', this, pokemon); } this.setAbility(pokemon.ability); // Change formes based on held items (for Transform) // Only ever relevant in Generation 4 since Generation 3 didn't have item-based forme changes if (this.battle.gen === 4) { if (this.template.num === 487) { // Giratina formes if (this.template.species === 'Giratina' && this.item === 'griseousorb') { this.formeChange('Giratina-Origin'); this.battle.add('-formechange', this, 'Giratina-Origin'); } else if (this.template.species === 'Giratina-Origin' && this.item !== 'griseousorb') { this.formeChange('Giratina'); this.battle.add('-formechange', this, 'Giratina'); } } if (this.template.num === 493) { // Arceus formes let item = Tools.getItem(this.item); let targetForme = (item && item.onPlate ? 'Arceus-' + item.onPlate : 'Arceus'); if (this.template.species !== targetForme) { this.formeChange(targetForme); this.battle.add('-formechange', this, targetForme); } } } return true; }; BattlePokemon.prototype.formeChange = function (template, dontRecalculateStats) { template = this.battle.getTemplate(template); if (!template.abilities) return false; this.illusion = null; this.template = template; this.types = template.types; this.addedType = ''; if (!dontRecalculateStats) { for (let statName in this.stats) { let stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); // nature let nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = this.stats[statName] = Math.floor(stat); // If gen 1, we reset modified stats. if (this.battle.gen === 1) { this.modifiedStats[statName] = Math.floor(stat); // ...and here is where the gen 1 games re-apply burn and para drops. if (this.status === 'par' && statName === 'spe') this.modifyStat('spe', 0.25); if (this.status === 'brn' && statName === 'atk') this.modifyStat('atk', 0.5); } } this.speed = this.stats.spe; } return true; }; BattlePokemon.prototype.clearVolatile = function (init) { this.boosts = { atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0, }; if (this.battle.gen === 1 && this.baseMoves.indexOf('mimic') >= 0 && !this.transformed) { let moveslot = this.baseMoves.indexOf('mimic'); let mimicPP = this.moveset[moveslot] ? this.moveset[moveslot].pp : 16; this.moveset = this.baseMoveset.slice(); this.moveset[moveslot].pp = mimicPP; } else { this.moveset = this.baseMoveset.slice(); } this.moves = this.moveset.map(move => toId(move.move)); this.transformed = false; this.ability = this.baseAbility; this.set.ivs = this.baseIvs; this.hpType = this.baseHpType; this.hpPower = this.baseHpPower; for (let i in this.volatiles) { if (this.volatiles[i].linkedStatus) { this.volatiles[i].linkedPokemon.removeVolatile(this.volatiles[i].linkedStatus); } } this.volatiles = {}; this.switchFlag = false; this.lastMove = ''; this.moveThisTurn = ''; this.lastDamage = 0; this.lastAttackedBy = null; this.newlySwitched = true; this.beingCalledBack = false; this.formeChange(this.baseTemplate); }; BattlePokemon.prototype.hasType = function (type) { if (!type) return false; if (Array.isArray(type)) { for (let i = 0; i < type.length; i++) { if (this.hasType(type[i])) return true; } } else { if (this.getTypes().indexOf(type) >= 0) return true; } return false; }; // returns the amount of damage actually dealt BattlePokemon.prototype.faint = function (source, effect) { // This function only puts the pokemon in the faint queue; // actually setting of this.fainted comes later when the // faint queue is resolved. if (this.fainted || this.faintQueued) return 0; let d = this.hp; this.hp = 0; this.switchFlag = false; this.faintQueued = true; this.battle.faintQueue.push({ target: this, source: source, effect: effect, }); return d; }; BattlePokemon.prototype.damage = function (d, source, effect) { if (!this.hp) return 0; if (d < 1 && d > 0) d = 1; d = Math.floor(d); if (isNaN(d)) return 0; if (d <= 0) return 0; this.hp -= d; if (this.hp <= 0) { d += this.hp; this.faint(source, effect); } return d; }; BattlePokemon.prototype.tryTrap = function (isHidden) { if (this.runStatusImmunity('trapped')) { if (this.trapped && isHidden) return true; this.trapped = isHidden ? 'hidden' : true; return true; } return false; }; BattlePokemon.prototype.hasMove = function (moveid) { moveid = toId(moveid); if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower'; for (let i = 0; i < this.moveset.length; i++) { if (moveid === this.battle.getMove(this.moveset[i].move).id) { return moveid; } } return false; }; BattlePokemon.prototype.disableMove = function (moveid, isHidden, sourceEffect) { if (!sourceEffect && this.battle.event) { sourceEffect = this.battle.effect; } moveid = toId(moveid); for (let move of this.moveset) { if (move.id === moveid && move.disabled !== true) { move.disabled = (isHidden || true); move.disabledSource = (sourceEffect ? sourceEffect.fullname : ''); break; } } }; // returns the amount of damage actually healed BattlePokemon.prototype.heal = function (d) { if (!this.hp) return false; d = Math.floor(d); if (isNaN(d)) return false; if (d <= 0) return false; if (this.hp >= this.maxhp) return false; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; // sets HP, returns delta BattlePokemon.prototype.sethp = function (d) { if (!this.hp) return 0; d = Math.floor(d); if (isNaN(d)) return; if (d < 1) d = 1; d = d - this.hp; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; BattlePokemon.prototype.trySetStatus = function (status, source, sourceEffect) { if (!this.hp) return false; if (this.status) return false; return this.setStatus(status, source, sourceEffect); }; BattlePokemon.prototype.cureStatus = function () { if (!this.hp) return false; // unlike clearStatus, gives cure message if (this.status) { this.battle.add('-curestatus', this, this.status); this.setStatus(''); } }; BattlePokemon.prototype.setStatus = function (status, source, sourceEffect, ignoreImmunities) { if (!this.hp) return false; status = this.battle.getEffect(status); if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (!ignoreImmunities && status.id) { // the game currently never ignores immunities if (!this.runStatusImmunity(status.id === 'tox' ? 'psn' : status.id)) { this.battle.debug('immune to status'); return false; } } if (this.status === status.id) return false; let prevStatus = this.status; let prevStatusData = this.statusData; if (status.id && !this.battle.runEvent('SetStatus', this, source, sourceEffect, status)) { this.battle.debug('set status [' + status.id + '] interrupted'); return false; } this.status = status.id; this.statusData = {id: status.id, target: this}; if (source) this.statusData.source = source; if (status.duration) { this.statusData.duration = status.duration; } if (status.durationCallback) { this.statusData.duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (status.id && !this.battle.singleEvent('Start', status, this.statusData, this, source, sourceEffect)) { this.battle.debug('status start [' + status.id + '] interrupted'); // cancel the setstatus this.status = prevStatus; this.statusData = prevStatusData; return false; } if (status.id && !this.battle.runEvent('AfterSetStatus', this, source, sourceEffect, status)) { return false; } return true; }; BattlePokemon.prototype.clearStatus = function () { // unlike cureStatus, does not give cure message return this.setStatus(''); }; BattlePokemon.prototype.getStatus = function () { return this.battle.getEffect(this.status); }; BattlePokemon.prototype.eatItem = function (item, source, sourceEffect) { if (!this.hp || !this.isActive) return false; if (!this.item) return false; let id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item) && this.battle.runEvent('EatItem', this, null, null, item)) { this.battle.add('-enditem', this, item, '[eat]'); this.battle.singleEvent('Eat', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.ateBerry = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.useItem = function (item, source, sourceEffect) { if (!this.isActive) return false; if (!this.item) return false; let id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item)) { switch (item.id) { case 'redcard': this.battle.add('-enditem', this, item, '[of] ' + source); break; default: if (!item.isGem) { this.battle.add('-enditem', this, item); } break; } this.battle.singleEvent('Use', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.takeItem = function (source) { if (!this.isActive) return false; if (!this.item) return false; if (!source) source = this; if (this.battle.gen === 4) { if (toId(this.ability) === 'multitype') return false; if (source && toId(source.ability) === 'multitype') return false; } let item = this.getItem(); if (this.battle.runEvent('TakeItem', this, source, null, item)) { this.item = ''; this.itemData = {id: '', target: this}; return item; } return false; }; BattlePokemon.prototype.setItem = function (item, source, effect) { if (!this.hp || !this.isActive) return false; item = this.battle.getItem(item); if (item.id === 'leppaberry') { this.isStale = 2; this.isStaleSource = 'getleppa'; } this.lastItem = this.item; this.item = item.id; this.itemData = {id: item.id, target: this}; if (item.id) { this.battle.singleEvent('Start', item, this.itemData, this, source, effect); } if (this.lastItem) this.usedItemThisTurn = true; return true; }; BattlePokemon.prototype.getItem = function () { return this.battle.getItem(this.item); }; BattlePokemon.prototype.hasItem = function (item) { if (this.ignoringItem()) return false; let ownItem = this.item; if (!Array.isArray(item)) { return ownItem === toId(item); } return (item.map(toId).indexOf(ownItem) >= 0); }; BattlePokemon.prototype.clearItem = function () { return this.setItem(''); }; BattlePokemon.prototype.setAbility = function (ability, source, effect, noForce) { if (!this.hp) return false; ability = this.battle.getAbility(ability); let oldAbility = this.ability; if (noForce && oldAbility === ability.id) { return false; } if (ability.id in {illusion:1, multitype:1, stancechange:1}) return false; if (oldAbility in {multitype:1, stancechange:1}) return false; this.battle.singleEvent('End', this.battle.getAbility(oldAbility), this.abilityData, this, source, effect); this.ability = ability.id; this.abilityData = {id: ability.id, target: this}; if (ability.id && this.battle.gen > 3) { this.battle.singleEvent('Start', ability, this.abilityData, this, source, effect); } this.abilityOrder = this.battle.abilityOrder++; return oldAbility; }; BattlePokemon.prototype.getAbility = function () { return this.battle.getAbility(this.ability); }; BattlePokemon.prototype.hasAbility = function (ability) { if (this.ignoringAbility()) return false; let ownAbility = this.ability; if (!Array.isArray(ability)) { return ownAbility === toId(ability); } return (ability.map(toId).indexOf(ownAbility) >= 0); }; BattlePokemon.prototype.clearAbility = function () { return this.setAbility(''); }; BattlePokemon.prototype.getNature = function () { return this.battle.getNature(this.set.nature); }; BattlePokemon.prototype.addVolatile = function (status, source, sourceEffect, linkedStatus) { let result; status = this.battle.getEffect(status); if (!this.hp && !status.affectsFainted) return false; if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (this.volatiles[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.volatiles[status.id], this, source, sourceEffect); } if (!this.runStatusImmunity(status.id)) return false; result = this.battle.runEvent('TryAddVolatile', this, source, sourceEffect, status); if (!result) { this.battle.debug('add volatile [' + status.id + '] interrupted'); return result; } this.volatiles[status.id] = {id: status.id}; this.volatiles[status.id].target = this; if (source) { this.volatiles[status.id].source = source; this.volatiles[status.id].sourcePosition = source.position; } if (sourceEffect) { this.volatiles[status.id].sourceEffect = sourceEffect; } if (status.duration) { this.volatiles[status.id].duration = status.duration; } if (status.durationCallback) { this.volatiles[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } result = this.battle.singleEvent('Start', status, this.volatiles[status.id], this, source, sourceEffect); if (!result) { // cancel delete this.volatiles[status.id]; return result; } if (linkedStatus && source && !source.volatiles[linkedStatus]) { source.addVolatile(linkedStatus, this, sourceEffect, status); source.volatiles[linkedStatus].linkedPokemon = this; source.volatiles[linkedStatus].linkedStatus = status; this.volatiles[status].linkedPokemon = source; this.volatiles[status].linkedStatus = linkedStatus; } return true; }; BattlePokemon.prototype.getVolatile = function (status) { status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return null; return status; }; BattlePokemon.prototype.removeVolatile = function (status) { if (!this.hp) return false; status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return false; this.battle.singleEvent('End', status, this.volatiles[status.id], this); let linkedPokemon = this.volatiles[status.id].linkedPokemon; let linkedStatus = this.volatiles[status.id].linkedStatus; delete this.volatiles[status.id]; if (linkedPokemon && linkedPokemon.volatiles[linkedStatus]) { linkedPokemon.removeVolatile(linkedStatus); } return true; }; // "static" function BattlePokemon.getHealth = function (side) { if (!this.hp) return '0 fnt'; let hpstring; if ((side === true) || (this.side === side) || this.battle.getFormat().debug || this.battle.reportExactHP) { hpstring = '' + this.hp + '/' + this.maxhp; } else { let ratio = this.hp / this.maxhp; if (this.battle.reportPercentages) { // HP Percentage Mod mechanics let percentage = Math.ceil(ratio * 100); if ((percentage === 100) && (ratio < 1.0)) { percentage = 99; } hpstring = '' + percentage + '/100'; } else { // In-game accurate pixel health mechanics let pixels = Math.floor(ratio * 48) || 1; hpstring = '' + pixels + '/48'; if ((pixels === 9) && (ratio > 0.2)) { hpstring += 'y'; // force yellow HP bar } else if ((pixels === 24) && (ratio > 0.5)) { hpstring += 'g'; // force green HP bar } } } if (this.status) hpstring += ' ' + this.status; return hpstring; }; BattlePokemon.prototype.setType = function (newType, enforce) { // Arceus first type cannot be normally changed if (!enforce && this.template.num === 493) return false; this.types = [newType]; this.addedType = ''; return true; }; BattlePokemon.prototype.addType = function (newType) { // removes any types added previously and adds another one this.addedType = newType; return true; }; BattlePokemon.prototype.getTypes = function (excludeAdded) { let types = this.types; if (!excludeAdded && this.addedType) { types = types.concat(this.addedType); } if ('roost' in this.volatiles) { types = types.filter(type => type !== 'Flying'); } if (types.length) return types; return [this.battle.gen >= 5 ? 'Normal' : '???']; }; BattlePokemon.prototype.isGrounded = function (negateImmunity) { if ('gravity' in this.battle.pseudoWeather) return true; if ('ingrain' in this.volatiles) return true; if ('smackdown' in this.volatiles) return true; let item = (this.ignoringItem() ? '' : this.item); if (item === 'ironball') return true; if (!negateImmunity && this.hasType('Flying')) return false; if (this.hasAbility('levitate') && !this.battle.suppressingAttackEvents()) return null; if ('magnetrise' in this.volatiles) return false; if ('telekinesis' in this.volatiles) return false; return item !== 'airballoon'; }; BattlePokemon.prototype.isSemiInvulnerable = function () { if (this.volatiles['fly'] || this.volatiles['bounce'] || this.volatiles['skydrop'] || this.volatiles['dive'] || this.volatiles['dig'] || this.volatiles['phantomforce'] || this.volatiles['shadowforce']) { return true; } for (let i = 0; i < this.side.foe.active.length; i++) { if (this.side.foe.active[i].volatiles['skydrop'] && this.side.foe.active[i].volatiles['skydrop'].source === this) { return true; } } return false; }; BattlePokemon.prototype.runEffectiveness = function (move) { let totalTypeMod = 0; let types = this.getTypes(); for (let i = 0; i < types.length; i++) { let typeMod = this.battle.getEffectiveness(move, types[i]); typeMod = this.battle.singleEvent('Effectiveness', move, null, types[i], move, null, typeMod); totalTypeMod += this.battle.runEvent('Effectiveness', this, types[i], move, typeMod); } return totalTypeMod; }; BattlePokemon.prototype.runImmunity = function (type, message) { if (!type || type === '???') { return true; } if (!(type in this.battle.data.TypeChart)) { if (type === 'Fairy' || type === 'Dark' || type === 'Steel') return true; throw new Error("Use runStatusImmunity for " + type); } if (this.fainted) { return false; } let isGrounded; let negateResult = this.battle.runEvent('NegateImmunity', this, type); if (type === 'Ground') { isGrounded = this.isGrounded(!negateResult); if (isGrounded === null) { if (message) { this.battle.add('-immune', this, '[msg]', '[from] ability: Levitate'); } return false; } } if (!negateResult) return true; if ((isGrounded === undefined && !this.battle.getImmunity(type, this)) || isGrounded === false) { if (message) { this.battle.add('-immune', this, '[msg]'); } return false; } return true; }; BattlePokemon.prototype.runStatusImmunity = function (type, message) { if (this.fainted) { return false; } if (!type) { return true; } if (!this.battle.getImmunity(type, this)) { this.battle.debug('natural status immunity'); if (message) { this.battle.add('-immune', this, '[msg]'); } return false; } let immunity = this.battle.runEvent('Immunity', this, null, null, type); if (!immunity) { this.battle.debug('artificial status immunity'); if (message && immunity !== null) { this.battle.add('-immune', this, '[msg]'); } return false; } return true; }; BattlePokemon.prototype.destroy = function () { // deallocate ourself // get rid of some possibly-circular references this.battle = null; this.side = null; }; return BattlePokemon; })(); BattleSide = (() => { function BattleSide(name, battle, n, team) { let sideScripts = battle.data.Scripts.side; if (sideScripts) Object.merge(this, sideScripts); this.getChoice = (this.getChoice || BattleSide.getChoice).bind(this); this.battle = battle; this.n = n; this.name = name; this.pokemon = []; this.active = [null]; this.sideConditions = {}; this.id = n ? 'p2' : 'p1'; switch (this.battle.gameType) { case 'doubles': this.active = [null, null]; break; case 'triples': case 'rotation': this.active = [null, null, null]; break; } this.team = this.battle.getTeam(this, team); for (let i = 0; i < this.team.length && i < 6; i++) { //console.log("NEW POKEMON: " + (this.team[i] ? this.team[i].name : '[unidentified]')); this.pokemon.push(new BattlePokemon(this.team[i], this)); } this.pokemonLeft = this.pokemon.length; for (let i = 0; i < this.pokemon.length; i++) { this.pokemon[i].position = i; } } BattleSide.getChoice = function (side) { if (side !== this && side !== true) return ''; return this.choice; }; BattleSide.prototype.isActive = false; BattleSide.prototype.pokemonLeft = 0; BattleSide.prototype.faintedLastTurn = false; BattleSide.prototype.faintedThisTurn = false; BattleSide.prototype.decision = null; BattleSide.prototype.foe = null; BattleSide.prototype.toString = function () { return this.id + ': ' + this.name; }; BattleSide.prototype.getData = function () { let data = { name: this.name, id: this.id, pokemon: [], }; for (let i = 0; i < this.pokemon.length; i++) { let pokemon = this.pokemon[i]; data.pokemon.push({ ident: pokemon.fullname, details: pokemon.details, condition: pokemon.getHealth(pokemon.side), active: (pokemon.position < pokemon.side.active.length), stats: { atk: pokemon.baseStats['atk'], def: pokemon.baseStats['def'], spa: pokemon.baseStats['spa'], spd: pokemon.baseStats['spd'], spe: pokemon.baseStats['spe'], }, moves: pokemon.moves.map(move => { if (move === 'hiddenpower') { return move + toId(pokemon.hpType) + (pokemon.hpPower === 70 ? '' : pokemon.hpPower); } return move; }), baseAbility: pokemon.baseAbility, item: pokemon.item, pokeball: pokemon.pokeball, }); } return data; }; BattleSide.prototype.randomActive = function () { let actives = this.active.filter(active => active && !active.fainted); if (!actives.length) return null; let i = Math.floor(Math.random() * actives.length); return actives[i]; }; BattleSide.prototype.addSideCondition = function (status, source, sourceEffect) { status = this.battle.getEffect(status); if (this.sideConditions[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.sideConditions[status.id], this, source, sourceEffect); } this.sideConditions[status.id] = {id: status.id}; this.sideConditions[status.id].target = this; if (source) { this.sideConditions[status.id].source = source; this.sideConditions[status.id].sourcePosition = source.position; } if (status.duration) { this.sideConditions[status.id].duration = status.duration; } if (status.durationCallback) { this.sideConditions[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (!this.battle.singleEvent('Start', status, this.sideConditions[status.id], this, source, sourceEffect)) { delete this.sideConditions[status.id]; return false; } return true; }; BattleSide.prototype.getSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return null; return status; }; BattleSide.prototype.removeSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return false; this.battle.singleEvent('End', status, this.sideConditions[status.id], this); delete this.sideConditions[status.id]; return true; }; BattleSide.prototype.send = function () { let parts = Array.prototype.slice.call(arguments); let sideUpdate = '|' + parts.map(part => { if (typeof part !== 'function') return part; return part(this); }).join('|'); this.battle.send('sideupdate', this.id + "\n" + sideUpdate); }; BattleSide.prototype.emitCallback = function () { this.battle.send('sideupdate', this.id + "\n|callback|" + Array.prototype.slice.call(arguments).join('|')); }; BattleSide.prototype.emitRequest = function (update) { this.battle.send('request', this.id + "\n" + this.battle.rqid + "\n" + JSON.stringify(update)); }; BattleSide.prototype.resolveDecision = function () { if (this.decision) { if (this.decision === true) this.choice = ''; return; } let decisions = []; switch (this.currentRequest) { case 'move': for (let i = 0; i < this.active.length; i++) { let pokemon = this.active[i]; if (!pokemon || pokemon.fainted) continue; let lockedMove = pokemon.getLockedMove(); if (lockedMove) { decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: this.battle.runEvent('LockMoveTarget', pokemon) || 0, move: lockedMove, }); continue; } let moveid = 'struggle'; let moves = pokemon.getMoves(); for (let j = 0; j < moves.length; j++) { if (moves[j].disabled) continue; moveid = moves[j].id; break; } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: 0, move: moveid, }); } break; case 'switch': { let canSwitchOut = []; for (let i = 0; i < this.active.length; i++) { if (this.active[i] && this.active[i].switchFlag) canSwitchOut.push(i); } let canSwitchIn = []; for (let i = this.active.length; i < this.pokemon.length; i++) { if (this.pokemon[i] && !this.pokemon[i].fainted) canSwitchIn.push(i); } let willPass = canSwitchOut.splice(Math.min(canSwitchOut.length, canSwitchIn.length)); for (let i = 0; i < canSwitchOut.length; i++) { decisions.push({ choice: this.foe.currentRequest === 'switch' ? 'instaswitch' : 'switch', pokemon: this.active[canSwitchOut[i]], target: this.pokemon[canSwitchIn[i]], }); } for (let i = 0; i < willPass.length; i++) { decisions.push({ choice: 'pass', pokemon: this.active[willPass[i]], priority: 102, }); } break; } case 'teampreview': decisions.push({ choice: 'team', side: this, team: [0, 1, 2, 3, 4, 5].slice(0, this.pokemon.length), }); } this.choice = ''; this.decision = decisions; }; BattleSide.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (let i = 0; i < this.pokemon.length; i++) { if (this.pokemon[i]) this.pokemon[i].destroy(); this.pokemon[i] = null; } this.pokemon = null; for (let i = 0; i < this.active.length; i++) { this.active[i] = null; } this.active = null; if (this.decision) { delete this.decision.side; delete this.decision.pokemon; } this.decision = null; // get rid of some possibly-circular references this.battle = null; this.foe = null; }; return BattleSide; })(); Battle = (() => { let Battle = {}; Battle.construct = (() => { let battleProtoCache = {}; return (roomid, formatarg, rated) => { let battle = Object.create((() => { if (battleProtoCache[formatarg] !== undefined) { return battleProtoCache[formatarg]; } // Scripts overrides Battle overrides Scripts overrides Tools let tools = Tools.mod(formatarg); let proto = Object.create(tools); for (let i in Battle.prototype) { proto[i] = Battle.prototype[i]; } let battle = Object.create(proto); tools.install(battle); return (battleProtoCache[formatarg] = battle); })()); Battle.prototype.init.call(battle, roomid, formatarg, rated); return battle; }; })(); Battle.logReplay = function (data, isReplay) { if (isReplay === true) return data; return ''; }; Battle.prototype = {}; Battle.prototype.init = function (roomid, formatarg, rated) { let format = Tools.getFormat(formatarg); this.log = []; this.sides = [null, null]; this.roomid = roomid; this.id = roomid; this.rated = rated; this.weatherData = {id:''}; this.terrainData = {id:''}; this.pseudoWeather = {}; this.format = toId(format); this.formatData = {id:this.format}; this.effect = {id:''}; this.effectData = {id:''}; this.event = {id:''}; this.gameType = (format.gameType || 'singles'); this.queue = []; this.faintQueue = []; this.messageLog = []; // use a random initial seed (64-bit, [high -> low]) this.startingSeed = this.seed = [ Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), ]; }; Battle.prototype.turn = 0; Battle.prototype.p1 = null; Battle.prototype.p2 = null; Battle.prototype.lastUpdate = 0; Battle.prototype.weather = ''; Battle.prototype.terrain = ''; Battle.prototype.ended = false; Battle.prototype.started = false; Battle.prototype.active = false; Battle.prototype.eventDepth = 0; Battle.prototype.lastMove = ''; Battle.prototype.activeMove = null; Battle.prototype.activePokemon = null; Battle.prototype.activeTarget = null; Battle.prototype.midTurn = false; Battle.prototype.currentRequest = ''; Battle.prototype.currentRequestDetails = ''; Battle.prototype.rqid = 0; Battle.prototype.lastMoveLine = 0; Battle.prototype.reportPercentages = false; Battle.prototype.supportCancel = false; Battle.prototype.events = null; Battle.prototype.abilityOrder = 0; Battle.prototype.toString = function () { return 'Battle: ' + this.format; }; // This function is designed to emulate the on-cartridge PRNG for Gens 3 and 4, as described in // http://www.smogon.com/ingame/rng/pid_iv_creation#pokemon_random_number_generator // This RNG uses a 32-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. /* Battle.prototype.random = function (m, n) { this.seed = (this.seed * 0x41C64E6D + 0x6073) >>> 0; // truncate the result to the last 32 bits let result = this.seed >>> 16; // the first 16 bits of the seed are the random value m = Math.floor(m); n = Math.floor(n); return (m ? (n ? (result % (n - m)) + m : result % m) : result / 0x10000); }; */ // This function is designed to emulate the on-cartridge PRNG for Gen 5 and uses a 64-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. Battle.prototype.random = function (m, n) { this.seed = this.nextFrame(); // Advance the RNG let result = (this.seed[0] << 16 >>> 0) + this.seed[1]; // Use the upper 32 bits m = Math.floor(m); n = Math.floor(n); result = (m ? (n ? Math.floor(result * (n - m) / 0x100000000) + m : Math.floor(result * m / 0x100000000)) : result / 0x100000000); this.debug('randBW(' + (m ? (n ? m + ', ' + n : m) : '') + ') = ' + result); return result; }; Battle.prototype.nextFrame = function (n) { let seed = this.seed; n = n || 1; for (let frame = 0; frame < n; ++frame) { // The RNG is a Linear Congruential Generator (LCG) in the form: x_{n + 1} = (a x_n + c) % m // Where: x_0 is the seed, x_n is the random number after n iterations, // a = 0x5D588B656C078965, c = 0x00269EC3 and m = 2^64 // Javascript doesnt handle such large numbers properly, so this function does it in 16-bit parts. // x_{n + 1} = (x_n * a) + c // Let any 64 bit number n = (n[0] << 48) + (n[1] << 32) + (n[2] << 16) + n[3] // Then x_{n + 1} = // ((a[3] x_n[0] + a[2] x_n[1] + a[1] x_n[2] + a[0] x_n[3] + c[0]) << 48) + // ((a[3] x_n[1] + a[2] x_n[2] + a[1] x_n[3] + c[1]) << 32) + // ((a[3] x_n[2] + a[2] x_n[3] + c[2]) << 16) + // a[3] x_n[3] + c[3] // Which can be generalised where b is the number of 16 bit words in the number: // (Notice how the a[] word starts at b-1, and decrements every time it appears again on the line; // x_n[] starts at b-<line#>-1 and increments to b-1 at the end of the line per line, limiting the length of the line; // c[] is at b-<line#>-1 for each line and the left shift is 16 * <line#>) // ((a[b-1] + x_n[b-1] + c[b-1]) << (16 * 0)) + // ((a[b-1] x_n[b-2] + a[b-2] x_n[b-1] + c[b-2]) << (16 * 1)) + // ((a[b-1] x_n[b-3] + a[b-2] x_n[b-2] + a[b-3] x_n[b-1] + c[b-3]) << (16 * 2)) + // ... // ((a[b-1] x_n[1] + a[b-2] x_n[2] + ... + a[2] x_n[b-2] + a[1] + x_n[b-1] + c[1]) << (16 * (b-2))) + // ((a[b-1] x_n[0] + a[b-2] x_n[1] + ... + a[1] x_n[b-2] + a[0] + x_n[b-1] + c[0]) << (16 * (b-1))) // Which produces this equation: \sum_{l=0}^{b-1}\left(\sum_{m=b-l-1}^{b-1}\left\{a[2b-m-l-2] x_n[m]\right\}+c[b-l-1]\ll16l\right) // This is all ignoring overflow/carry because that cannot be shown in a pseudo-mathematical equation. // The below code implements a optimised version of that equation while also checking for overflow/carry. let a = [0x5D58, 0x8B65, 0x6C07, 0x8965]; let c = [0, 0, 0x26, 0x9EC3]; let nextSeed = [0, 0, 0, 0]; let carry = 0; for (let cN = seed.length - 1; cN >= 0; --cN) { nextSeed[cN] = carry; carry = 0; let aN = seed.length - 1; let seedN = cN; for (; seedN < seed.length; --aN, ++seedN) { let nextWord = a[aN] * seed[seedN]; carry += nextWord >>> 16; nextSeed[cN] += nextWord & 0xFFFF; } nextSeed[cN] += c[cN]; carry += nextSeed[cN] >>> 16; nextSeed[cN] &= 0xFFFF; } seed = nextSeed; } return seed; }; Battle.prototype.setWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.weather === status.id && (this.gen > 2 || status.id === 'sandstorm')) { return false; } if (status.id) { let result = this.runEvent('SetWeather', source, source, status); if (!result) { if (result === false) { if (sourceEffect && sourceEffect.weather) { this.add('-fail', source, sourceEffect, '[from]: ' + this.weather); } else if (sourceEffect && sourceEffect.effectType === 'Ability') { this.add('-ability', source, sourceEffect, '[from] ' + this.weather, '[fail]'); } } return null; } } if (this.weather && !status.id) { let oldstatus = this.getWeather(); this.singleEvent('End', oldstatus, this.weatherData, this); } let prevWeather = this.weather; let prevWeatherData = this.weatherData; this.weather = status.id; this.weatherData = {id: status.id}; if (source) { this.weatherData.source = source; this.weatherData.sourcePosition = source.position; } if (status.duration) { this.weatherData.duration = status.duration; } if (status.durationCallback) { this.weatherData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.weatherData, this, source, sourceEffect)) { this.weather = prevWeather; this.weatherData = prevWeatherData; return false; } return true; }; Battle.prototype.clearWeather = function () { return this.setWeather(''); }; Battle.prototype.effectiveWeather = function (target) { if (this.event) { if (!target) target = this.event.target; } if (this.suppressingWeather()) return ''; return this.weather; }; Battle.prototype.isWeather = function (weather, target) { let ourWeather = this.effectiveWeather(target); if (!Array.isArray(weather)) { return ourWeather === toId(weather); } return (weather.map(toId).indexOf(ourWeather) >= 0); }; Battle.prototype.getWeather = function () { return this.getEffect(this.weather); }; Battle.prototype.setTerrain = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.terrain === status.id) return false; if (this.terrain && !status.id) { let oldstatus = this.getTerrain(); this.singleEvent('End', oldstatus, this.terrainData, this); } let prevTerrain = this.terrain; let prevTerrainData = this.terrainData; this.terrain = status.id; this.terrainData = {id: status.id}; if (source) { this.terrainData.source = source; this.terrainData.sourcePosition = source.position; } if (status.duration) { this.terrainData.duration = status.duration; } if (status.durationCallback) { this.terrainData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.terrainData, this, source, sourceEffect)) { this.terrain = prevTerrain; this.terrainData = prevTerrainData; return false; } return true; }; Battle.prototype.clearTerrain = function () { return this.setTerrain(''); }; Battle.prototype.effectiveTerrain = function (target) { if (this.event) { if (!target) target = this.event.target; } if (!this.runEvent('TryTerrain', target)) return ''; return this.terrain; }; Battle.prototype.isTerrain = function (terrain, target) { let ourTerrain = this.effectiveTerrain(target); if (!Array.isArray(terrain)) { return ourTerrain === toId(terrain); } return (terrain.map(toId).indexOf(ourTerrain) >= 0); }; Battle.prototype.getTerrain = function () { return this.getEffect(this.terrain); }; Battle.prototype.getFormat = function () { return this.getEffect(this.format); }; Battle.prototype.addPseudoWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (this.pseudoWeather[status.id]) { if (!status.onRestart) return false; return this.singleEvent('Restart', status, this.pseudoWeather[status.id], this, source, sourceEffect); } this.pseudoWeather[status.id] = {id: status.id}; if (source) { this.pseudoWeather[status.id].source = source; this.pseudoWeather[status.id].sourcePosition = source.position; } if (status.duration) { this.pseudoWeather[status.id].duration = status.duration; } if (status.durationCallback) { this.pseudoWeather[status.id].duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.pseudoWeather[status.id], this, source, sourceEffect)) { delete this.pseudoWeather[status.id]; return false; } return true; }; Battle.prototype.getPseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return null; return status; }; Battle.prototype.removePseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return false; this.singleEvent('End', status, this.pseudoWeather[status.id], this); delete this.pseudoWeather[status.id]; return true; }; Battle.prototype.suppressingAttackEvents = function () { return (this.activePokemon && this.activePokemon.isActive && !this.activePokemon.ignoringAbility() && this.activePokemon.getAbility().stopAttackEvents); }; Battle.prototype.suppressingWeather = function () { let pokemon; for (let i = 0; i < this.sides.length; i++) { for (let j = 0; j < this.sides[i].active.length; j++) { pokemon = this.sides[i].active[j]; if (pokemon && !pokemon.ignoringAbility() && pokemon.getAbility().suppressWeather) { return true; } } } return false; }; Battle.prototype.setActiveMove = function (move, pokemon, target) { if (!move) move = null; if (!pokemon) pokemon = null; if (!target) target = pokemon; this.activeMove = move; this.activePokemon = pokemon; this.activeTarget = target; }; Battle.prototype.clearActiveMove = function (failed) { if (this.activeMove) { if (!failed) { this.lastMove = this.activeMove.id; } this.activeMove = null; this.activePokemon = null; this.activeTarget = null; } }; Battle.prototype.updateSpeed = function () { let actives = this.p1.active; for (let i = 0; i < actives.length; i++) { if (actives[i]) actives[i].updateSpeed(); } actives = this.p2.active; for (let i = 0; i < actives.length; i++) { if (actives[i]) actives[i].updateSpeed(); } }; // intentionally not in Battle.prototype Battle.comparePriority = function (a, b) { a.priority = a.priority || 0; a.subPriority = a.subPriority || 0; a.speed = a.speed || 0; b.priority = b.priority || 0; b.subPriority = b.subPriority || 0; b.speed = b.speed || 0; if ((typeof a.order === 'number' || typeof b.order === 'number') && a.order !== b.order) { if (typeof a.order !== 'number') { return -1; } if (typeof b.order !== 'number') { return 1; } if (b.order - a.order) { return -(b.order - a.order); } } if (b.priority - a.priority) { return b.priority - a.priority; } if (b.speed - a.speed) { return b.speed - a.speed; } if (b.subOrder - a.subOrder) { return -(b.subOrder - a.subOrder); } return Math.random() - 0.5; }; // also not in Battle.prototype Battle.compareRedirectOrder = function (a, b) { a.priority = a.priority || 0; a.speed = a.speed || 0; b.priority = b.priority || 0; b.speed = b.speed || 0; if (b.priority - a.priority) { return b.priority - a.priority; } if (b.speed - a.speed) { return b.speed - a.speed; } if (b.thing.abilityOrder - a.thing.abilityOrder) { return -(b.thing.abilityOrder - a.thing.abilityOrder); } return 0; }; Battle.prototype.getResidualStatuses = function (thing, callbackType) { let statuses = this.getRelevantEffectsInner(thing || this, callbackType || 'residualCallback', null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); //if (statuses[0]) this.debug('match ' + (callbackType || 'residualCallback') + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.eachEvent = function (eventid, effect, relayVar) { let actives = []; if (!effect && this.effect) effect = this.effect; for (let i = 0; i < this.sides.length; i++) { let side = this.sides[i]; for (let j = 0; j < side.active.length; j++) { if (side.active[j]) actives.push(side.active[j]); } } actives.sort((a, b) => { if (b.speed - a.speed) { return b.speed - a.speed; } return Math.random() - 0.5; }); for (let i = 0; i < actives.length; i++) { if (actives[i].isStarted) { this.runEvent(eventid, actives[i], null, effect, relayVar); } } }; Battle.prototype.residualEvent = function (eventid, relayVar) { let statuses = this.getRelevantEffectsInner(this, 'on' + eventid, null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); while (statuses.length) { let statusObj = statuses.shift(); let status = statusObj.status; if (statusObj.thing.fainted) continue; if (statusObj.statusData && statusObj.statusData.duration) { statusObj.statusData.duration--; if (!statusObj.statusData.duration) { statusObj.end.call(statusObj.thing, status.id); continue; } } this.singleEvent(eventid, status, statusObj.statusData, statusObj.thing, relayVar); } }; // The entire event system revolves around this function // (and its helper functions, getRelevant * ) Battle.prototype.singleEvent = function (eventid, effect, effectData, target, source, sourceEffect, relayVar) { if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } //this.add('Event: ' + eventid + ' (depth ' + this.eventDepth + ')'); effect = this.getEffect(effect); let hasRelayVar = true; if (relayVar === undefined) { relayVar = true; hasRelayVar = false; } if (effect.effectType === 'Status' && target.status !== effect.id) { // it's changed; call it off return relayVar; } if (eventid !== 'Start' && eventid !== 'TakeItem' && eventid !== 'Primal' && effect.effectType === 'Item' && (target instanceof BattlePokemon) && target.ignoringItem()) { this.debug(eventid + ' handler suppressed by Embargo, Klutz or Magic Room'); return relayVar; } if (eventid !== 'End' && effect.effectType === 'Ability' && (target instanceof BattlePokemon) && target.ignoringAbility()) { this.debug(eventid + ' handler suppressed by Gastro Acid'); return relayVar; } if (effect.effectType === 'Weather' && eventid !== 'Start' && eventid !== 'Residual' && eventid !== 'End' && this.suppressingWeather()) { this.debug(eventid + ' handler suppressed by Air Lock'); return relayVar; } if (effect['on' + eventid] === undefined) return relayVar; let parentEffect = this.effect; let parentEffectData = this.effectData; let parentEvent = this.event; this.effect = effect; this.effectData = effectData; this.event = {id: eventid, target: target, source: source, effect: sourceEffect}; this.eventDepth++; let args = [target, source, sourceEffect]; if (hasRelayVar) args.unshift(relayVar); let returnVal; if (typeof effect['on' + eventid] === 'function') { returnVal = effect['on' + eventid].apply(this, args); } else { returnVal = effect['on' + eventid]; } this.eventDepth--; this.effect = parentEffect; this.effectData = parentEffectData; this.event = parentEvent; if (returnVal === undefined) return relayVar; return returnVal; }; /** * runEvent is the core of Pokemon Showdown's event system. * * Basic usage * =========== * * this.runEvent('Blah') * will trigger any onBlah global event handlers. * * this.runEvent('Blah', target) * will additionally trigger any onBlah handlers on the target, onAllyBlah * handlers on any active pokemon on the target's team, and onFoeBlah * handlers on any active pokemon on the target's foe's team * * this.runEvent('Blah', target, source) * will additionally trigger any onSourceBlah handlers on the source * * this.runEvent('Blah', target, source, effect) * will additionally pass the effect onto all event handlers triggered * * this.runEvent('Blah', target, source, effect, relayVar) * will additionally pass the relayVar as the first argument along all event * handlers * * You may leave any of these null. For instance, if you have a relayVar but * no source or effect: * this.runEvent('Damage', target, null, null, 50) * * Event handlers * ============== * * Items, abilities, statuses, and other effects like SR, confusion, weather, * or Trick Room can have event handlers. Event handlers are functions that * can modify what happens during an event. * * event handlers are passed: * function (target, source, effect) * although some of these can be blank. * * certain events have a relay variable, in which case they're passed: * function (relayVar, target, source, effect) * * Relay variables are variables that give additional information about the * event. For instance, the damage event has a relayVar which is the amount * of damage dealt. * * If a relay variable isn't passed to runEvent, there will still be a secret * relayVar defaulting to `true`, but it won't get passed to any event * handlers. * * After an event handler is run, its return value helps determine what * happens next: * 1. If the return value isn't `undefined`, relayVar is set to the return * value * 2. If relayVar is falsy, no more event handlers are run * 3. Otherwise, if there are more event handlers, the next one is run and * we go back to step 1. * 4. Once all event handlers are run (or one of them results in a falsy * relayVar), relayVar is returned by runEvent * * As a shortcut, an event handler that isn't a function will be interpreted * as a function that returns that value. * * You can have return values mean whatever you like, but in general, we * follow the convention that returning `false` or `null` means * stopping or interrupting the event. * * For instance, returning `false` from a TrySetStatus handler means that * the pokemon doesn't get statused. * * If a failed event usually results in a message like "But it failed!" * or "It had no effect!", returning `null` will suppress that message and * returning `false` will display it. Returning `null` is useful if your * event handler already gave its own custom failure message. * * Returning `undefined` means "don't change anything" or "keep going". * A function that does nothing but return `undefined` is the equivalent * of not having an event handler at all. * * Returning a value means that that value is the new `relayVar`. For * instance, if a Damage event handler returns 50, the damage event * will deal 50 damage instead of whatever it was going to deal before. * * Useful values * ============= * * In addition to all the methods and attributes of Tools, Battle, and * Scripts, event handlers have some additional values they can access: * * this.effect: * the Effect having the event handler * this.effectData: * the data store associated with the above Effect. This is a plain Object * and you can use it to store data for later event handlers. * this.effectData.target: * the Pokemon, Side, or Battle that the event handler's effect was * attached to. * this.event.id: * the event ID * this.event.target, this.event.source, this.event.effect: * the target, source, and effect of the event. These are the same * variables that are passed as arguments to the event handler, but * they're useful for functions called by the event handler. */ Battle.prototype.runEvent = function (eventid, target, source, effect, relayVar, onEffect, fastExit) { // if (Battle.eventCounter) { // if (!Battle.eventCounter[eventid]) Battle.eventCounter[eventid] = 0; // Battle.eventCounter[eventid]++; // } if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } if (!target) target = this; let statuses = this.getRelevantEffects(target, 'on' + eventid, 'onSource' + eventid, source); if (fastExit) { statuses.sort(Battle.compareRedirectOrder); } else { statuses.sort(Battle.comparePriority); } let hasRelayVar = true; effect = this.getEffect(effect); let args = [target, source, effect]; //console.log('Event: ' + eventid + ' (depth ' + this.eventDepth + ') t:' + target.id + ' s:' + (!source || source.id) + ' e:' + effect.id); if (relayVar === undefined || relayVar === null) { relayVar = true; hasRelayVar = false; } else { args.unshift(relayVar); } let parentEvent = this.event; this.event = {id: eventid, target: target, source: source, effect: effect, modifier: 1}; this.eventDepth++; if (onEffect && 'on' + eventid in effect) { statuses.unshift({status: effect, callback: effect['on' + eventid], statusData: {}, end: null, thing: target}); } for (let i = 0; i < statuses.length; i++) { let status = statuses[i].status; let thing = statuses[i].thing; //this.debug('match ' + eventid + ': ' + status.id + ' ' + status.effectType); if (status.effectType === 'Status' && thing.status !== status.id) { // it's changed; call it off continue; } if (status.effectType === 'Ability' && this.suppressingAttackEvents() && this.activePokemon !== thing) { // ignore attacking events let AttackingEvents = { BeforeMove: 1, BasePower: 1, Immunity: 1, RedirectTarget: 1, Heal: 1, SetStatus: 1, CriticalHit: 1, ModifyAtk: 1, ModifyDef: 1, ModifySpA: 1, ModifySpD: 1, ModifySpe: 1, ModifyAccuracy: 1, ModifyBoost: 1, ModifyDamage: 1, ModifySecondaries: 1, ModifyWeight: 1, TryHit: 1, TryHitSide: 1, TryMove: 1, Hit: 1, Boost: 1, DragOut: 1, }; if (eventid in AttackingEvents) { this.debug(eventid + ' handler suppressed by Mold Breaker'); continue; } else if (eventid === 'Damage' && effect && effect.effectType === 'Move') { this.debug(eventid + ' handler suppressed by Mold Breaker'); continue; } } if (eventid !== 'Start' && eventid !== 'SwitchIn' && eventid !== 'TakeItem' && status.effectType === 'Item' && (thing instanceof BattlePokemon) && thing.ignoringItem()) { if (eventid !== 'Update') { this.debug(eventid + ' handler suppressed by Embargo, Klutz or Magic Room'); } continue; } else if (eventid !== 'End' && status.effectType === 'Ability' && (thing instanceof BattlePokemon) && thing.ignoringAbility()) { if (eventid !== 'Update') { this.debug(eventid + ' handler suppressed by Gastro Acid'); } continue; } if ((status.effectType === 'Weather' || eventid === 'Weather') && eventid !== 'Residual' && eventid !== 'End' && this.suppressingWeather()) { this.debug(eventid + ' handler suppressed by Air Lock'); continue; } let returnVal; if (typeof statuses[i].callback === 'function') { let parentEffect = this.effect; let parentEffectData = this.effectData; this.effect = statuses[i].status; this.effectData = statuses[i].statusData; this.effectData.target = thing; returnVal = statuses[i].callback.apply(this, args); this.effect = parentEffect; this.effectData = parentEffectData; } else { returnVal = statuses[i].callback; } if (returnVal !== undefined) { relayVar = returnVal; if (!relayVar || fastExit) break; if (hasRelayVar) { args[0] = relayVar; } } } this.eventDepth--; if (this.event.modifier !== 1 && typeof relayVar === 'number') { // this.debug(eventid + ' modifier: 0x' + ('0000' + (this.event.modifier * 4096).toString(16)).slice(-4).toUpperCase()); relayVar = this.modify(relayVar, this.event.modifier); } this.event = parentEvent; return relayVar; }; /** * priorityEvent works just like runEvent, except it exits and returns * on the first non-undefined value instead of only on null/false. */ Battle.prototype.priorityEvent = function (eventid, target, source, effect, relayVar, onEffect) { return this.runEvent(eventid, target, source, effect, relayVar, onEffect, true); }; Battle.prototype.resolveLastPriority = function (statuses, callbackType) { let order = false; let priority = 0; let subOrder = 0; let status = statuses[statuses.length - 1]; if (status.status[callbackType + 'Order']) { order = status.status[callbackType + 'Order']; } if (status.status[callbackType + 'Priority']) { priority = status.status[callbackType + 'Priority']; } else if (status.status[callbackType + 'SubOrder']) { subOrder = status.status[callbackType + 'SubOrder']; } status.order = order; status.priority = priority; status.subOrder = subOrder; if (status.thing && status.thing.getStat) status.speed = status.thing.speed; }; // bubbles up to parents Battle.prototype.getRelevantEffects = function (thing, callbackType, foeCallbackType, foeThing) { let statuses = this.getRelevantEffectsInner(thing, callbackType, foeCallbackType, foeThing, true, false); //if (statuses[0]) this.debug('match ' + callbackType + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.getRelevantEffectsInner = function (thing, callbackType, foeCallbackType, foeThing, bubbleUp, bubbleDown, getAll) { if (!callbackType || !thing) return []; let statuses = []; let status; if (thing.sides) { for (let i in this.pseudoWeather) { status = this.getPseudoWeather(i); if (status[callbackType] !== undefined || (getAll && thing.pseudoWeather[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.pseudoWeather[i], end: this.removePseudoWeather, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = this.getWeather(); if (status[callbackType] !== undefined || (getAll && thing.weatherData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.weatherData, end: this.clearWeather, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getTerrain(); if (status[callbackType] !== undefined || (getAll && thing.terrainData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.terrainData, end: this.clearTerrain, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getFormat(); if (status[callbackType] !== undefined || (getAll && thing.formatData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.formatData, end: function () {}, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } if (this.events && this.events[callbackType] !== undefined) { for (let i = 0; i < this.events[callbackType].length; i++) { let handler = this.events[callbackType][i]; let statusData; switch (handler.target.effectType) { case 'Format': statusData = this.formatData; } statuses.push({status: handler.target, callback: handler.callback, statusData: statusData, end: function () {}, thing: thing, priority: handler.priority, order: handler.order, subOrder: handler.subOrder}); } } if (bubbleDown) { statuses = statuses.concat(this.getRelevantEffectsInner(this.p1, callbackType, null, null, false, true, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(this.p2, callbackType, null, null, false, true, getAll)); } return statuses; } if (thing.pokemon) { for (let i in thing.sideConditions) { status = thing.getSideCondition(i); if (status[callbackType] !== undefined || (getAll && thing.sideConditions[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.sideConditions[i], end: thing.removeSideCondition, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } if (foeCallbackType) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.foe, foeCallbackType, null, null, false, false, getAll)); if (foeCallbackType.substr(0, 5) === 'onFoe') { let eventName = foeCallbackType.substr(5); statuses = statuses.concat(this.getRelevantEffectsInner(thing.foe, 'onAny' + eventName, null, null, false, false, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(thing, 'onAny' + eventName, null, null, false, false, getAll)); } } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(this, callbackType, null, null, true, false, getAll)); } if (bubbleDown) { for (let i = 0; i < thing.active.length; i++) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.active[i], callbackType, null, null, false, true, getAll)); } } return statuses; } if (!thing.getStatus) { //this.debug(JSON.stringify(thing)); return statuses; } status = thing.getStatus(); if (status[callbackType] !== undefined || (getAll && thing.statusData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.statusData, end: thing.clearStatus, thing: thing}); this.resolveLastPriority(statuses, callbackType); } for (let i in thing.volatiles) { status = thing.getVolatile(i); if (status[callbackType] !== undefined || (getAll && thing.volatiles[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.volatiles[i], end: thing.removeVolatile, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = thing.getAbility(); if (status[callbackType] !== undefined || (getAll && thing.abilityData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.abilityData, end: thing.clearAbility, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = thing.getItem(); if (status[callbackType] !== undefined || (getAll && thing.itemData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.itemData, end: thing.clearItem, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = this.getEffect(thing.template.baseSpecies); if (status[callbackType] !== undefined) { statuses.push({status: status, callback: status[callbackType], statusData: thing.speciesData, end: function () {}, thing: thing}); this.resolveLastPriority(statuses, callbackType); } if (foeThing && foeCallbackType && foeCallbackType.substr(0, 8) !== 'onSource') { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } else if (foeCallbackType) { let foeActive = thing.side.foe.active; let allyActive = thing.side.active; let eventName = ''; if (foeCallbackType.substr(0, 8) === 'onSource') { eventName = foeCallbackType.substr(8); if (foeThing) { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } foeCallbackType = 'onFoe' + eventName; foeThing = null; } if (foeCallbackType.substr(0, 5) === 'onFoe') { eventName = foeCallbackType.substr(5); for (let i = 0; i < allyActive.length; i++) { if (!allyActive[i] || allyActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAlly' + eventName, null, null, false, false, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } for (let i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } } for (let i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], foeCallbackType, null, null, false, false, getAll)); } } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.side, callbackType, foeCallbackType, null, true, false, getAll)); } return statuses; }; /** * Use this function to attach custom event handlers to a battle. See Battle#runEvent for * more information on how to write callbacks for event handlers. * * Try to use this sparingly. Most event handlers can be simply placed in a format instead. * * this.on(eventid, target, callback) * will set the callback as an event handler for the target when eventid is called with the * default priority. Currently only valid formats are supported as targets but this will * eventually be expanded to support other target types. * * this.on(eventid, target, priority, callback) * will set the callback as an event handler for the target when eventid is called with the * provided priority. Priority can either be a number or an object that contains the priority, * order, and subOrder for the evend handler as needed (undefined keys will use default values) */ Battle.prototype.on = function (eventid, target /*[, priority], callback*/) { if (!eventid) throw new TypeError("Event handlers must have an event to listen to"); if (!target) throw new TypeError("Event handlers must have a target"); if (arguments.length < 3) throw new TypeError("Event handlers must have a callback"); if (target.effectType !== 'Format') { throw new TypeError("" + target.effectType + " targets are not supported at this time"); } let callback, priority, order, subOrder; if (arguments.length === 3) { callback = arguments[2]; priority = 0; order = false; subOrder = 0; } else { callback = arguments[3]; let data = arguments[2]; if (typeof data === 'object') { priority = data['priority'] || 0; order = data['order'] || false; subOrder = data['subOrder'] || 0; } else { priority = data || 0; order = false; subOrder = 0; } } let eventHandler = {callback: callback, target: target, priority: priority, order: order, subOrder: subOrder}; let callbackType = 'on' + eventid; if (!this.events) this.events = {}; if (this.events[callbackType] === undefined) { this.events[callbackType] = [eventHandler]; } else { this.events[callbackType].push(eventHandler); } }; Battle.prototype.getPokemon = function (id) { if (typeof id !== 'string') id = id.id; for (let i = 0; i < this.p1.pokemon.length; i++) { let pokemon = this.p1.pokemon[i]; if (pokemon.id === id) return pokemon; } for (let i = 0; i < this.p2.pokemon.length; i++) { let pokemon = this.p2.pokemon[i]; if (pokemon.id === id) return pokemon; } return null; }; Battle.prototype.makeRequest = function (type, requestDetails) { if (type) { this.currentRequest = type; this.currentRequestDetails = requestDetails || ''; this.rqid++; this.p1.decision = null; this.p2.decision = null; } else { type = this.currentRequest; requestDetails = this.currentRequestDetails; } // default to no request let p1request = null; let p2request = null; this.p1.currentRequest = ''; this.p2.currentRequest = ''; let switchTable = []; switch (type) { case 'switch': { for (let i = 0, l = this.p1.active.length; i < l; i++) { let active = this.p1.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p1.currentRequest = 'switch'; p1request = {forceSwitch: switchTable, side: this.p1.getData(), rqid: this.rqid}; } switchTable = []; for (let i = 0, l = this.p2.active.length; i < l; i++) { let active = this.p2.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p2.currentRequest = 'switch'; p2request = {forceSwitch: switchTable, side: this.p2.getData(), rqid: this.rqid}; } break; } case 'teampreview': this.add('teampreview' + (requestDetails ? '|' + requestDetails : '')); this.p1.currentRequest = 'teampreview'; p1request = {teamPreview: true, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'teampreview'; p2request = {teamPreview: true, side: this.p2.getData(), rqid: this.rqid}; break; default: { this.p1.currentRequest = 'move'; let activeData = this.p1.active.map(pokemon => pokemon && pokemon.getRequestData()); p1request = {active: activeData, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'move'; activeData = this.p2.active.map(pokemon => pokemon && pokemon.getRequestData()); p2request = {active: activeData, side: this.p2.getData(), rqid: this.rqid}; break; } } if (this.p1 && this.p2) { let inactiveSide = -1; if (p1request && !p2request) { inactiveSide = 0; } else if (!p1request && p2request) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (p1request) { if (!this.supportCancel || !p2request) p1request.noCancel = true; this.p1.emitRequest(p1request); } else { this.p1.decision = true; this.p1.emitRequest({wait: true, side: this.p1.getData()}); } if (p2request) { if (!this.supportCancel || !p1request) p2request.noCancel = true; this.p2.emitRequest(p2request); } else { this.p2.decision = true; this.p2.emitRequest({wait: true, side: this.p2.getData()}); } if (this.p2.decision && this.p1.decision) { if (this.p2.decision === true && this.p1.decision === true) { if (type !== 'move') { // TODO: investigate this race condition; should be fixed // properly later return this.makeRequest('move'); } this.add('html', '<div class="broadcast-red"><b>The battle crashed</b></div>'); this.win(); } else { // some kind of weird race condition? this.commitDecisions(); } return; } }; Battle.prototype.tie = function () { this.win(); }; Battle.prototype.win = function (side) { if (this.ended) { return false; } if (side === 'p1' || side === 'p2') { side = this[side]; } else if (side !== this.p1 && side !== this.p2) { side = null; } this.winner = side ? side.name : ''; this.add(''); if (side) { this.add('win', side.name); } else { this.add('tie'); } this.ended = true; this.active = false; this.currentRequest = ''; this.currentRequestDetails = ''; return true; }; Battle.prototype.switchIn = function (pokemon, pos) { if (!pokemon || pokemon.isActive) return false; if (!pos) pos = 0; let side = pokemon.side; if (pos >= side.active.length) { throw new Error("Invalid switch position"); } if (side.active[pos]) { let oldActive = side.active[pos]; if (this.cancelMove(oldActive)) { for (let i = 0; i < side.foe.active.length; i++) { if (side.foe.active[i].isStale >= 2) { oldActive.isStaleCon++; oldActive.isStaleSource = 'drag'; break; } } } if (oldActive.switchCopyFlag === 'copyvolatile') { delete oldActive.switchCopyFlag; pokemon.copyVolatileFrom(oldActive); } } pokemon.isActive = true; this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { let oldActive = side.active[pos]; oldActive.isActive = false; oldActive.isStarted = false; oldActive.usedItemThisTurn = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; this.cancelMove(oldActive); oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.activeTurns = 0; for (let m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('switch', pokemon, pokemon.getDetails); this.insertQueue({pokemon: pokemon, choice: 'runSwitch'}); }; Battle.prototype.canSwitch = function (side) { let canSwitchIn = []; for (let i = side.active.length; i < side.pokemon.length; i++) { let pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } return canSwitchIn.length; }; Battle.prototype.getRandomSwitchable = function (side) { let canSwitchIn = []; for (let i = side.active.length; i < side.pokemon.length; i++) { let pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } if (!canSwitchIn.length) { return null; } return canSwitchIn[this.random(canSwitchIn.length)]; }; Battle.prototype.dragIn = function (side, pos) { if (pos >= side.active.length) return false; let pokemon = this.getRandomSwitchable(side); if (!pos) pos = 0; if (!pokemon || pokemon.isActive) return false; this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { let oldActive = side.active[pos]; if (!oldActive.hp) { return false; } if (!this.runEvent('DragOut', oldActive)) { return false; } this.runEvent('SwitchOut', oldActive); this.singleEvent('End', this.getAbility(oldActive.ability), oldActive.abilityData, oldActive); oldActive.isActive = false; oldActive.isStarted = false; oldActive.usedItemThisTurn = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; if (this.cancelMove(oldActive)) { for (let i = 0; i < side.foe.active.length; i++) { if (side.foe.active[i].isStale >= 2) { oldActive.isStaleCon++; oldActive.isStaleSource = 'drag'; break; } } } oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.isActive = true; pokemon.activeTurns = 0; if (this.gen === 2) pokemon.draggedIn = this.turn; for (let m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('drag', pokemon, pokemon.getDetails); if (this.gen >= 5) { this.runEvent('SwitchIn', pokemon); if (!pokemon.hp) return true; pokemon.isStarted = true; if (!pokemon.fainted) { this.singleEvent('Start', pokemon.getAbility(), pokemon.abilityData, pokemon); this.singleEvent('Start', pokemon.getItem(), pokemon.itemData, pokemon); } } else { this.insertQueue({pokemon: pokemon, choice: 'runSwitch'}); } return true; }; Battle.prototype.swapPosition = function (pokemon, slot, attributes) { if (slot >= pokemon.side.active.length) { throw new Error("Invalid swap position"); } let target = pokemon.side.active[slot]; if (slot !== 1 && (!target || target.fainted)) return false; this.add('swap', pokemon, slot, attributes || ''); let side = pokemon.side; side.pokemon[pokemon.position] = target; side.pokemon[slot] = pokemon; side.active[pokemon.position] = side.pokemon[pokemon.position]; side.active[slot] = side.pokemon[slot]; if (target) target.position = pokemon.position; pokemon.position = slot; return true; }; Battle.prototype.faint = function (pokemon, source, effect) { pokemon.faint(source, effect); }; Battle.prototype.nextTurn = function () { this.turn++; let allStale = true; let oneStale = false; for (let i = 0; i < this.sides.length; i++) { for (let j = 0; j < this.sides[i].active.length; j++) { let pokemon = this.sides[i].active[j]; if (!pokemon) continue; pokemon.moveThisTurn = ''; pokemon.usedItemThisTurn = false; pokemon.newlySwitched = false; pokemon.maybeDisabled = false; for (let entry of pokemon.moveset) { entry.disabled = false; entry.disabledSource = ''; } this.runEvent('DisableMove', pokemon); if (!pokemon.ateBerry) pokemon.disableMove('belch'); if (pokemon.lastAttackedBy) { if (pokemon.lastAttackedBy.pokemon.isActive) { pokemon.lastAttackedBy.thisTurn = false; } else { pokemon.lastAttackedBy = null; } } pokemon.trapped = pokemon.maybeTrapped = false; this.runEvent('TrapPokemon', pokemon); if (pokemon.runStatusImmunity('trapped')) { this.runEvent('MaybeTrapPokemon', pokemon); } // Disable the faculty to cancel switches if a foe may have a trapping ability let foeSide = pokemon.side.foe; for (let k = 0; k < foeSide.active.length; ++k) { let source = foeSide.active[k]; if (!source || source.fainted) continue; let template = (source.illusion || source).template; if (!template.abilities) continue; for (let abilitySlot in template.abilities) { let abilityName = template.abilities[abilitySlot]; if (abilityName === source.ability) { // pokemon event was already run above so we don't need // to run it again. continue; } let banlistTable = this.getFormat().banlistTable; if (banlistTable && !('illegal' in banlistTable) && !this.getFormat().team) { // hackmons format continue; } else if (abilitySlot === 'H' && template.unreleasedHidden) { // unreleased hidden ability continue; } let ability = this.getAbility(abilityName); if (banlistTable && ability.id in banlistTable) continue; if (!pokemon.runStatusImmunity('trapped')) continue; this.singleEvent('FoeMaybeTrapPokemon', ability, {}, pokemon, source); } } if (pokemon.fainted) continue; if (pokemon.isStale < 2) { if (pokemon.isStaleCon >= 2) { if (pokemon.hp >= pokemon.isStaleHP - pokemon.maxhp / 100) { pokemon.isStale++; if (this.firstStaleWarned && pokemon.isStale < 2) { switch (pokemon.isStaleSource) { case 'struggle': this.add('html', '<div class="broadcast-red">' + this.escapeHTML(pokemon.name) + ' isn\'t losing HP from Struggle. If this continues, it will be classified as being in an endless loop.</div>'); break; case 'drag': this.add('html', '<div class="broadcast-red">' + this.escapeHTML(pokemon.name) + ' isn\'t losing PP or HP from being forced to switch. If this continues, it will be classified as being in an endless loop.</div>'); break; case 'switch': this.add('html', '<div class="broadcast-red">' + this.escapeHTML(pokemon.name) + ' isn\'t losing PP or HP from repeatedly switching. If this continues, it will be classified as being in an endless loop.</div>'); break; } } } pokemon.isStaleCon = 0; pokemon.isStalePPTurns = 0; pokemon.isStaleHP = pokemon.hp; } if (pokemon.isStalePPTurns >= 5) { if (pokemon.hp >= pokemon.isStaleHP - pokemon.maxhp / 100) { pokemon.isStale++; pokemon.isStaleSource = 'ppstall'; if (this.firstStaleWarned && pokemon.isStale < 2) { this.add('html', '<div class="broadcast-red">' + this.escapeHTML(pokemon.name) + ' isn\'t losing PP or HP. If it keeps on not losing PP or HP, it will be classified as being in an endless loop.</div>'); } } pokemon.isStaleCon = 0; pokemon.isStalePPTurns = 0; pokemon.isStaleHP = pokemon.hp; } } if (pokemon.getMoves().length === 0) { pokemon.isStaleCon++; pokemon.isStaleSource = 'struggle'; } if (pokemon.isStale < 2) { allStale = false; } else if (pokemon.isStale && !pokemon.staleWarned) { oneStale = pokemon; } if (!pokemon.isStalePPTurns) { pokemon.isStaleHP = pokemon.hp; if (pokemon.activeTurns) pokemon.isStaleCon = 0; } if (pokemon.activeTurns) { pokemon.isStalePPTurns++; } pokemon.activeTurns++; } this.sides[i].faintedLastTurn = this.sides[i].faintedThisTurn; this.sides[i].faintedThisTurn = false; } let banlistTable = this.getFormat().banlistTable; if (banlistTable && 'Rule:endlessbattleclause' in banlistTable) { if (oneStale) { let activationWarning = '<br />If all active Pok&eacute;mon go in an endless loop, Endless Battle Clause will activate.'; if (allStale) activationWarning = ''; let loopReason = ''; switch (oneStale.isStaleSource) { case 'struggle': loopReason = ": it isn't losing HP from Struggle"; break; case 'drag': loopReason = ": it isn't losing PP or HP from being forced to switch"; break; case 'switch': loopReason = ": it isn't losing PP or HP from repeatedly switching"; break; case 'getleppa': loopReason = ": it got a Leppa Berry it didn't start with"; break; case 'useleppa': loopReason = ": it used a Leppa Berry it didn't start with"; break; case 'ppstall': loopReason = ": it isn't losing PP or HP"; break; case 'ppoverflow': loopReason = ": its PP overflowed"; break; } this.add('html', '<div class="broadcast-red">' + this.escapeHTML(oneStale.name) + ' is in an endless loop' + loopReason + '.' + activationWarning + '</div>'); oneStale.staleWarned = true; this.firstStaleWarned = true; } if (allStale) { this.add('message', "All active Pok\u00e9mon are in an endless loop. Endless Battle Clause activated!"); let leppaPokemon = null; for (let i = 0; i < this.sides.length; i++) { for (let j = 0; j < this.sides[i].pokemon.length; j++) { let pokemon = this.sides[i].pokemon[j]; if (toId(pokemon.set.item) === 'leppaberry') { if (leppaPokemon) { leppaPokemon = null; // both sides have Leppa this.add('-message', "Both sides started with a Leppa Berry."); } else { leppaPokemon = pokemon; } break; } } } if (leppaPokemon) { this.add('-message', "" + leppaPokemon.side.name + "'s " + leppaPokemon.name + " started with a Leppa Berry and loses."); this.win(leppaPokemon.side.foe); return; } this.win(); return; } } else { if (allStale && !this.staleWarned) { this.staleWarned = true; this.add('html', '<div class="broadcast-red">If this format had Endless Battle Clause, it would have activated.</div>'); } else if (oneStale) { this.add('html', '<div class="broadcast-red">' + this.escapeHTML(oneStale.name) + ' is in an endless loop.</div>'); oneStale.staleWarned = true; } } if (this.gameType === 'triples' && this.sides.map('pokemonLeft').count(1) === this.sides.length) { // If both sides have one Pokemon left in triples and they are not adjacent, they are both moved to the center. let center = false; for (let i = 0; i < this.sides.length; i++) { for (let j = 0; j < this.sides[i].active.length; j++) { if (!this.sides[i].active[j] || this.sides[i].active[j].fainted) continue; if (this.sides[i].active[j].position === 1) break; this.swapPosition(this.sides[i].active[j], 1, '[silent]'); center = true; break; } } if (center) this.add('-center'); } this.add('turn', this.turn); this.makeRequest('move'); }; Battle.prototype.start = function () { if (this.active) return; if (!this.p1 || !this.p1.isActive || !this.p2 || !this.p2.isActive) { // need two players to start return; } if (this.started) { this.makeRequest(); this.isActive = true; this.activeTurns = 0; return; } this.isActive = true; this.activeTurns = 0; this.started = true; this.p2.foe = this.p1; this.p1.foe = this.p2; this.add('gametype', this.gameType); this.add('gen', this.gen); let format = this.getFormat(); Tools.mod(format.mod).getBanlistTable(format); // fill in format ruleset this.add('tier', format.name); if (this.rated) { this.add('rated'); } this.add('seed', Battle.logReplay.bind(this, this.startingSeed.join(','))); if (format.onBegin) { format.onBegin.call(this); } if (format && format.ruleset) { for (let i = 0; i < format.ruleset.length; i++) { this.addPseudoWeather(format.ruleset[i]); } } if (!this.p1.pokemon[0] || !this.p2.pokemon[0]) { this.add('message', 'Battle not started: One of you has an empty team.'); return; } this.residualEvent('TeamPreview'); this.addQueue({choice: 'start'}); this.midTurn = true; if (!this.currentRequest) this.go(); }; Battle.prototype.boost = function (boost, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!target.isActive) return false; effect = this.getEffect(effect); boost = this.runEvent('Boost', target, source, effect, Object.clone(boost)); let success = false; let boosted = false; for (let i in boost) { let currentBoost = {}; currentBoost[i] = boost[i]; if (boost[i] !== 0 && target.boostBy(currentBoost)) { success = true; let msg = '-boost'; if (boost[i] < 0) { msg = '-unboost'; boost[i] = -boost[i]; } switch (effect.id) { case 'bellydrum': this.add('-setboost', target, 'atk', target.boosts['atk'], '[from] move: Belly Drum'); break; case 'bellydrum2': this.add(msg, target, i, boost[i], '[silent]'); this.add('-hint', "In Gen 2, Belly Drum boosts by 2 when it fails."); break; case 'intimidate': case 'gooey': this.add(msg, target, i, boost[i]); break; default: if (effect.effectType === 'Move') { this.add(msg, target, i, boost[i]); } else { if (effect.effectType === 'Ability' && !boosted) { this.add('-ability', target, effect.name, 'boost'); boosted = true; } this.add(msg, target, i, boost[i]); } break; } this.runEvent('AfterEachBoost', target, source, effect, currentBoost); } } this.runEvent('AfterBoost', target, source, effect, boost); return success; }; Battle.prototype.damage = function (damage, target, source, effect, instafaint) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!target.isActive) return false; effect = this.getEffect(effect); if (!(damage || damage === 0)) return damage; if (damage !== 0) damage = this.clampIntRange(damage, 1); if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects if (effect.effectType === 'Weather' && !target.runStatusImmunity(effect.id)) { this.debug('weather immunity'); return 0; } damage = this.runEvent('Damage', target, source, effect, damage); if (!(damage || damage === 0)) { this.debug('damage event failed'); return damage; } if (target.illusion && effect && effect.effectType === 'Move' && effect.id !== 'confused') { this.debug('illusion cleared'); target.illusion = null; this.add('replace', target, target.getDetails); this.add('-end', target, 'Illusion'); } } if (damage !== 0) damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); if (source) source.lastDamage = damage; let name = effect.fullname; if (name === 'tox') name = 'psn'; switch (effect.id) { case 'partiallytrapped': this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]'); break; case 'powder': this.add('-damage', target, target.getHealth, '[silent]'); break; case 'confused': this.add('-damage', target, target.getHealth, '[from] confusion'); break; default: if (effect.effectType === 'Move' || !name) { this.add('-damage', target, target.getHealth); } else if (source && (source !== target || effect.effectType === 'Ability')) { this.add('-damage', target, target.getHealth, '[from] ' + name, '[of] ' + source); } else { this.add('-damage', target, target.getHealth, '[from] ' + name); } break; } if (effect.drain && source) { this.heal(Math.ceil(damage * effect.drain[0] / effect.drain[1]), source, target, 'drain'); } if (!effect.flags) effect.flags = {}; if (instafaint && !target.hp) { this.debug('instafaint: ' + this.faintQueue.map('target').map('name')); this.faintMessages(true); } else { damage = this.runEvent('AfterDamage', target, source, effect, damage); } return damage; }; Battle.prototype.directDamage = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!damage) return 0; damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); switch (effect.id) { case 'strugglerecoil': this.add('-damage', target, target.getHealth, '[from] recoil'); break; case 'confusion': this.add('-damage', target, target.getHealth, '[from] confusion'); break; default: this.add('-damage', target, target.getHealth); break; } if (target.fainted) this.faint(target); return damage; }; Battle.prototype.heal = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } effect = this.getEffect(effect); if (damage && damage <= 1) damage = 1; damage = Math.floor(damage); // for things like Liquid Ooze, the Heal event still happens when nothing is healed. damage = this.runEvent('TryHeal', target, source, effect, damage); if (!damage) return 0; if (!target || !target.hp) return 0; if (!target.isActive) return false; if (target.hp >= target.maxhp) return 0; damage = target.heal(damage, source, effect); switch (effect.id) { case 'leechseed': case 'rest': this.add('-heal', target, target.getHealth, '[silent]'); break; case 'drain': this.add('-heal', target, target.getHealth, '[from] drain', '[of] ' + source); break; case 'wish': break; default: if (effect.effectType === 'Move') { this.add('-heal', target, target.getHealth); } else if (source && source !== target) { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname); } break; } this.runEvent('Heal', target, source, effect, damage); return damage; }; Battle.prototype.chain = function (previousMod, nextMod) { // previousMod or nextMod can be either a number or an array [numerator, denominator] if (previousMod.length) { previousMod = Math.floor(previousMod[0] * 4096 / previousMod[1]); } else { previousMod = Math.floor(previousMod * 4096); } if (nextMod.length) { nextMod = Math.floor(nextMod[0] * 4096 / nextMod[1]); } else { nextMod = Math.floor(nextMod * 4096); } return ((previousMod * nextMod + 2048) >> 12) / 4096; // M'' = ((M * M') + 0x800) >> 12 }; Battle.prototype.chainModify = function (numerator, denominator) { let previousMod = Math.floor(this.event.modifier * 4096); if (numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } let nextMod = 0; if (this.event.ceilModifier) { nextMod = Math.ceil(numerator * 4096 / (denominator || 1)); } else { nextMod = Math.floor(numerator * 4096 / (denominator || 1)); } this.event.modifier = ((previousMod * nextMod + 2048) >> 12) / 4096; }; Battle.prototype.modify = function (value, numerator, denominator) { // You can also use: // modify(value, [numerator, denominator]) // modify(value, fraction) - assuming you trust JavaScript's floating-point handler if (!denominator) denominator = 1; if (numerator && numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } let modifier = Math.floor(numerator * 4096 / denominator); return Math.floor((value * modifier + 2048 - 1) / 4096); }; Battle.prototype.getCategory = function (move) { move = this.getMove(move); return move.category || 'Physical'; }; Battle.prototype.getDamage = function (pokemon, target, move, suppressMessages) { if (typeof move === 'string') move = this.getMove(move); if (typeof move === 'number') { move = { basePower: move, type: '???', category: 'Physical', flags: {}, }; } if (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) { if (!target.runImmunity(move.type, !suppressMessages)) { return false; } } if (move.ohko) { return target.maxhp; } if (move.damageCallback) { return move.damageCallback.call(this, pokemon, target); } if (move.damage === 'level') { return pokemon.level; } if (move.damage) { return move.damage; } if (!move) { move = {}; } if (!move.type) move.type = '???'; let type = move.type; // '???' is typeless damage: used for Struggle and Confusion etc let category = this.getCategory(move); let defensiveCategory = move.defensiveCategory || category; let basePower = move.basePower; if (move.basePowerCallback) { basePower = move.basePowerCallback.call(this, pokemon, target, move); } if (!basePower) { if (basePower === 0) return; // returning undefined means not dealing damage return basePower; } basePower = this.clampIntRange(basePower, 1); let critMult; if (this.gen <= 5) { move.critRatio = this.clampIntRange(move.critRatio, 0, 5); critMult = [0, 16, 8, 4, 3, 2]; } else { move.critRatio = this.clampIntRange(move.critRatio, 0, 4); critMult = [0, 16, 8, 2, 1]; } move.crit = move.willCrit || false; if (move.willCrit === undefined) { if (move.critRatio) { move.crit = (this.random(critMult[move.critRatio]) === 0); } } if (move.crit) { move.crit = this.runEvent('CriticalHit', target, null, move); } // happens after crit calculation basePower = this.runEvent('BasePower', pokemon, target, move, basePower, true); if (!basePower) return 0; basePower = this.clampIntRange(basePower, 1); let level = pokemon.level; let attacker = pokemon; let defender = target; let attackStat = category === 'Physical' ? 'atk' : 'spa'; let defenseStat = defensiveCategory === 'Physical' ? 'def' : 'spd'; let statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; let attack; let defense; let atkBoosts = move.useTargetOffensive ? defender.boosts[attackStat] : attacker.boosts[attackStat]; let defBoosts = move.useSourceDefensive ? attacker.boosts[defenseStat] : defender.boosts[defenseStat]; let ignoreNegativeOffensive = !!move.ignoreNegativeOffensive; let ignorePositiveDefensive = !!move.ignorePositiveDefensive; if (move.crit) { ignoreNegativeOffensive = true; ignorePositiveDefensive = true; } let ignoreOffensive = !!(move.ignoreOffensive || (ignoreNegativeOffensive && atkBoosts < 0)); let ignoreDefensive = !!(move.ignoreDefensive || (ignorePositiveDefensive && defBoosts > 0)); if (ignoreOffensive) { this.debug('Negating (sp)atk boost/penalty.'); atkBoosts = 0; } if (ignoreDefensive) { this.debug('Negating (sp)def boost/penalty.'); defBoosts = 0; } if (move.useTargetOffensive) { attack = defender.calculateStat(attackStat, atkBoosts); } else { attack = attacker.calculateStat(attackStat, atkBoosts); } if (move.useSourceDefensive) { defense = attacker.calculateStat(defenseStat, defBoosts); } else { defense = defender.calculateStat(defenseStat, defBoosts); } // Apply Stat Modifiers attack = this.runEvent('Modify' + statTable[attackStat], attacker, defender, move, attack); defense = this.runEvent('Modify' + statTable[defenseStat], defender, attacker, move, defense); //int(int(int(2 * L / 5 + 2) * A * P / D) / 50); let baseDamage = Math.floor(Math.floor(Math.floor(2 * level / 5 + 2) * basePower * attack / defense) / 50) + 2; // multi-target modifier (doubles only) if (move.spreadHit) { let spreadModifier = move.spreadModifier || 0.75; this.debug('Spread modifier: ' + spreadModifier); baseDamage = this.modify(baseDamage, spreadModifier); } // weather modifier baseDamage = this.runEvent('WeatherModifyDamage', pokemon, target, move, baseDamage); // crit if (move.crit) { baseDamage = this.modify(baseDamage, move.critModifier || (this.gen >= 6 ? 1.5 : 2)); } // this is not a modifier baseDamage = this.randomizer(baseDamage); // STAB if (move.hasSTAB || type !== '???' && pokemon.hasType(type)) { // The "???" type never gets STAB // Not even if you Roost in Gen 4 and somehow manage to use // Struggle in the same turn. // (On second thought, it might be easier to get a Missingno.) baseDamage = this.modify(baseDamage, move.stab || 1.5); } // types move.typeMod = target.runEffectiveness(move); move.typeMod = this.clampIntRange(move.typeMod, -6, 6); if (move.typeMod > 0) { if (!suppressMessages) this.add('-supereffective', target); for (let i = 0; i < move.typeMod; i++) { baseDamage *= 2; } } if (move.typeMod < 0) { if (!suppressMessages) this.add('-resisted', target); for (let i = 0; i > move.typeMod; i--) { baseDamage = Math.floor(baseDamage / 2); } } if (move.crit && !suppressMessages) this.add('-crit', target); if (pokemon.status === 'brn' && basePower && move.category === 'Physical' && !pokemon.hasAbility('guts')) { if (this.gen < 6 || move.id !== 'facade') { baseDamage = this.modify(baseDamage, 0.5); } } // Generation 5 sets damage to 1 before the final damage modifiers only if (this.gen === 5 && basePower && !Math.floor(baseDamage)) { baseDamage = 1; } // Final modifier. Modifiers that modify damage after min damage check, such as Life Orb. baseDamage = this.runEvent('ModifyDamage', pokemon, target, move, baseDamage); if (this.gen !== 5 && basePower && !Math.floor(baseDamage)) { return 1; } return Math.floor(baseDamage); }; Battle.prototype.randomizer = function (baseDamage) { return Math.floor(baseDamage * (100 - this.random(16)) / 100); }; /** * Returns whether a proposed target for a move is valid. */ Battle.prototype.validTargetLoc = function (targetLoc, source, targetType) { let numSlots = source.side.active.length; if (!Math.abs(targetLoc) && Math.abs(targetLoc) > numSlots) return false; let sourceLoc = -(source.position + 1); let isFoe = (targetLoc > 0); let isAdjacent = (isFoe ? Math.abs(-(numSlots + 1 - targetLoc) - sourceLoc) <= 1 : Math.abs(targetLoc - sourceLoc) === 1); let isSelf = (sourceLoc === targetLoc); switch (targetType) { case 'randomNormal': case 'normal': return isAdjacent; case 'adjacentAlly': return isAdjacent && !isFoe; case 'adjacentAllyOrSelf': return isAdjacent && !isFoe || isSelf; case 'adjacentFoe': return isAdjacent && isFoe; case 'any': return !isSelf; } return false; }; Battle.prototype.getTargetLoc = function (target, source) { if (target.side === source.side) { return -(target.position + 1); } else { return target.position + 1; } }; Battle.prototype.validTarget = function (target, source, targetType) { return this.validTargetLoc(this.getTargetLoc(target, source), source, targetType); }; Battle.prototype.getTarget = function (decision) { let move = this.getMove(decision.move); let target; if ((move.target !== 'randomNormal') && this.validTargetLoc(decision.targetLoc, decision.pokemon, move.target)) { if (decision.targetLoc > 0) { target = decision.pokemon.side.foe.active[decision.targetLoc - 1]; } else { target = decision.pokemon.side.active[-decision.targetLoc - 1]; } if (target) { if (!target.fainted) { // target exists and is not fainted return target; } else if (target.side === decision.pokemon.side) { // fainted allied targets don't retarget return false; } } // chosen target not valid, retarget randomly with resolveTarget } if (!decision.targetPosition || !decision.targetSide) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } return decision.targetSide.active[decision.targetPosition]; }; Battle.prototype.resolveTarget = function (pokemon, move) { // A move was used without a chosen target // For instance: Metronome chooses Ice Beam. Since the user didn't // choose a target when choosing Metronome, Ice Beam's target must // be chosen randomly. // The target is chosen randomly from possible targets, EXCEPT that // moves that can target either allies or foes will only target foes // when used without an explicit target. move = this.getMove(move); if (move.target === 'adjacentAlly') { let allyActives = pokemon.side.active; let adjacentAllies = [allyActives[pokemon.position - 1], allyActives[pokemon.position + 1]]; adjacentAllies = adjacentAllies.filter(active => active && !active.fainted); if (adjacentAllies.length) return adjacentAllies[Math.floor(Math.random() * adjacentAllies.length)]; return pokemon; } if (move.target === 'self' || move.target === 'all' || move.target === 'allySide' || move.target === 'allyTeam' || move.target === 'adjacentAllyOrSelf') { return pokemon; } if (pokemon.side.active.length > 2) { if (move.target === 'adjacentFoe' || move.target === 'normal' || move.target === 'randomNormal') { let foeActives = pokemon.side.foe.active; let frontPosition = foeActives.length - 1 - pokemon.position; let adjacentFoes = foeActives.slice(frontPosition < 1 ? 0 : frontPosition - 1, frontPosition + 2); adjacentFoes = adjacentFoes.filter(active => active && !active.fainted); if (adjacentFoes.length) return adjacentFoes[Math.floor(Math.random() * adjacentFoes.length)]; // no valid target at all, return a foe for any possible redirection } } return pokemon.side.foe.randomActive() || pokemon.side.foe.active[0]; }; Battle.prototype.checkFainted = function () { for (let i = 0; i < this.p1.active.length; i++) { let pokemon = this.p1.active[i]; if (pokemon.fainted) { pokemon.status = 'fnt'; pokemon.switchFlag = true; } } for (let i = 0; i < this.p2.active.length; i++) { let pokemon = this.p2.active[i]; if (pokemon.fainted) { pokemon.status = 'fnt'; pokemon.switchFlag = true; } } }; Battle.prototype.faintMessages = function (lastFirst) { if (this.ended) return; if (!this.faintQueue.length) return false; if (lastFirst) { this.faintQueue.unshift(this.faintQueue.pop()); } let faintData; while (this.faintQueue.length) { faintData = this.faintQueue.shift(); if (!faintData.target.fainted) { this.add('faint', faintData.target); this.runEvent('Faint', faintData.target, faintData.source, faintData.effect); this.singleEvent('End', this.getAbility(faintData.target.ability), faintData.target.abilityData, faintData.target); faintData.target.fainted = true; faintData.target.isActive = false; faintData.target.isStarted = false; faintData.target.side.pokemonLeft--; faintData.target.side.faintedThisTurn = true; } } if (this.gen <= 1) { // in gen 1, fainting skips the rest of the turn, including residuals this.queue = []; } else if (this.gen <= 3 && this.gameType === 'singles') { // in gen 3 or earlier, fainting in singles skips to residuals for (let i = 0; i < this.p1.active.length; i++) { this.cancelMove(this.p1.active[i]); // Stop Pursuit from running this.p1.active[i].moveThisTurn = true; } for (let i = 0; i < this.p2.active.length; i++) { this.cancelMove(this.p2.active[i]); // Stop Pursuit from running this.p2.active[i].moveThisTurn = true; } } if (!this.p1.pokemonLeft && !this.p2.pokemonLeft) { this.win(faintData && faintData.target.side); return true; } if (!this.p1.pokemonLeft) { this.win(this.p2); return true; } if (!this.p2.pokemonLeft) { this.win(this.p1); return true; } return false; }; Battle.prototype.resolvePriority = function (decision) { if (decision) { if (!decision.side && decision.pokemon) decision.side = decision.pokemon.side; if (!decision.choice && decision.move) decision.choice = 'move'; if (!decision.priority && decision.priority !== 0) { let priorities = { 'beforeTurn': 100, 'beforeTurnMove': 99, 'switch': 7, 'runSwitch': 7.2, 'runPrimal': 7.1, 'instaswitch': 101, 'megaEvo': 6.9, 'residual': -100, 'team': 102, 'start': 101, }; if (decision.choice in priorities) { decision.priority = priorities[decision.choice]; } } if (decision.choice === 'move') { if (this.getMove(decision.move).beforeTurnCallback) { this.addQueue({choice: 'beforeTurnMove', pokemon: decision.pokemon, move: decision.move, targetLoc: decision.targetLoc}); } } else if (decision.choice === 'switch' || decision.choice === 'instaswitch') { if (decision.pokemon.switchFlag && decision.pokemon.switchFlag !== true) { decision.pokemon.switchCopyFlag = decision.pokemon.switchFlag; } decision.pokemon.switchFlag = false; if (!decision.speed && decision.pokemon && decision.pokemon.isActive) decision.speed = decision.pokemon.speed; } if (decision.move) { let target; if (!decision.targetPosition) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } decision.move = this.getMoveCopy(decision.move); if (!decision.priority) { let priority = decision.move.priority; priority = this.runEvent('ModifyPriority', decision.pokemon, target, decision.move, priority); decision.priority = priority; // In Gen 6, Quick Guard blocks moves with artificially enhanced priority. if (this.gen > 5) decision.move.priority = priority; } } if (!decision.pokemon && !decision.speed) decision.speed = 1; if (!decision.speed && (decision.choice === 'switch' || decision.choice === 'instaswitch') && decision.target) decision.speed = decision.target.speed; if (!decision.speed) decision.speed = decision.pokemon.speed; } }; Battle.prototype.addQueue = function (decision) { if (Array.isArray(decision)) { for (let i = 0; i < decision.length; i++) { this.addQueue(decision[i]); } return; } this.resolvePriority(decision); this.queue.push(decision); }; Battle.prototype.sortQueue = function () { this.queue.sort(Battle.comparePriority); }; Battle.prototype.insertQueue = function (decision) { if (Array.isArray(decision)) { for (let i = 0; i < decision.length; i++) { this.insertQueue(decision[i]); } return; } if (decision.pokemon) decision.pokemon.updateSpeed(); this.resolvePriority(decision); for (let i = 0; i < this.queue.length; i++) { if (Battle.comparePriority(decision, this.queue[i]) < 0) { this.queue.splice(i, 0, decision); return; } } this.queue.push(decision); }; Battle.prototype.prioritizeQueue = function (decision, source, sourceEffect) { if (this.event) { if (!source) source = this.event.source; if (!sourceEffect) sourceEffect = this.effect; } for (let i = 0; i < this.queue.length; i++) { if (this.queue[i] === decision) { this.queue.splice(i, 1); break; } } decision.sourceEffect = sourceEffect; this.queue.unshift(decision); }; Battle.prototype.willAct = function () { for (let i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' || this.queue[i].choice === 'switch' || this.queue[i].choice === 'instaswitch' || this.queue[i].choice === 'shift') { return this.queue[i]; } } return null; }; Battle.prototype.willMove = function (pokemon) { for (let i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { return this.queue[i]; } } return null; }; Battle.prototype.cancelDecision = function (pokemon) { let success = false; for (let i = 0; i < this.queue.length; i++) { if (this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); i--; success = true; } } return success; }; Battle.prototype.cancelMove = function (pokemon) { for (let i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); return true; } } return false; }; Battle.prototype.willSwitch = function (pokemon) { for (let i = 0; i < this.queue.length; i++) { if ((this.queue[i].choice === 'switch' || this.queue[i].choice === 'instaswitch') && this.queue[i].pokemon === pokemon) { return this.queue[i]; } } return false; }; Battle.prototype.runDecision = function (decision) { // returns whether or not we ended in a callback switch (decision.choice) { case 'start': { // I GIVE UP, WILL WRESTLE WITH EVENT SYSTEM LATER let format = this.getFormat(); if (format.teamLength && format.teamLength.battle) { // Trim the team: not all of the Pokémon brought to Preview will battle. this.p1.pokemon = this.p1.pokemon.slice(0, format.teamLength.battle); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0, format.teamLength.battle); this.p2.pokemonLeft = this.p2.pokemon.length; } this.add('start'); for (let pos = 0; pos < this.p1.active.length; pos++) { this.switchIn(this.p1.pokemon[pos], pos); } for (let pos = 0; pos < this.p2.active.length; pos++) { this.switchIn(this.p2.pokemon[pos], pos); } for (let pos = 0; pos < this.p1.pokemon.length; pos++) { let pokemon = this.p1.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } for (let pos = 0; pos < this.p2.pokemon.length; pos++) { let pokemon = this.p2.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } this.midTurn = true; break; } case 'move': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.runMove(decision.move, decision.pokemon, this.getTarget(decision), decision.sourceEffect); break; case 'megaEvo': if (decision.pokemon.canMegaEvo) this.runMegaEvo(decision.pokemon); break; case 'beforeTurnMove': { if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.debug('before turn callback: ' + decision.move.id); let target = this.getTarget(decision); if (!target) return false; decision.move.beforeTurnCallback.call(this, decision.pokemon, target); break; } case 'event': this.runEvent(decision.event, decision.pokemon); break; case 'team': { let len = decision.side.pokemon.length; let newPokemon = [null, null, null, null, null, null].slice(0, len); for (let j = 0; j < len; j++) { let i = decision.team[j]; newPokemon[j] = decision.side.pokemon[i]; newPokemon[j].position = j; } decision.side.pokemon = newPokemon; // we return here because the update event would crash since there are no active pokemon yet return; } case 'pass': if (!decision.priority || decision.priority <= 101) return; if (decision.pokemon) { decision.pokemon.switchFlag = false; } break; case 'instaswitch': case 'switch': if (decision.choice === 'switch' && decision.pokemon.status && this.data.Abilities.naturalcure) { this.singleEvent('CheckShow', this.data.Abilities.naturalcure, null, decision.pokemon); } if (decision.pokemon.hp) { decision.pokemon.beingCalledBack = true; let lastMove = this.getMove(decision.pokemon.lastMove); if (lastMove.selfSwitch !== 'copyvolatile') { this.runEvent('BeforeSwitchOut', decision.pokemon); if (this.gen >= 5) { this.eachEvent('Update'); } } if (!this.runEvent('SwitchOut', decision.pokemon)) { // Warning: DO NOT interrupt a switch-out // if you just want to trap a pokemon. // To trap a pokemon and prevent it from switching out, // (e.g. Mean Look, Magnet Pull) use the 'trapped' flag // instead. // Note: Nothing in BW or earlier interrupts // a switch-out. break; } } this.singleEvent('End', this.getAbility(decision.pokemon.ability), decision.pokemon.abilityData, decision.pokemon); if (!decision.pokemon.hp && !decision.pokemon.fainted) { // a pokemon fainted from Pursuit before it could switch if (this.gen <= 4) { // in gen 2-4, the switch still happens decision.priority = -101; this.queue.unshift(decision); this.add('-hint', 'Pursuit target fainted, switch continues in gen 2-4'); break; } // in gen 5+, the switch is cancelled this.debug('A Pokemon can\'t switch between when it runs out of HP and when it faints'); break; } if (decision.target.isActive) { this.add('-hint', 'Switch failed; switch target is already active'); break; } if (decision.choice === 'switch' && decision.pokemon.activeTurns === 1) { let foeActive = decision.pokemon.side.foe.active; for (let i = 0; i < foeActive.length; i++) { if (foeActive[i].isStale >= 2) { decision.pokemon.isStaleCon++; decision.pokemon.isStaleSource = 'switch'; break; } } } this.switchIn(decision.target, decision.pokemon.position); break; case 'runSwitch': this.runEvent('SwitchIn', decision.pokemon); if (this.gen <= 2 && !decision.pokemon.side.faintedThisTurn && decision.pokemon.draggedIn !== this.turn) this.runEvent('AfterSwitchInSelf', decision.pokemon); if (!decision.pokemon.hp) break; decision.pokemon.isStarted = true; if (!decision.pokemon.fainted) { this.singleEvent('Start', decision.pokemon.getAbility(), decision.pokemon.abilityData, decision.pokemon); decision.pokemon.abilityOrder = this.abilityOrder++; this.singleEvent('Start', decision.pokemon.getItem(), decision.pokemon.itemData, decision.pokemon); } delete decision.pokemon.draggedIn; break; case 'runPrimal': this.singleEvent('Primal', decision.pokemon.getItem(), decision.pokemon.itemData, decision.pokemon); break; case 'shift': { if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; decision.pokemon.activeTurns--; this.swapPosition(decision.pokemon, 1); let foeActive = decision.pokemon.side.foe.active; for (let i = 0; i < foeActive.length; i++) { if (foeActive[i].isStale >= 2) { decision.pokemon.isStaleCon++; decision.pokemon.isStaleSource = 'switch'; break; } } break; } case 'beforeTurn': this.eachEvent('BeforeTurn'); break; case 'residual': this.add(''); this.clearActiveMove(true); this.updateSpeed(); this.residualEvent('Residual'); break; } // phazing (Roar, etc) for (let i = 0; i < this.p1.active.length; i++) { let pokemon = this.p1.active[i]; if (pokemon.forceSwitchFlag) { if (pokemon.hp) this.dragIn(pokemon.side, pokemon.position); pokemon.forceSwitchFlag = false; } } for (let i = 0; i < this.p2.active.length; i++) { let pokemon = this.p2.active[i]; if (pokemon.forceSwitchFlag) { if (pokemon.hp) this.dragIn(pokemon.side, pokemon.position); pokemon.forceSwitchFlag = false; } } this.clearActiveMove(); // fainting this.faintMessages(); if (this.ended) return true; // switching (fainted pokemon, U-turn, Baton Pass, etc) if (!this.queue.length || (this.gen <= 3 && this.queue[0].choice in {move:1, residual:1})) { // in gen 3 or earlier, switching in fainted pokemon is done after // every move, rather than only at the end of the turn. this.checkFainted(); } else if (decision.choice === 'pass') { this.eachEvent('Update'); return false; } let p1switch = this.p1.active.some(mon => mon && mon.switchFlag); let p2switch = this.p2.active.some(mon => mon && mon.switchFlag); if (p1switch && !this.canSwitch(this.p1)) { for (let i = 0; i < this.p1.active.length; i++) { this.p1.active[i].switchFlag = false; } p1switch = false; } if (p2switch && !this.canSwitch(this.p2)) { for (let i = 0; i < this.p2.active.length; i++) { this.p2.active[i].switchFlag = false; } p2switch = false; } if (p1switch || p2switch) { if (this.gen >= 5) { this.eachEvent('Update'); } this.makeRequest('switch'); return true; } this.eachEvent('Update'); return false; }; Battle.prototype.go = function () { this.add(''); if (this.currentRequest) { this.currentRequest = ''; this.currentRequestDetails = ''; } if (!this.midTurn) { this.queue.push({choice: 'residual', priority: -100}); this.queue.unshift({choice: 'beforeTurn', priority: 100}); this.midTurn = true; } while (this.queue.length) { let decision = this.queue.shift(); this.runDecision(decision); if (this.currentRequest) { return; } if (this.ended) return; } this.nextTurn(); this.midTurn = false; this.queue = []; }; /** * Changes a pokemon's decision, and inserts its new decision * in priority order. * * You'd normally want the OverrideDecision event (which doesn't * change priority order). */ Battle.prototype.changeDecision = function (pokemon, decision) { this.cancelDecision(pokemon); if (!decision.pokemon) decision.pokemon = pokemon; this.insertQueue(decision); }; /** * Takes a choice string passed from the client. Starts the next * turn if all required choices have been made. */ Battle.prototype.choose = function (sideid, choice, rqid) { let side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // This condition should be impossible because the sideid comes // from our forked process and if the player id were invalid, we would // not have even got to this function. if (!side) return; // wtf // This condition can occur if the client sends a decision at the // wrong time. if (!side.currentRequest) return; // Make sure the decision is for the right request. if ((rqid !== undefined) && (parseInt(rqid) !== this.rqid)) { return; } if (side.decision && side.decision.finalDecision) { this.debug("Can't override decision: the last pokemon could have been trapped or disabled"); return; } side.decision = this.parseChoice(choice.split(','), side); side.choice = choice; if (this.p1.decision && this.p2.decision) { this.commitDecisions(); } }; Battle.prototype.commitDecisions = function () { this.updateSpeed(); let oldQueue = this.queue; this.queue = []; for (let i = 0; i < this.sides.length; i++) { this.sides[i].resolveDecision(); if (this.sides[i].decision === true) continue; this.addQueue(this.sides[i].decision); } this.add('choice', this.p1.getChoice, this.p2.getChoice); this.sortQueue(); Array.prototype.push.apply(this.queue, oldQueue); this.currentRequest = ''; this.currentRequestDetails = ''; this.p1.currentRequest = ''; this.p2.currentRequest = ''; this.p1.decision = true; this.p2.decision = true; this.go(); }; Battle.prototype.undoChoice = function (sideid) { let side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // The following condition can never occur for the reasons given in // the choose() function above. if (!side) return; // wtf // This condition can occur. if (!side.currentRequest) return; if (side.decision && side.decision.finalDecision) { this.debug("Can't cancel decision: the last pokemon could have been trapped or disabled"); return; } side.decision = false; }; /** * Parses a choice string passed from a client into a decision object * usable by PS's engine. * * Choice validation is also done here. */ Battle.prototype.parseChoice = function (choices, side) { let prevSwitches = {}; if (!side.currentRequest) return true; if (typeof choices === 'string') choices = choices.split(','); let decisions = []; let len = choices.length; if (side.currentRequest !== 'teampreview') len = side.active.length; let isDefault; let choosableTargets = {normal:1, any:1, adjacentAlly:1, adjacentAllyOrSelf:1, adjacentFoe:1}; let freeSwitchCount = {'switch':0, 'pass':0}; if (side.currentRequest === 'switch') { let canSwitch = side.active.filter(mon => mon && mon.switchFlag).length; let canSwitchIn = side.pokemon.slice(side.active.length).filter(mon => !mon.fainted).length; freeSwitchCount['switch'] = Math.min(canSwitch, canSwitchIn); freeSwitchCount['pass'] = canSwitch - freeSwitchCount['switch']; } for (let i = 0; i < len; i++) { let choice = (choices[i] || '').trim(); let data = ''; let firstSpaceIndex = choice.indexOf(' '); if (firstSpaceIndex >= 0) { data = choice.substr(firstSpaceIndex + 1).trim(); choice = choice.substr(0, firstSpaceIndex).trim(); } let pokemon = side.pokemon[i]; switch (side.currentRequest) { case 'teampreview': if (choice !== 'team' || i > 0) return false; break; case 'move': { if (i >= side.active.length) return false; if (!pokemon || pokemon.fainted) { decisions.push({ choice: 'pass', }); continue; } let lockedMove = pokemon.getLockedMove(); if (lockedMove) { decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: this.runEvent('LockMoveTarget', pokemon) || 0, move: lockedMove, }); continue; } if (isDefault || choice === 'default') { isDefault = true; let moves = pokemon.getMoves(); let moveid = 'struggle'; for (let j = 0; j < moves.length; j++) { if (moves[j].disabled) continue; moveid = moves[j].id; break; } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: 0, move: moveid, }); continue; } if (choice !== 'move' && choice !== 'switch' && choice !== 'shift') { if (i === 0) return false; // fallback choice = 'move'; data = '1'; } break; } case 'switch': if (i >= side.active.length) return false; if (!side.active[i] || !side.active[i].switchFlag) { if (choice !== 'pass') choices.splice(i, 0, 'pass'); decisions.push({ choice: 'pass', pokemon: side.active[i], priority: 102, }); continue; } if (choice !== 'switch' && choice !== 'pass') return false; freeSwitchCount[choice]--; break; default: return false; } switch (choice) { case 'team': { let pokemonLength = side.pokemon.length; if (!data || data.length > pokemonLength) return false; let dataArr = [0, 1, 2, 3, 4, 5].slice(0, pokemonLength); let slotMap = dataArr.slice(); // Inverse of `dataArr` (slotMap[dataArr[x]] === x) for (let j = 0; j < data.length; j++) { let slot = parseInt(data.charAt(j)) - 1; if (slotMap[slot] < j) return false; if (isNaN(slot) || slot < 0 || slot >= pokemonLength) return false; // Keep track of team order so far let tempSlot = dataArr[j]; dataArr[j] = slot; dataArr[slotMap[slot]] = tempSlot; // Update its inverse slotMap[tempSlot] = slotMap[slot]; slotMap[slot] = j; } decisions.push({ choice: 'team', side: side, team: dataArr, }); break; } case 'switch': if (i > side.active.length || i > side.pokemon.length) continue; data = parseInt(data) - 1; if (data < 0) data = 0; if (data > side.pokemon.length - 1) data = side.pokemon.length - 1; if (!side.pokemon[data]) { this.debug("Can't switch: You can't switch to a pokemon that doesn't exist"); return false; } if (data === i) { this.debug("Can't switch: You can't switch to yourself"); return false; } if (data < side.active.length) { this.debug("Can't switch: You can't switch to an active pokemon"); return false; } if (side.pokemon[data].fainted) { this.debug("Can't switch: You can't switch to a fainted pokemon"); return false; } if (prevSwitches[data]) { this.debug("Can't switch: You can't switch to pokemon already queued to be switched"); return false; } prevSwitches[data] = true; if (side.currentRequest === 'move') { if (side.pokemon[i].trapped) { //this.debug("Can't switch: The active pokemon is trapped"); side.emitCallback('trapped', i); return false; } else if (side.pokemon[i].maybeTrapped) { decisions.finalDecision = decisions.finalDecision || side.pokemon[i].isLastActive(); } } decisions.push({ choice: (side.currentRequest === 'switch' ? 'instaswitch' : 'switch'), pokemon: side.pokemon[i], target: side.pokemon[data], }); break; case 'shift': if (i > side.active.length || i > side.pokemon.length) continue; if (this.gameType !== 'triples') { this.debug("Can't shift: You can't shift a pokemon to the center except in a triple battle"); return false; } if (i === 1) { this.debug("Can't shift: You can't shift a pokemon to its own position"); return false; } decisions.push({ choice: 'shift', pokemon: side.pokemon[i], }); break; case 'move': { let moveid = ''; let targetLoc = 0; pokemon = side.pokemon[i]; if (data.substr(-2) === ' 1') targetLoc = 1; if (data.substr(-2) === ' 2') targetLoc = 2; if (data.substr(-2) === ' 3') targetLoc = 3; if (data.substr(-3) === ' -1') targetLoc = -1; if (data.substr(-3) === ' -2') targetLoc = -2; if (data.substr(-3) === ' -3') targetLoc = -3; if (targetLoc) data = data.substr(0, data.lastIndexOf(' ')); if (data.substr(-5) === ' mega') { decisions.push({ choice: 'megaEvo', pokemon: pokemon, }); data = data.substr(0, data.length - 5); } /** * Parse the move identifier (name or index), according to the request sent to the client. * If the move is not found, the decision is invalid without requiring further inspection. */ let requestMoves = pokemon.getRequestData().moves; if (data.search(/^[0-9]+$/) >= 0) { // parse a one-based move index let moveIndex = parseInt(data) - 1; if (!requestMoves[moveIndex]) { this.debug("Can't use an unexpected move"); return false; } moveid = requestMoves[moveIndex].id; if (!targetLoc && side.active.length > 1 && requestMoves[moveIndex].target in choosableTargets) { this.debug("Can't use the move without a target"); return false; } } else { // parse a move name moveid = toId(data); if (moveid.substr(0, 11) === 'hiddenpower') { moveid = 'hiddenpower'; } let isValidMove = false; for (let j = 0; j < requestMoves.length; j++) { if (requestMoves[j].id !== moveid) continue; if (!targetLoc && side.active.length > 1 && requestMoves[j].target in choosableTargets) { this.debug("Can't use the move without a target"); return false; } isValidMove = true; break; } if (!isValidMove) { this.debug("Can't use an unexpected move"); return false; } } /** * Check whether the chosen move is really valid, accounting for effects active in battle, * which could be unknown for the client. */ let moves = pokemon.getMoves(); if (!moves.length) { // Override decision and use Struggle if there are no enabled moves with PP if (this.gen <= 4) side.send('-activate', pokemon, 'move: Struggle'); moveid = 'struggle'; } else { // At least a move is valid. Check if the chosen one is. // This may include Struggle in Hackmons. let isEnabled = false; let disabledSource = ''; for (let j = 0; j < moves.length; j++) { if (moves[j].id !== moveid) continue; if (!moves[j].disabled) { isEnabled = true; break; } else if (moves[j].disabledSource) { disabledSource = moves[j].disabledSource; } } if (!isEnabled) { // request a different choice side.emitCallback('cant', pokemon, disabledSource, moveid); return false; } // the chosen move is valid } if (pokemon.maybeDisabled) { decisions.finalDecision = decisions.finalDecision || pokemon.isLastActive(); } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: targetLoc, move: moveid, }); break; } case 'pass': if (i > side.active.length || i > side.pokemon.length) continue; if (side.currentRequest !== 'switch') { this.debug("Can't pass the turn"); return false; } decisions.push({ choice: 'pass', priority: 102, pokemon: side.active[i], }); } } if (freeSwitchCount['switch'] !== 0 || freeSwitchCount['pass'] !== 0) return false; if (!this.supportCancel || isDefault) decisions.finalDecision = true; return decisions; }; Battle.prototype.add = function () { let parts = Array.prototype.slice.call(arguments); if (!parts.some(part => typeof part === 'function')) { this.log.push('|' + parts.join('|')); return; } this.log.push('|split'); let sides = [null, this.sides[0], this.sides[1], true]; for (let i = 0; i < sides.length; ++i) { let sideUpdate = '|' + parts.map(part => { if (typeof part !== 'function') return part; return part(sides[i]); }).join('|'); this.log.push(sideUpdate); } }; Battle.prototype.addMove = function () { this.lastMoveLine = this.log.length; this.log.push('|' + Array.prototype.slice.call(arguments).join('|')); }; Battle.prototype.attrLastMove = function () { this.log[this.lastMoveLine] += '|' + Array.prototype.slice.call(arguments).join('|'); }; Battle.prototype.debug = function (activity) { if (this.getFormat().debug) { this.add('debug', activity); } }; Battle.prototype.debugError = function (activity) { this.add('debug', activity); }; // players Battle.prototype.join = function (slot, name, avatar, team) { if (this.p1 && this.p1.isActive && this.p2 && this.p2.isActive) return false; if ((this.p1 && this.p1.isActive && this.p1.name === name) || (this.p2 && this.p2.isActive && this.p2.name === name)) return false; if (this.p1 && this.p1.isActive || slot === 'p2') { if (this.started) { this.p2.name = name; } else { //console.log("NEW SIDE: " + name); this.p2 = new BattleSide(name, this, 1, team); this.sides[1] = this.p2; } if (avatar) this.p2.avatar = avatar; this.p2.isActive = true; this.add('player', 'p2', this.p2.name, avatar); } else { if (this.started) { this.p1.name = name; } else { //console.log("NEW SIDE: " + name); this.p1 = new BattleSide(name, this, 0, team); this.sides[0] = this.p1; } if (avatar) this.p1.avatar = avatar; this.p1.isActive = true; this.add('player', 'p1', this.p1.name, avatar); } this.start(); return true; }; Battle.prototype.rename = function (slot, name, avatar) { if (slot === 'p1' || slot === 'p2') { let side = this[slot]; side.name = name; if (avatar) side.avatar = avatar; this.add('player', slot, name, side.avatar); } }; Battle.prototype.leave = function (slot) { if (slot === 'p1' || slot === 'p2') { let side = this[slot]; if (!side) { console.log('**** ' + slot + ' tried to leave before it was possible in ' + this.id); require('./crashlogger.js')(new Error('**** ' + slot + ' tried to leave before it was possible in ' + this.id), 'A simulator process'); return; } side.emitRequest(null); side.isActive = false; this.add('player', slot); this.active = false; } return true; }; // IPC // Messages sent by this function are received and handled in // Battle.prototype.receive in simulator.js (in another process). Battle.prototype.send = function (type, data) { if (Array.isArray(data)) data = data.join("\n"); process.send(this.id + "\n" + type + "\n" + data); }; // This function is called by this process's 'message' event. Battle.prototype.receive = function (data, more) { this.messageLog.push(data.join(' ')); let logPos = this.log.length; let alreadyEnded = this.ended; switch (data[1]) { case 'join': { let team = ''; try { if (more) team = Tools.fastUnpackTeam(more); } catch (e) { console.log('TEAM PARSE ERROR: ' + more); team = null; } this.join(data[2], data[3], data[4], team); break; } case 'rename': this.rename(data[2], data[3], data[4]); break; case 'leave': this.leave(data[2]); break; case 'chat': this.add('chat', data[2], more); break; case 'win': case 'tie': this.win(data[2]); break; case 'choose': this.choose(data[2], data[3], data[4]); break; case 'undo': this.undoChoice(data[2]); break; case 'eval': { /* eslint-disable no-eval, no-unused-vars */ let battle = this; let p1 = this.p1; let p2 = this.p2; let p1active = p1 ? p1.active[0] : null; let p2active = p2 ? p2.active[0] : null; let target = data.slice(2).join('|').replace(/\f/g, '\n'); this.add('', '>>> ' + target); try { this.add('', '<<< ' + eval(target)); } catch (e) { this.add('', '<<< error: ' + e.message); } /* eslint-enable no-eval, no-unused-vars */ break; } default: // unhandled } this.sendUpdates(logPos, alreadyEnded); }; Battle.prototype.sendUpdates = function (logPos, alreadyEnded) { if (this.p1 && this.p2) { let inactiveSide = -1; if (!this.p1.isActive && this.p2.isActive) { inactiveSide = 0; } else if (this.p1.isActive && !this.p2.isActive) { inactiveSide = 1; } else if (!this.p1.decision && this.p2.decision) { inactiveSide = 0; } else if (this.p1.decision && !this.p2.decision) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (this.log.length > logPos) { if (alreadyEnded !== undefined && this.ended && !alreadyEnded) { if (this.rated || Config.logchallenges) { let log = { seed: this.startingSeed, turns: this.turn, p1: this.p1.name, p2: this.p2.name, p1team: this.p1.team, p2team: this.p2.team, log: this.log, }; this.send('log', JSON.stringify(log)); } this.send('score', [this.p1.pokemonLeft, this.p2.pokemonLeft]); this.send('winupdate', [this.winner].concat(this.log.slice(logPos))); } else { this.send('update', this.log.slice(logPos)); } } }; Battle.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (let i = 0; i < this.sides.length; i++) { if (this.sides[i]) this.sides[i].destroy(); this.sides[i] = null; } this.p1 = null; this.p2 = null; for (let i = 0; i < this.queue.length; i++) { delete this.queue[i].pokemon; delete this.queue[i].side; this.queue[i] = null; } this.queue = null; // in case the garbage collector really sucks, at least deallocate the log this.log = null; // remove from battle list Battles[this.id] = null; }; return Battle; })(); exports.BattlePokemon = BattlePokemon; exports.BattleSide = BattleSide; exports.Battle = Battle;
{ "content_hash": "d23151c30d846ac4bcc96243b937e2a0", "timestamp": "", "source": "github", "line_count": 4810, "max_line_length": 222, "avg_line_length": 33.22806652806653, "alnum_prop": 0.6441151995595238, "repo_name": "kuroscafe/Showdown-Boilerplate", "id": "08f8101fb5bffae960cb0b29d08d62508caabc1d", "size": "159829", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "battle-engine.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1055" }, { "name": "CSS", "bytes": "8845" }, { "name": "HTML", "bytes": "655" }, { "name": "JavaScript", "bytes": "6184991" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- For detailed information on each of the elements that can be used in this descriptor please see the Coherence Cache Configuration deployment descriptor guide included in the Coherence distribution or on the web at: http://www.tangosol.com/UserGuide-Reference-CacheConfig.jsp --> <!DOCTYPE cache-config SYSTEM "cache-config.dtd"> <cache-config> <caching-schemes> <!-- scheme for partitioned cache --> <distributed-scheme> <scheme-name>distributed</scheme-name> <service-name>DistributedCache</service-name> <backing-map-scheme> <local-scheme> <scheme-ref>default-backing-map</scheme-ref> </local-scheme> </backing-map-scheme> <!--<autostart>true</autostart>--> </distributed-scheme> <!-- Default Replicated caching scheme --> <replicated-scheme> <scheme-name>replicated</scheme-name> <service-name>ReplicatedCache</service-name> <backing-map-scheme> <local-scheme> <scheme-ref>default-backing-map</scheme-ref> </local-scheme> </backing-map-scheme> </replicated-scheme> <!-- scheme for partitioned cache fronted by near cache --> <near-scheme> <scheme-name>near-distributed</scheme-name> <front-scheme> <local-scheme> <eviction-policy>LRU</eviction-policy> <high-units>{near-size-high 1000}</high-units> <low-units>{near-size-low 900}</low-units> <expiry-delay>{near-expiry 5s}</expiry-delay> <flush-delay>{near-flush 0}</flush-delay> </local-scheme> </front-scheme> <back-scheme> <distributed-scheme> <scheme-ref>{distributed-scheme-name distributed}</scheme-ref> </distributed-scheme> </back-scheme> <invalidation-strategy>{near-invalidation-strategy none}</invalidation-strategy> <!--<autostart>true</autostart>--> </near-scheme> <!-- Optimistic caching scheme. --> <optimistic-scheme> <scheme-name>optimistic</scheme-name> <service-name>OptimisticCache</service-name> <backing-map-scheme> <local-scheme> <scheme-ref>default-backing-map</scheme-ref> </local-scheme> </backing-map-scheme> <!--<autostart>true</autostart>--> </optimistic-scheme> <local-scheme> <scheme-name>default-backing-map</scheme-name> <class-name>{backing-map-class com.jivesoftware.util.cache.CoherenceCache}</class-name> <eviction-policy>LRU</eviction-policy> <high-units>{back-size-high 1000}</high-units> <low-units>{back-size-low 900}</low-units> <expiry-delay>{back-expiry 0}</expiry-delay> <flush-delay>{back-flush 1m}</flush-delay> </local-scheme> <!-- scheme for service allowing cluster wide tasks --> <invocation-scheme> <scheme-name>OpenFire Cluster Service</scheme-name> <service-name>OpenFire Cluster Service</service-name> <autostart>true</autostart> </invocation-scheme> </caching-schemes> <caching-scheme-mapping> <!-- local caches --> <cache-mapping> <cache-name>POP3 Authentication</cache-name> <scheme-name>default-backing-map</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>1h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>LDAP Authentication</cache-name> <scheme-name>default-backing-map</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>2h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>File Transfer</cache-name> <scheme-name>default-backing-map</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>File Transfer Cache</cache-name> <scheme-name>default-backing-map</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <!-- optimistic caches --> <!-- replicated caches --> <cache-mapping> <cache-name>opt-$cacheStats</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Clearspace SSO Nonce</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>2m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Client Session Info Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Javascript Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>262144</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>10d</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>235930</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Components Sessions</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Connection Managers Sessions</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Secret Keys Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Validated Domains</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Disco Server Features</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Disco Server Items</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Incoming Server Sessions</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Sessions by Hostname</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Entity Capabilities</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>48h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Routing Servers Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Routing Components Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Routing Users Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Routing AnonymousUsers Cache</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Directed Presences</cache-name> <scheme-name>replicated</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <!-- partitioned caches --> <cache-mapping> <cache-name>Group Metadata Cache</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>5242880</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>15m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Routing User Sessions</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>VCard</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>10485760</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> <init-param> <param-name>near-invalidation-strategy</param-name> <param-value>present</param-value> </init-param> <init-param> <param-name>near-expiry</param-name> <param-value>30m</param-value> </init-param> <init-param> <param-name>near-size-high</param-name> <param-value>10000</param-value> </init-param> <init-param> <param-name>near-size-low</param-name> <param-value>9000</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Favicon Hits</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>262144</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>235930</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Favicon Misses</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>262144</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>235930</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Group</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>1048576</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>15m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Locked Out Accounts</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>1048576</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>15m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Last Activity Cache</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Multicast Service</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>24h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Offline Message Size</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>262144</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>12h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>235930</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Offline Presence Cache</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>1048576</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Privacy Lists</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>1048576</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Roster</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>10485760</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>6h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>User</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>10485760</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>30m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>943718</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Remote Users Existence</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Remote Server Configurations</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>524288</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>30m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>471859</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>Entity Capabilities Users</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>48h</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>0</param-value> </init-param> </init-params> </cache-mapping> <cache-mapping> <cache-name>PEPServiceManager</cache-name> <scheme-name>near-distributed</scheme-name> <init-params> <init-param> <param-name>back-size-high</param-name> <param-value>4000</param-value> </init-param> <init-param> <param-name>back-expiry</param-name> <param-value>30m</param-value> </init-param> <init-param> <param-name>back-size-low</param-name> <param-value>3000</param-value> </init-param> </init-params> </cache-mapping> </caching-scheme-mapping> </cache-config>
{ "content_hash": "19aae1880c1e41f6b02952bc6d86acfc", "timestamp": "", "source": "github", "line_count": 888, "max_line_length": 99, "avg_line_length": 38.332207207207205, "alnum_prop": 0.4481917800170393, "repo_name": "eraserx99/OF", "id": "bdddbaab9a13387a11218b19c1b97d689a8a85c2", "size": "34039", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/plugins/clustering/coherence-cache-config.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3814" }, { "name": "D", "bytes": "2290" }, { "name": "Java", "bytes": "8646310" }, { "name": "JavaScript", "bytes": "220259" }, { "name": "Objective-C", "bytes": "6879" }, { "name": "Shell", "bytes": "6389" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e049dbd427235937d38864a7d0501333", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "a40e5e53c20e536065113f682b948c41e9dcf477", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Lasianthus/Lasianthus attenuatus/ Syn. Mephitidia plagiophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
layout: post sections: [Git] title: "Ventajas de usar GIT" date: 2017-09-13 desc: "." keywords: "git, GitHub, BitBucket" categories: [arquitectura] tags: [git, GitHub, BitBucket] icon: fas fa-university image: static/img/blog/docker/docker-logo.png --- https://codeburst.io/git-and-github-in-a-nutshell-b0a3cc06458f https://dzone.com/articles/gitlab-vs-github-for-open-source-projects?edition=358115&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=Daily%20Digest%202018-02-03 # ¿Qué es Git? # Un sistema distribuido de control de versiones # ¿Qué es GitHub? # GitHub es una plataforma de alojamiento de código para el control de versiones y la colaboración. Le permite a usted ya otros trabajar juntos en proyectos desde cualquier lugar. Buenos días, Pensando en la mejora de los procesos de desarrollo de SATEC, quiero proponer que se estudie la posibilidad de **usar git con gitHub** como repositorio para algún piloto o nuevos proyectos de SATEC. A continuación, explico algunas las razones por las que creo que esto es conveniente: - **Espacio**: Tu repositorio de Subversión acumula ramas de desarrollo difuntas que ocupan espacio aunque ya no se necesitan. En git, el repositorio central sólo necesita guardar lo que realmente está terminado y funcionando. Con git no hay miedo a estar trabajando en distintas ramas a la vez, ya que el espacio que requiere es insignificante, con SVN puedes hacer lo mismo pero tardarías mucho más en realizar copias y ocuparía bastante más. El tamaño que ocupa el repositorio es menor, ya que cada vez que haces commit se crea un tag pero solo con los cambios con respecto al tag anterior. - **Backups**: Se puede decir que git al ser distribuido, cada copia en una maquina es un backup completo del repositorio central. - **Gestión de ramas y agilidad**: Es más fácil crear y gestionar las ramas en local, lo cual te permite estar haciendo el desarrollo de un requisito y si las prioridades cambian, guardar la rama con estas modificaciones en local y volver muy rápidamente a la rama principal para desarrollar la nueva prioridad. Facilitando el poder volver e incorporar el desarrollo que dejaste parado en paralelo y haciéndonos mucho más agiles a los cambios. En sistemas como SVN a veces volver a la versión estable anterior es muy difícil, Con Git es más fácil revisar el histórico de cambios viendo de golpe todos los ficheros que se cambiaron en un única subida y pudiendo ver el resumen de cambios, esto debido a su naturaleza de commits incrementales, ya que cada tag es sobre un commit completo del repositorio y no de archivos sueltos de este, con SVN para hacer lo mismo tienes que recurrir a programas de terceros como sonar, que registran los últimos cambios para mostrártelos más como lo hace GIT. - **Asegurar la integridad del desarrollo**: Una de las cualidades de Git es que no puedes hacer commit a una rama sin haber integrado primero los cambios de esta en la rama que quieres subir. Con esto aseguras que tus cambios están incorporados y que si has probado correctamente la integración, aseguras que tu commit no rompe la integridad del proyecto. - **Problemas con el repositorio central**. Ante una caída de la red, puedes seguir haciendo commits de tus cambios al repositorio local sin miedo a perderlos y pudiendo volver atrás sin problemas. Con SVN a menos que tengas configurado el guardado de histórico de las últimas horas esto no sería posible y aún así puedes perder los cambios, con Git esto no te pasará nunca. - **Gestión del proyecto con plataforma Github**. 1. **Revisión de la integración de los cambios por el responsable técnico (El pull request)**. Una ventaja en el ámbito de git es el pull request. Es un flujo de trabajo en que un desarrollador dice que ha terminado algo y pide al jefe de integrarlo en la rama de release. Antes unas cuantas personas más pueden dar su acuerdo o incluso añadir nuevos commits con cambios. Esta funcionalidad no es de git mismo, sino un software adicional que ofrecen servidores para proyectos en git como GitHub. 2. **Tablero de gestión del proyecto**. Desde github, puedes tener un tablero kamban, donde analizar el backlog, las tareas en curso, pendientes, etc. 3. **Gestion de releases** Se puede realizar de una manera muy sencilla que luego pueden ser usadas en la integración continua con herramientas como Jenkins. 4. **Gestión de Issues** También la herramienta permite abrir y reportar solicitudes de cambios y errores detectados e incluye una manera de gestionarlos y documentarlos en las releases. - **Mercado actual:** Es una tecnología muy madura que lleva bastante tiempo en uso, existe desde 2005. Git lo usan los grandes como google, facebook, twitter, android y es fácil que los clientes lo empiecen a incorporar en sus infraestructuras, lo cual si no empezamos a usarlo en la empresa nos iria dejando rezagados contra otros competidores que ya estén acostumbrados a trabajar bien con este sistema. A nivel social, cada día está más en auge usar git, sobre todo desde plataformas web como GitHub o BitBucket. Es una manera muy buena de crear infraestructuras comunity, para que personas de todo el mundo se involucren en el desarrollo de proyectos. Esto quiere decir que los nuevos profesionales están aumentando su uso y reduciendo su curva de aprendizaje. Lo usan para mejorar sus herramientas de trabajo, tener software propio y fiable disponible, poder publicarlo y que otros participen en su mejora. Poder mostrar el conocimiento y la valía de estos profesionales, al poder mostrar directamente su trabajo. Incluso muchas empresas piden la cuenta de github del candidato para estudiar su trabajo durante las campañas de selección de personal. Las empresas y frameworks que todos conocemos usan esta vía para sus desarrollos: Spring, BonitaSoft, Angular, Android, Google, linux ... Lo cual nos obliga como profesionales el hacer uso de este tipo de repositorios sin ninguna duda. Para finalizar y desde mi experiencia personal lo recomiendo encarecidamente, sobre todo con plataformas como **gitHub o BitBucket**, sobre todo por la potencia que tiene para generar entregas rápidas, generar tags y releases y la facilidad de gestión del repositorio. Llevo más de un año usándolo como herramienta para mejorar mi visibilidad profesional, aprender, recopilar desarrollos, herramientas y acceder a las publicaciones de los frameworks que uso y estoy encantado, es más creo que es imprescindible su uso para el trabajo del día a día. Esto que comento a nivel personal se puede extrapolar al nivel de la empresa mostrando algún proyecto/producto que queramos montar con la filosofía comunity. De este modo podríamos contar con una comunidad que de ideas e incluso nos ayude con la codificación, pruebas, feedback de uso de un producto que luego queramos vender o dar soporte de modo privado, como hacen empresas como JBOSS o Bonitasoft. Esto mejoraría la imagen de la empresa, ayudaría a darse a conocer e introducirse como servicio de implantación de nuevas soluciones. Saludos cordiales ## Referencias ## https://git-scm.com/
{ "content_hash": "a34f4d9a0b0d9846e17ec907a609b5aa", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 550, "avg_line_length": 70.22549019607843, "alnum_prop": 0.7940806924472986, "repo_name": "javiermartinalonso/javiermartinalonso.github.io", "id": "e510b0f99eebbd188b041cc39f0b87c6cd108088", "size": "7246", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "drafts/DEV-OPS/vagrant/2017-09-13-Ventajas de usar GIT.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "523002" }, { "name": "Dockerfile", "bytes": "5738" }, { "name": "Groovy", "bytes": "124928" }, { "name": "HTML", "bytes": "1141593" }, { "name": "Java", "bytes": "21211" }, { "name": "JavaScript", "bytes": "619224" }, { "name": "PHP", "bytes": "868" }, { "name": "PLpgSQL", "bytes": "20580657" }, { "name": "Ruby", "bytes": "913" }, { "name": "SQLPL", "bytes": "21003" }, { "name": "Shell", "bytes": "20955" }, { "name": "TSQL", "bytes": "3850" } ], "symlink_target": "" }
package org.apache.directory.api.asn1.ber.grammar; import org.apache.directory.api.asn1.ber.Asn1Container; /** * A top level grammar class that store meta informations about the actions. * Those informations are not mandatory, but they can be useful for debugging. * * @param C The container type * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public abstract class GrammarAction<C extends Asn1Container> implements Action<C> { /** The action's name */ protected String name; /** A default constructor */ public GrammarAction() { } /** * Creates a new GrammarAction object. * * @param name The name of the grammar action */ public GrammarAction( String name ) { this.name = name; } /** * Prints the action's name * * @return The action's name */ public String toString() { return name; } }
{ "content_hash": "f97852ec6a2ee69784c98c08d11eedcb", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 81, "avg_line_length": 20.0625, "alnum_prop": 0.6344755970924195, "repo_name": "darranl/directory-shared", "id": "a0e904497424aad0b39b6e3ef3e43ba888f29101", "size": "1790", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "asn1/ber/src/main/java/org/apache/directory/api/asn1/ber/grammar/GrammarAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "195655" }, { "name": "Java", "bytes": "10377937" }, { "name": "XSLT", "bytes": "1674" } ], "symlink_target": "" }
import {Field} from './field.model'; export interface Catalog { identifier: string; name: string; description?: string; fields: Field[]; createdBy?: string; createdOn?: string; lastModifiedBy?: string; lastModifiedOn?: string; }
{ "content_hash": "3bddc3a3bf5bd6c62b9ac261d5e86e44", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 36, "avg_line_length": 17.714285714285715, "alnum_prop": 0.6895161290322581, "repo_name": "mifosio/fims-web-app", "id": "4e4649992101f422875add728cdc60d749d06dec", "size": "849", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/app/services/catalog/domain/catalog.model.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9175" }, { "name": "HTML", "bytes": "392320" }, { "name": "JavaScript", "bytes": "3031" }, { "name": "TypeScript", "bytes": "1875420" } ], "symlink_target": "" }
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <arrow-glib/array.hpp> #include <arrow-glib/buffer.hpp> #include <arrow-glib/compute.hpp> #include <arrow-glib/data-type.hpp> #include <arrow-glib/error.hpp> #include <arrow-glib/type.hpp> G_BEGIN_DECLS /** * SECTION: composite-array * @section_id: composite-array-classes * @title: Composite array classes * @include: arrow-glib/arrow-glib.h * * #GArrowListArray is a class for list array. It can store zero or * more list data. If you don't have Arrow format data, you need to * use #GArrowListArrayBuilder to create a new array. * * #GArrowLargeListArray is a class for 64-bit offsets list array. * It can store zero or more list data. If you don't have Arrow format data, * you need to use #GArrowLargeListArrayBuilder to create a new array. * * #GArrowStructArray is a class for struct array. It can store zero * or more structs. One struct has one or more fields. If you don't * have Arrow format data, you need to use #GArrowStructArrayBuilder * to create a new array. * * #GArrowMapArray is a class for map array. It can store * data with keys and items. * * #GArrowUnionArray is a base class for union array. It can store * zero or more unions. One union has one or more fields but one union * can store only one field value. * * #GArrowDenseUnionArray is a class for dense union array. * * #GArrowSparseUnionArray is a class for sparse union array. * * #GArrowDictionaryArray is a class for dictionary array. It can * store data with dictionary and indices. It's space effective than * normal array when the array has many same values. You can convert a * normal array to dictionary array by garrow_array_dictionary_encode(). */ typedef struct GArrowListArrayPrivate_ { GArrowArray *raw_values; } GArrowListArrayPrivate; enum { PROP_RAW_VALUES = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GArrowListArray, garrow_list_array, GARROW_TYPE_ARRAY) #define GARROW_LIST_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowListArrayPrivate *>( \ garrow_list_array_get_instance_private( \ GARROW_LIST_ARRAY(obj))) G_END_DECLS template <typename LIST_ARRAY_CLASS> GArrowArray * garrow_base_list_array_new(GArrowDataType *data_type, gint64 length, GArrowBuffer *value_offsets, GArrowArray *values, GArrowBuffer *null_bitmap, gint64 n_nulls) { const auto arrow_data_type = garrow_data_type_get_raw(data_type); const auto arrow_value_offsets = garrow_buffer_get_raw(value_offsets); const auto arrow_values = garrow_array_get_raw(values); const auto arrow_null_bitmap = garrow_buffer_get_raw(null_bitmap); auto arrow_list_array = std::make_shared<LIST_ARRAY_CLASS>(arrow_data_type, length, arrow_value_offsets, arrow_values, arrow_null_bitmap, n_nulls); auto arrow_array = std::static_pointer_cast<arrow::Array>(arrow_list_array); return garrow_array_new_raw(&arrow_array, "array", &arrow_array, "value-data-type", data_type, "null-bitmap", null_bitmap, "buffer1", value_offsets, "raw-values", values, NULL); }; template <typename LIST_ARRAY_CLASS> GArrowDataType * garrow_base_list_array_get_value_type(GArrowArray *array) { auto arrow_array = garrow_array_get_raw(array); auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); auto arrow_value_type = arrow_list_array->value_type(); return garrow_data_type_new_raw(&arrow_value_type); }; template <typename LIST_ARRAY_CLASS> GArrowArray * garrow_base_list_array_get_value(GArrowArray *array, gint64 i) { auto arrow_array = garrow_array_get_raw(array); auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); auto arrow_list = arrow_list_array->value_slice(i); return garrow_array_new_raw(&arrow_list, "array", &arrow_list, "parent", array, NULL); }; template <typename LIST_ARRAY_CLASS> GArrowArray * garrow_base_list_array_get_values(GArrowArray *array) { auto arrow_array = garrow_array_get_raw(array); auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); auto arrow_values = arrow_list_array->values(); return garrow_array_new_raw(&arrow_values, "array", &arrow_values, "parent", array, NULL); }; template <typename LIST_ARRAY_CLASS> typename LIST_ARRAY_CLASS::offset_type garrow_base_list_array_get_value_offset(GArrowArray *array, gint64 i) { auto arrow_array = garrow_array_get_raw(array); auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); return arrow_list_array->value_offset(i); }; template <typename LIST_ARRAY_CLASS> typename LIST_ARRAY_CLASS::offset_type garrow_base_list_array_get_value_length(GArrowArray *array, gint64 i) { auto arrow_array = garrow_array_get_raw(array); auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); return arrow_list_array->value_length(i); }; template <typename LIST_ARRAY_CLASS> const typename LIST_ARRAY_CLASS::offset_type * garrow_base_list_array_get_value_offsets(GArrowArray *array, gint64 *n_offsets) { auto arrow_array = garrow_array_get_raw(array); *n_offsets = arrow_array->length() + 1; auto arrow_list_array = std::static_pointer_cast<LIST_ARRAY_CLASS>(arrow_array); return arrow_list_array->raw_value_offsets(); }; G_BEGIN_DECLS static void garrow_list_array_dispose(GObject *object) { auto priv = GARROW_LIST_ARRAY_GET_PRIVATE(object); if (priv->raw_values) { g_object_unref(priv->raw_values); priv->raw_values = NULL; } G_OBJECT_CLASS(garrow_list_array_parent_class)->dispose(object); } static void garrow_list_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_LIST_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_RAW_VALUES: priv->raw_values = GARROW_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_list_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_LIST_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_RAW_VALUES: g_value_set_object(value, priv->raw_values); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_list_array_init(GArrowListArray *object) { } static void garrow_list_array_class_init(GArrowListArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_list_array_dispose; gobject_class->set_property = garrow_list_array_set_property; gobject_class->get_property = garrow_list_array_get_property; GParamSpec *spec; spec = g_param_spec_object("raw-values", "Raw values", "The raw values", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_RAW_VALUES, spec); } /** * garrow_list_array_new: * @data_type: The data type of the list. * @length: The number of elements. * @value_offsets: The offsets of @values in Arrow format. * @values: The values as #GArrowArray. * @null_bitmap: (nullable): The bitmap that shows null elements. The * N-th element is null when the N-th bit is 0, not null otherwise. * If the array has no null elements, the bitmap must be %NULL and * @n_nulls is 0. * @n_nulls: The number of null elements. If -1 is specified, the * number of nulls are computed from @null_bitmap. * * Returns: A newly created #GArrowListArray. * * Since: 0.4.0 */ GArrowListArray * garrow_list_array_new(GArrowDataType *data_type, gint64 length, GArrowBuffer *value_offsets, GArrowArray *values, GArrowBuffer *null_bitmap, gint64 n_nulls) { auto list_array = garrow_base_list_array_new<arrow::ListArray>( data_type, length, value_offsets, values, null_bitmap, n_nulls); return GARROW_LIST_ARRAY(list_array); } /** * garrow_list_array_get_value_type: * @array: A #GArrowListArray. * * Returns: (transfer full): The data type of value in each list. */ GArrowDataType * garrow_list_array_get_value_type(GArrowListArray *array) { return garrow_base_list_array_get_value_type<arrow::ListArray>( GARROW_ARRAY(array)); } /** * garrow_list_array_get_value: * @array: A #GArrowListArray. * @i: The index of the target value. * * Returns: (transfer full): The i-th list. */ GArrowArray * garrow_list_array_get_value(GArrowListArray *array, gint64 i) { return garrow_base_list_array_get_value<arrow::ListArray>( GARROW_ARRAY(array), i); } /** * garrow_list_array_get_values: * @array: A #GArrowListArray. * * Returns: (transfer full): The array containing the list's values. * * Since: 2.0.0 */ GArrowArray * garrow_list_array_get_values(GArrowListArray *array) { return garrow_base_list_array_get_values<arrow::ListArray>( GARROW_ARRAY(array)); } /** * garrow_list_array_get_offset: * @array: A #GArrowListArray. * @i: The index of the offset of the target value. * * Returns: The target offset in the array containing the list's values. * * Since: 2.0.0 */ gint32 garrow_list_array_get_value_offset(GArrowListArray *array, gint64 i) { return garrow_base_list_array_get_value_offset<arrow::ListArray>( GARROW_ARRAY(array), i); } /** * garrow_list_array_get_value_length: * @array: A #GArrowListArray. * @i: The index of the length of the target value. * * Returns: The target length in the array containing the list's values. * * Since: 2.0.0 */ gint32 garrow_list_array_get_value_length(GArrowListArray *array, gint64 i) { return garrow_base_list_array_get_value_length<arrow::ListArray>( GARROW_ARRAY(array), i); } /** * garrow_list_array_get_value_offsets: * @array: A #GArrowListArray. * @n_offsets: The number of offsets to be returned. * * Returns: (array length=n_offsets): The target offsets in the array * containing the list's values. * * Since: 2.0.0 */ const gint32 * garrow_list_array_get_value_offsets(GArrowListArray *array, gint64 *n_offsets) { return garrow_base_list_array_get_value_offsets<arrow::ListArray>( GARROW_ARRAY(array), n_offsets); } typedef struct GArrowLargeListArrayPrivate_ { GArrowArray *raw_values; } GArrowLargeListArrayPrivate; G_DEFINE_TYPE_WITH_PRIVATE(GArrowLargeListArray, garrow_large_list_array, GARROW_TYPE_ARRAY) #define GARROW_LARGE_LIST_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowLargeListArrayPrivate *>( \ garrow_large_list_array_get_instance_private( \ GARROW_LARGE_LIST_ARRAY(obj))) static void garrow_large_list_array_dispose(GObject *object) { auto priv = GARROW_LARGE_LIST_ARRAY_GET_PRIVATE(object); if (priv->raw_values) { g_object_unref(priv->raw_values); priv->raw_values = NULL; } G_OBJECT_CLASS(garrow_large_list_array_parent_class)->dispose(object); } static void garrow_large_list_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_LARGE_LIST_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_RAW_VALUES: priv->raw_values = GARROW_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_large_list_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_LARGE_LIST_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_RAW_VALUES: g_value_set_object(value, priv->raw_values); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_large_list_array_init(GArrowLargeListArray *object) { } static void garrow_large_list_array_class_init(GArrowLargeListArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_large_list_array_dispose; gobject_class->set_property = garrow_large_list_array_set_property; gobject_class->get_property = garrow_large_list_array_get_property; GParamSpec *spec; spec = g_param_spec_object("raw-values", "Raw values", "The raw values", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_RAW_VALUES, spec); } /** * garrow_large_list_array_new: * @data_type: The data type of the list. * @length: The number of elements. * @value_offsets: The offsets of @values in Arrow format. * @values: The values as #GArrowArray. * @null_bitmap: (nullable): The bitmap that shows null elements. The * N-th element is null when the N-th bit is 0, not null otherwise. * If the array has no null elements, the bitmap must be %NULL and * @n_nulls is 0. * @n_nulls: The number of null elements. If -1 is specified, the * number of nulls are computed from @null_bitmap. * * Returns: A newly created #GArrowLargeListArray. * * Since: 0.16.0 */ GArrowLargeListArray * garrow_large_list_array_new(GArrowDataType *data_type, gint64 length, GArrowBuffer *value_offsets, GArrowArray *values, GArrowBuffer *null_bitmap, gint64 n_nulls) { auto large_list_array = garrow_base_list_array_new<arrow::LargeListArray>( data_type, length, value_offsets, values, null_bitmap, n_nulls); return GARROW_LARGE_LIST_ARRAY(large_list_array); } /** * garrow_large_list_array_get_value_type: * @array: A #GArrowLargeListArray. * * Returns: (transfer full): The data type of value in each list. * * Since: 0.16.0 */ GArrowDataType * garrow_large_list_array_get_value_type(GArrowLargeListArray *array) { return garrow_base_list_array_get_value_type<arrow::LargeListArray>( GARROW_ARRAY(array)); } /** * garrow_large_list_array_get_value: * @array: A #GArrowLargeListArray. * @i: The index of the target value. * * Returns: (transfer full): The @i-th list. * * Since: 0.16.0 */ GArrowArray * garrow_large_list_array_get_value(GArrowLargeListArray *array, gint64 i) { return garrow_base_list_array_get_value<arrow::LargeListArray>( GARROW_ARRAY(array), i); } /** * garrow_large_list_array_get_values: * @array: A #GArrowLargeListArray. * * Returns: (transfer full): The array containing the list's values. * * Since: 2.0.0 */ GArrowArray * garrow_large_list_array_get_values(GArrowLargeListArray *array) { return garrow_base_list_array_get_values<arrow::LargeListArray>( GARROW_ARRAY(array)); } /** * garrow_large_list_array_get_value_offset: * @array: A #GArrowLargeListArray. * @i: The index of the offset of the target value. * * Returns: The target offset in the array containing the list's values. * * Since: 2.0.0 */ gint64 garrow_large_list_array_get_value_offset(GArrowLargeListArray *array, gint64 i) { return garrow_base_list_array_get_value_offset<arrow::LargeListArray>( GARROW_ARRAY(array), i); } /** * garrow_large_list_array_get_length: * @array: A #GArrowLargeListArray. * @i: The index of the length of the target value. * * Returns: The target length in the array containing the list's values. * * Since: 2.0.0 */ gint64 garrow_large_list_array_get_value_length(GArrowLargeListArray *array, gint64 i) { return garrow_base_list_array_get_value_length<arrow::LargeListArray>( GARROW_ARRAY(array), i); } /** * garrow_large_list_array_get_value_offsets: * @array: A #GArrowLargeListArray. * @n_offsets: The number of offsets to be returned. * * Returns: (array length=n_offsets): The target offsets in the array * containing the list's values. * * Since: 2.0.0 */ const gint64 * garrow_large_list_array_get_value_offsets(GArrowLargeListArray *array, gint64 *n_offsets) { return garrow_base_list_array_get_value_offsets<arrow::LargeListArray>( GARROW_ARRAY(array), n_offsets); } typedef struct GArrowStructArrayPrivate_ { GPtrArray *fields; } GArrowStructArrayPrivate; G_DEFINE_TYPE_WITH_PRIVATE(GArrowStructArray, garrow_struct_array, GARROW_TYPE_ARRAY) #define GARROW_STRUCT_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowStructArrayPrivate *>( \ garrow_struct_array_get_instance_private( \ GARROW_STRUCT_ARRAY(obj))) static void garrow_struct_array_dispose(GObject *object) { auto priv = GARROW_STRUCT_ARRAY_GET_PRIVATE(object); if (priv->fields) { g_ptr_array_free(priv->fields, TRUE); priv->fields = NULL; } G_OBJECT_CLASS(garrow_struct_array_parent_class)->dispose(object); } static void garrow_struct_array_init(GArrowStructArray *object) { } static void garrow_struct_array_class_init(GArrowStructArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_struct_array_dispose; } /** * garrow_struct_array_new: * @data_type: The data type of the struct. * @length: The number of elements. * @fields: (element-type GArrowArray): The arrays for each field * as #GList of #GArrowArray. * @null_bitmap: (nullable): The bitmap that shows null elements. The * N-th element is null when the N-th bit is 0, not null otherwise. * If the array has no null elements, the bitmap must be %NULL and * @n_nulls is 0. * @n_nulls: The number of null elements. If -1 is specified, the * number of nulls are computed from @null_bitmap. * * Returns: A newly created #GArrowStructArray. * * Since: 0.4.0 */ GArrowStructArray * garrow_struct_array_new(GArrowDataType *data_type, gint64 length, GList *fields, GArrowBuffer *null_bitmap, gint64 n_nulls) { const auto arrow_data_type = garrow_data_type_get_raw(data_type); std::vector<std::shared_ptr<arrow::Array>> arrow_fields; for (auto node = fields; node; node = node->next) { auto field = GARROW_ARRAY(node->data); arrow_fields.push_back(garrow_array_get_raw(field)); } const auto arrow_null_bitmap = garrow_buffer_get_raw(null_bitmap); auto arrow_struct_array = std::make_shared<arrow::StructArray>(arrow_data_type, length, arrow_fields, arrow_null_bitmap, n_nulls); auto arrow_array = std::static_pointer_cast<arrow::Array>(arrow_struct_array); auto struct_array = garrow_array_new_raw(&arrow_array, "array", &arrow_array, "null-bitmap", null_bitmap, NULL); auto priv = GARROW_STRUCT_ARRAY_GET_PRIVATE(struct_array); priv->fields = g_ptr_array_sized_new(arrow_fields.size()); g_ptr_array_set_free_func(priv->fields, g_object_unref); for (auto node = fields; node; node = node->next) { auto field = GARROW_ARRAY(node->data); g_ptr_array_add(priv->fields, g_object_ref(field)); } return GARROW_STRUCT_ARRAY(struct_array); } static GPtrArray * garrow_struct_array_get_fields_internal(GArrowStructArray *array) { auto priv = GARROW_STRUCT_ARRAY_GET_PRIVATE(array); if (!priv->fields) { auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_struct_array = std::static_pointer_cast<arrow::StructArray>(arrow_array); auto arrow_fields = arrow_struct_array->fields(); priv->fields = g_ptr_array_sized_new(arrow_fields.size()); g_ptr_array_set_free_func(priv->fields, g_object_unref); for (auto &arrow_field : arrow_fields) { g_ptr_array_add(priv->fields, garrow_array_new_raw(&arrow_field)); } } return priv->fields; } /** * garrow_struct_array_get_field * @array: A #GArrowStructArray. * @i: The index of the field in the struct. * * Returns: (transfer full): The i-th field. */ GArrowArray * garrow_struct_array_get_field(GArrowStructArray *array, gint i) { auto fields = garrow_struct_array_get_fields_internal(array); if (i < 0) { i += fields->len; } if (i < 0) { return NULL; } if (i >= static_cast<gint>(fields->len)) { return NULL; } auto field = static_cast<GArrowArray *>(g_ptr_array_index(fields, i)); g_object_ref(field); return field; } /** * garrow_struct_array_get_fields * @array: A #GArrowStructArray. * * Returns: (element-type GArrowArray) (transfer full): * The fields in the struct. */ GList * garrow_struct_array_get_fields(GArrowStructArray *array) { auto fields = garrow_struct_array_get_fields_internal(array); GList *field_list = NULL; for (guint i = 0; i < fields->len; ++i) { auto field = static_cast<GArrowArray *>(g_ptr_array_index(fields, i)); field_list = g_list_prepend(field_list, g_object_ref(field)); } return g_list_reverse(field_list); } /** * garrow_struct_array_flatten * @array: A #GArrowStructArray. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (element-type GArrowArray) (transfer full): * The fields in the struct. * * Since: 0.10.0 */ GList * garrow_struct_array_flatten(GArrowStructArray *array, GError **error) { const auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_struct_array = std::static_pointer_cast<arrow::StructArray>(arrow_array); auto memory_pool = arrow::default_memory_pool(); auto arrow_arrays = arrow_struct_array->Flatten(memory_pool); if (!garrow::check(error, arrow_arrays, "[struct-array][flatten]")) { return NULL; } GList *arrays = NULL; for (auto arrow_array : *arrow_arrays) { auto array = garrow_array_new_raw(&arrow_array); arrays = g_list_prepend(arrays, array); } return g_list_reverse(arrays); } typedef struct GArrowMapArrayPrivate_ { GArrowArray *offsets; GArrowArray *keys; GArrowArray *items; } GArrowMapArrayPrivate; enum { PROP_OFFSETS = 1, PROP_KEYS, PROP_ITEMS, }; G_DEFINE_TYPE_WITH_PRIVATE(GArrowMapArray, garrow_map_array, GARROW_TYPE_LIST_ARRAY) #define GARROW_MAP_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowMapArrayPrivate *>( \ garrow_map_array_get_instance_private( \ GARROW_MAP_ARRAY(obj))) static void garrow_map_array_dispose(GObject *object) { auto priv = GARROW_MAP_ARRAY_GET_PRIVATE(object); if (priv->offsets) { g_object_unref(priv->offsets); priv->offsets = NULL; } if (priv->keys) { g_object_unref(priv->keys); priv->keys = NULL; } if (priv->items) { g_object_unref(priv->items); priv->items = NULL; } G_OBJECT_CLASS(garrow_map_array_parent_class)->dispose(object); } static void garrow_map_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_MAP_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_OFFSETS: priv->offsets = GARROW_ARRAY(g_value_dup_object(value)); break; case PROP_KEYS: priv->keys = GARROW_ARRAY(g_value_dup_object(value)); break; case PROP_ITEMS: priv->items = GARROW_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_map_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_MAP_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_OFFSETS: g_value_set_object(value, priv->offsets); break; case PROP_KEYS: g_value_set_object(value, priv->keys); break; case PROP_ITEMS: g_value_set_object(value, priv->items); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_map_array_init(GArrowMapArray *object) { } static void garrow_map_array_class_init(GArrowMapArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_map_array_dispose; gobject_class->set_property = garrow_map_array_set_property; gobject_class->get_property = garrow_map_array_get_property; GParamSpec *spec; spec = g_param_spec_object("offsets", "Offsets", "The GArrowArray for offsets", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_OFFSETS, spec); spec = g_param_spec_object("keys", "Keys", "The GArrowArray for keys", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_KEYS, spec); spec = g_param_spec_object("items", "Items", "The GArrowArray for items", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_ITEMS, spec); } /** * garrow_map_array_new: * @offsets: The offsets Array containing n + 1 offsets encoding length and size. * @keys: The Array containing key values. * @items: The items Array containing item values. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowMapArray * or %NULL on error. * * Since: 0.17.0 */ GArrowMapArray * garrow_map_array_new(GArrowArray *offsets, GArrowArray *keys, GArrowArray *items, GError **error) { const auto arrow_offsets = garrow_array_get_raw(offsets); const auto arrow_keys = garrow_array_get_raw(keys); const auto arrow_items = garrow_array_get_raw(items); auto arrow_memory_pool = arrow::default_memory_pool(); auto arrow_array_result = arrow::MapArray::FromArrays(arrow_offsets, arrow_keys, arrow_items, arrow_memory_pool); if (garrow::check(error, arrow_array_result, "[map-array][new]")) { auto arrow_array = *arrow_array_result; return GARROW_MAP_ARRAY(garrow_array_new_raw(&arrow_array, "array", &arrow_array, "offsets", offsets, "keys", keys, "items", items, NULL)); } else { return NULL; } } /** * garrow_map_array_get_keys: * @array: A #GArrowMapArray. * * Returns: (transfer full): The Array containing key values. * * Since: 0.17.0 */ GArrowArray * garrow_map_array_get_keys(GArrowMapArray *array) { auto priv = GARROW_MAP_ARRAY_GET_PRIVATE(array); if (priv->keys) { g_object_ref(priv->keys); return priv->keys; } auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_map_array = std::static_pointer_cast<arrow::MapArray>(arrow_array); auto arrow_keys = arrow_map_array->keys(); return garrow_array_new_raw(&arrow_keys); } /** * garrow_map_array_get_items: * @array: A #GArrowMapArray. * * Returns: (transfer full): The items Array containing item values. * * Since: 0.17.0 */ GArrowArray * garrow_map_array_get_items(GArrowMapArray *array) { auto priv = GARROW_MAP_ARRAY_GET_PRIVATE(array); if (priv->items) { g_object_ref(priv->items); return priv->items; } auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_map_array = std::static_pointer_cast<arrow::MapArray>(arrow_array); auto arrow_items = arrow_map_array->items(); return garrow_array_new_raw(&arrow_items); } typedef struct GArrowUnionArrayPrivate_ { GArrowInt8Array *type_ids; GPtrArray *fields; } GArrowUnionArrayPrivate; enum { PROP_TYPE_IDS = 1, PROP_FIELDS, }; G_DEFINE_TYPE_WITH_PRIVATE(GArrowUnionArray, garrow_union_array, GARROW_TYPE_ARRAY) #define GARROW_UNION_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowUnionArrayPrivate *>( \ garrow_union_array_get_instance_private( \ GARROW_UNION_ARRAY(obj))) static void garrow_union_array_dispose(GObject *object) { auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(object); if (priv->type_ids) { g_object_unref(priv->type_ids); priv->type_ids = NULL; } if (priv->fields) { g_ptr_array_free(priv->fields, TRUE); priv->fields = NULL; } G_OBJECT_CLASS(garrow_union_array_parent_class)->dispose(object); } static void garrow_union_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_TYPE_IDS: priv->type_ids = GARROW_INT8_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_union_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_TYPE_IDS: g_value_set_object(value, priv->type_ids); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_union_array_init(GArrowUnionArray *object) { } static void garrow_union_array_class_init(GArrowUnionArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_union_array_dispose; gobject_class->set_property = garrow_union_array_set_property; gobject_class->get_property = garrow_union_array_get_property; GParamSpec *spec; spec = g_param_spec_object("type-ids", "Type IDs", "The GArrowInt8Array for type IDs", GARROW_TYPE_INT8_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_TYPE_IDS, spec); } /** * garrow_union_array_get_field * @array: A #GArrowUnionArray. * @i: The index of the field in the union. * * Returns: (nullable) (transfer full): The i-th field values as a * #GArrowArray or %NULL on out of range. */ GArrowArray * garrow_union_array_get_field(GArrowUnionArray *array, gint i) { auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(array); if (!priv->fields) { auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_union_array = std::static_pointer_cast<arrow::UnionArray>(arrow_array); auto n_fields = arrow_union_array->num_fields(); priv->fields = g_ptr_array_sized_new(n_fields); g_ptr_array_set_free_func(priv->fields, g_object_unref); for (int i = 0; i < n_fields; ++i) { auto arrow_field = arrow_union_array->field(i); g_ptr_array_add(priv->fields, garrow_array_new_raw(&arrow_field)); } } if (i < 0) { i += priv->fields->len; } if (i < 0) { return NULL; } if (i >= static_cast<gint>(priv->fields->len)) { return NULL; } auto field = static_cast<GArrowArray *>(g_ptr_array_index(priv->fields, i)); g_object_ref(field); return field; } G_DEFINE_TYPE(GArrowSparseUnionArray, garrow_sparse_union_array, GARROW_TYPE_UNION_ARRAY) static void garrow_sparse_union_array_init(GArrowSparseUnionArray *object) { } static void garrow_sparse_union_array_class_init(GArrowSparseUnionArrayClass *klass) { } static GArrowSparseUnionArray * garrow_sparse_union_array_new_internal(GArrowSparseUnionDataType *data_type, GArrowInt8Array *type_ids, GList *fields, GError **error, const char *context) { auto arrow_type_ids = garrow_array_get_raw(GARROW_ARRAY(type_ids)); std::vector<std::shared_ptr<arrow::Array>> arrow_fields; for (auto node = fields; node; node = node->next) { auto *field = GARROW_ARRAY(node->data); arrow_fields.push_back(garrow_array_get_raw(field)); } arrow::Result<std::shared_ptr<arrow::Array>> arrow_sparse_union_array_result; if (data_type) { auto arrow_data_type = garrow_data_type_get_raw(GARROW_DATA_TYPE(data_type)); auto arrow_union_data_type = std::static_pointer_cast<arrow::UnionType>(arrow_data_type); std::vector<std::string> arrow_field_names; for (const auto &arrow_field : arrow_union_data_type->fields()) { arrow_field_names.push_back(arrow_field->name()); } arrow_sparse_union_array_result = arrow::SparseUnionArray::Make(*arrow_type_ids, arrow_fields, arrow_field_names, arrow_union_data_type->type_codes()); } else { arrow_sparse_union_array_result = arrow::SparseUnionArray::Make(*arrow_type_ids, arrow_fields); } if (garrow::check(error, arrow_sparse_union_array_result, context)) { auto arrow_sparse_union_array = *arrow_sparse_union_array_result; auto sparse_union_array = garrow_array_new_raw(&arrow_sparse_union_array, "array", &arrow_sparse_union_array, "value-data-type", data_type, "type-ids", type_ids, NULL); auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(sparse_union_array); priv->fields = g_ptr_array_sized_new(arrow_fields.size()); g_ptr_array_set_free_func(priv->fields, g_object_unref); for (auto node = fields; node; node = node->next) { auto field = GARROW_ARRAY(node->data); g_ptr_array_add(priv->fields, g_object_ref(field)); } return GARROW_SPARSE_UNION_ARRAY(sparse_union_array); } else { return NULL; } } /** * garrow_sparse_union_array_new: * @type_ids: The field type IDs for each value as #GArrowInt8Array. * @fields: (element-type GArrowArray): The arrays for each field * as #GList of #GArrowArray. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowSparseUnionArray * or %NULL on error. * * Since: 0.12.0 */ GArrowSparseUnionArray * garrow_sparse_union_array_new(GArrowInt8Array *type_ids, GList *fields, GError **error) { return garrow_sparse_union_array_new_internal(NULL, type_ids, fields, error, "[sparse-union-array][new]"); } /** * garrow_sparse_union_array_new_data_type: * @data_type: The data type for the sparse array. * @type_ids: The field type IDs for each value as #GArrowInt8Array. * @fields: (element-type GArrowArray): The arrays for each field * as #GList of #GArrowArray. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowSparseUnionArray * or %NULL on error. * * Since: 0.14.0 */ GArrowSparseUnionArray * garrow_sparse_union_array_new_data_type(GArrowSparseUnionDataType *data_type, GArrowInt8Array *type_ids, GList *fields, GError **error) { return garrow_sparse_union_array_new_internal( data_type, type_ids, fields, error, "[sparse-union-array][new][data-type]"); } typedef struct GArrowDenseUnionArrayPrivate_ { GArrowInt32Array *value_offsets; } GArrowDenseUnionArrayPrivate; enum { PROP_VALUE_OFFSETS = 1, }; G_DEFINE_TYPE_WITH_PRIVATE(GArrowDenseUnionArray, garrow_dense_union_array, GARROW_TYPE_UNION_ARRAY) #define GARROW_DENSE_UNION_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowDenseUnionArrayPrivate *>( \ garrow_dense_union_array_get_instance_private( \ GARROW_DENSE_UNION_ARRAY(obj))) static void garrow_dense_union_array_dispose(GObject *object) { auto priv = GARROW_DENSE_UNION_ARRAY_GET_PRIVATE(object); if (priv->value_offsets) { g_object_unref(priv->value_offsets); priv->value_offsets = NULL; } G_OBJECT_CLASS(garrow_dense_union_array_parent_class)->dispose(object); } static void garrow_dense_union_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_DENSE_UNION_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_VALUE_OFFSETS: priv->value_offsets = GARROW_INT32_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_dense_union_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_DENSE_UNION_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_VALUE_OFFSETS: g_value_set_object(value, priv->value_offsets); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_dense_union_array_init(GArrowDenseUnionArray *object) { } static void garrow_dense_union_array_class_init(GArrowDenseUnionArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_dense_union_array_dispose; gobject_class->set_property = garrow_dense_union_array_set_property; gobject_class->get_property = garrow_dense_union_array_get_property; GParamSpec *spec; spec = g_param_spec_object("value-offsets", "Value offsets", "The GArrowInt32Array for value offsets", GARROW_TYPE_INT32_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_VALUE_OFFSETS, spec); } static GArrowDenseUnionArray * garrow_dense_union_array_new_internal(GArrowDenseUnionDataType *data_type, GArrowInt8Array *type_ids, GArrowInt32Array *value_offsets, GList *fields, GError **error, const gchar *context) { auto arrow_type_ids = garrow_array_get_raw(GARROW_ARRAY(type_ids)); auto arrow_value_offsets = garrow_array_get_raw(GARROW_ARRAY(value_offsets)); std::vector<std::shared_ptr<arrow::Array>> arrow_fields; for (auto node = fields; node; node = node->next) { auto *field = GARROW_ARRAY(node->data); arrow_fields.push_back(garrow_array_get_raw(field)); } arrow::Result<std::shared_ptr<arrow::Array>> arrow_dense_union_array_result; if (data_type) { auto arrow_data_type = garrow_data_type_get_raw(GARROW_DATA_TYPE(data_type)); auto arrow_union_data_type = std::static_pointer_cast<arrow::UnionType>(arrow_data_type); std::vector<std::string> arrow_field_names; for (const auto &arrow_field : arrow_union_data_type->fields()) { arrow_field_names.push_back(arrow_field->name()); } arrow_dense_union_array_result = arrow::DenseUnionArray::Make(*arrow_type_ids, *arrow_value_offsets, arrow_fields, arrow_field_names, arrow_union_data_type->type_codes()); } else { arrow_dense_union_array_result = arrow::DenseUnionArray::Make(*arrow_type_ids, *arrow_value_offsets, arrow_fields); } if (garrow::check(error, arrow_dense_union_array_result, context)) { auto arrow_dense_union_array = *arrow_dense_union_array_result; auto dense_union_array = garrow_array_new_raw(&arrow_dense_union_array, "array", &arrow_dense_union_array, "value-data-type", data_type, "type-ids", type_ids, "value-offsets", value_offsets, NULL); auto priv = GARROW_UNION_ARRAY_GET_PRIVATE(dense_union_array); priv->fields = g_ptr_array_sized_new(arrow_fields.size()); g_ptr_array_set_free_func(priv->fields, g_object_unref); for (auto node = fields; node; node = node->next) { auto field = GARROW_ARRAY(node->data); g_ptr_array_add(priv->fields, g_object_ref(field)); } return GARROW_DENSE_UNION_ARRAY(dense_union_array); } else { return NULL; } } /** * garrow_dense_union_array_new: * @type_ids: The field type IDs for each value as #GArrowInt8Array. * @value_offsets: The value offsets for each value as #GArrowInt32Array. * Each offset is counted for each type. * @fields: (element-type GArrowArray): The arrays for each field * as #GList of #GArrowArray. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowDenseUnionArray * or %NULL on error. * * Since: 0.12.0 */ GArrowDenseUnionArray * garrow_dense_union_array_new(GArrowInt8Array *type_ids, GArrowInt32Array *value_offsets, GList *fields, GError **error) { return garrow_dense_union_array_new_internal(NULL, type_ids, value_offsets, fields, error, "[dense-union-array][new]"); } /** * garrow_dense_union_array_new_data_type: * @data_type: The data type for the dense array. * @type_ids: The field type IDs for each value as #GArrowInt8Array. * @value_offsets: The value offsets for each value as #GArrowInt32Array. * Each offset is counted for each type. * @fields: (element-type GArrowArray): The arrays for each field * as #GList of #GArrowArray. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowSparseUnionArray * or %NULL on error. * * Since: 0.14.0 */ GArrowDenseUnionArray * garrow_dense_union_array_new_data_type(GArrowDenseUnionDataType *data_type, GArrowInt8Array *type_ids, GArrowInt32Array *value_offsets, GList *fields, GError **error) { return garrow_dense_union_array_new_internal( data_type, type_ids, value_offsets, fields, error, "[dense-union-array][new][data-type]"); } typedef struct GArrowDictionaryArrayPrivate_ { GArrowArray *indices; GArrowArray *dictionary; } GArrowDictionaryArrayPrivate; enum { PROP_INDICES = 1, PROP_DICTIONARY, }; G_DEFINE_TYPE_WITH_PRIVATE(GArrowDictionaryArray, garrow_dictionary_array, GARROW_TYPE_ARRAY) #define GARROW_DICTIONARY_ARRAY_GET_PRIVATE(obj) \ static_cast<GArrowDictionaryArrayPrivate *>( \ garrow_dictionary_array_get_instance_private( \ GARROW_DICTIONARY_ARRAY(obj))) static void garrow_dictionary_array_dispose(GObject *object) { auto priv = GARROW_DICTIONARY_ARRAY_GET_PRIVATE(object); if (priv->indices) { g_object_unref(priv->indices); priv->indices = NULL; } if (priv->dictionary) { g_object_unref(priv->dictionary); priv->dictionary = NULL; } G_OBJECT_CLASS(garrow_dictionary_array_parent_class)->dispose(object); } static void garrow_dictionary_array_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { auto priv = GARROW_DICTIONARY_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_INDICES: priv->indices = GARROW_ARRAY(g_value_dup_object(value)); break; case PROP_DICTIONARY: priv->dictionary = GARROW_ARRAY(g_value_dup_object(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_dictionary_array_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { auto priv = GARROW_DICTIONARY_ARRAY_GET_PRIVATE(object); switch (prop_id) { case PROP_INDICES: g_value_set_object(value, priv->indices); break; case PROP_DICTIONARY: g_value_set_object(value, priv->dictionary); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void garrow_dictionary_array_init(GArrowDictionaryArray *object) { } static void garrow_dictionary_array_class_init(GArrowDictionaryArrayClass *klass) { auto gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = garrow_dictionary_array_dispose; gobject_class->set_property = garrow_dictionary_array_set_property; gobject_class->get_property = garrow_dictionary_array_get_property; GParamSpec *spec; spec = g_param_spec_object("indices", "The indices", "The GArrowArray for indices", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_INDICES, spec); spec = g_param_spec_object("dictionary", "The dictionary", "The GArrowArray for dictionary", GARROW_TYPE_ARRAY, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); g_object_class_install_property(gobject_class, PROP_DICTIONARY, spec); } /** * garrow_dictionary_array_new: * @data_type: The data type of the dictionary array. * @indices: The indices of values in dictionary. * @dictionary: The dictionary of the dictionary array. * @error: (nullable): Return location for a #GError or %NULL. * * Returns: (nullable): A newly created #GArrowDictionaryArray * or %NULL on error. * * Since: 0.8.0 */ GArrowDictionaryArray * garrow_dictionary_array_new(GArrowDataType *data_type, GArrowArray *indices, GArrowArray *dictionary, GError **error) { const auto arrow_data_type = garrow_data_type_get_raw(data_type); const auto arrow_indices = garrow_array_get_raw(indices); const auto arrow_dictionary = garrow_array_get_raw(dictionary); auto arrow_dictionary_array_result = arrow::DictionaryArray::FromArrays( arrow_data_type, arrow_indices, arrow_dictionary); if (garrow::check(error, arrow_dictionary_array_result, "[dictionary-array][new]")) { auto arrow_array = std::static_pointer_cast<arrow::Array>(*arrow_dictionary_array_result); auto dictionary_array = garrow_array_new_raw(&arrow_array, "array", &arrow_array, "value-data-type", data_type, "indices", indices, "dictionary", dictionary, NULL); return GARROW_DICTIONARY_ARRAY(dictionary_array); } else { return NULL; } } /** * garrow_dictionary_array_get_indices: * @array: A #GArrowDictionaryArray. * * Returns: (transfer full): The indices of values in dictionary. * * Since: 0.8.0 */ GArrowArray * garrow_dictionary_array_get_indices(GArrowDictionaryArray *array) { auto priv = GARROW_DICTIONARY_ARRAY_GET_PRIVATE(array); if (priv->indices) { g_object_ref(priv->indices); return priv->indices; } auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_dictionary_array = std::static_pointer_cast<arrow::DictionaryArray>(arrow_array); auto arrow_indices = arrow_dictionary_array->indices(); return garrow_array_new_raw(&arrow_indices); } /** * garrow_dictionary_array_get_dictionary: * @array: A #GArrowDictionaryArray. * * Returns: (transfer full): The dictionary of this array. * * Since: 0.8.0 */ GArrowArray * garrow_dictionary_array_get_dictionary(GArrowDictionaryArray *array) { auto priv = GARROW_DICTIONARY_ARRAY_GET_PRIVATE(array); if (priv->dictionary) { g_object_ref(priv->dictionary); return priv->dictionary; } auto arrow_array = garrow_array_get_raw(GARROW_ARRAY(array)); auto arrow_dictionary_array = std::static_pointer_cast<arrow::DictionaryArray>(arrow_array); auto arrow_dictionary = arrow_dictionary_array->dictionary(); return garrow_array_new_raw(&arrow_dictionary); } /** * garrow_dictionary_array_get_dictionary_data_type: * @array: A #GArrowDictionaryArray. * * Returns: (transfer full): The dictionary data type of this array. * * Since: 0.8.0 * * Deprecated: 1.0.0: Use garrow_array_get_value_data_type() instead. */ GArrowDictionaryDataType * garrow_dictionary_array_get_dictionary_data_type(GArrowDictionaryArray *array) { auto data_type = garrow_array_get_value_data_type(GARROW_ARRAY(array)); return GARROW_DICTIONARY_DATA_TYPE(data_type); } G_END_DECLS
{ "content_hash": "3d69267509d8e5774b28290355dd3dca", "timestamp": "", "source": "github", "line_count": 1693, "max_line_length": 81, "avg_line_length": 31.275251033668045, "alnum_prop": 0.6091144308674384, "repo_name": "xhochy/arrow", "id": "688c548bf2ffd65853fbcdcb9ef767618e241ca5", "size": "53756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c_glib/arrow-glib/composite-array.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "73655" }, { "name": "Awk", "bytes": "3709" }, { "name": "Batchfile", "bytes": "24676" }, { "name": "C", "bytes": "881567" }, { "name": "C#", "bytes": "699719" }, { "name": "C++", "bytes": "14541996" }, { "name": "CMake", "bytes": "560347" }, { "name": "Dockerfile", "bytes": "100165" }, { "name": "Emacs Lisp", "bytes": "1916" }, { "name": "FreeMarker", "bytes": "2244" }, { "name": "Go", "bytes": "848212" }, { "name": "HTML", "bytes": "6152" }, { "name": "Java", "bytes": "4713332" }, { "name": "JavaScript", "bytes": "102300" }, { "name": "Julia", "bytes": "235105" }, { "name": "Lua", "bytes": "8771" }, { "name": "M4", "bytes": "11095" }, { "name": "MATLAB", "bytes": "36600" }, { "name": "Makefile", "bytes": "57687" }, { "name": "Meson", "bytes": "48356" }, { "name": "Objective-C", "bytes": "17680" }, { "name": "Objective-C++", "bytes": "12128" }, { "name": "PLpgSQL", "bytes": "56995" }, { "name": "Perl", "bytes": "3799" }, { "name": "Python", "bytes": "3135304" }, { "name": "R", "bytes": "533584" }, { "name": "Ruby", "bytes": "1084485" }, { "name": "Rust", "bytes": "3969176" }, { "name": "Shell", "bytes": "380070" }, { "name": "Thrift", "bytes": "142033" }, { "name": "TypeScript", "bytes": "1157087" } ], "symlink_target": "" }
package com.google.samples.apps.iosched.testutils; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.intent.rule.IntentsTestRule; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.samples.apps.iosched.archframework.Model; import com.google.samples.apps.iosched.injection.ModelProvider; import com.google.samples.apps.iosched.settings.ConfMessageCardUtils; import com.google.samples.apps.iosched.settings.SettingsUtils; import com.google.samples.apps.iosched.util.AccountUtils; import com.google.samples.apps.iosched.util.RegistrationUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * An {@link IntentsTestRule} bypassing the {@link com.google.samples.apps.iosched.welcome * .WelcomeActivity}. If passed in the constructor, the {@code model} is injected into the app. */ public class BaseActivityTestRule<T extends Activity> extends IntentsTestRule<T> { private Model mModel; private boolean mAttending; /** * @param activityClass The Activity under test */ public BaseActivityTestRule(final Class<T> activityClass) { super(activityClass); } /** * @param activityClass The Activity under test * @param model A stub model to inject into the {@link ModelProvider} * @param attending Whether the user should be set as attending or not */ public BaseActivityTestRule(final Class<T> activityClass, Model model, boolean attending) { super(activityClass); mModel = model; mAttending = attending; } // DISABLED: Broken // @Override // protected void beforeActivityLaunched() { // if (mAttending) { // prepareActivityForInPersonAttendee(); // } else { // prepareActivityForRemoteAttendee(); // } // ModelProvider.setStubModel(mModel); // } // DISABLED: Broken // private void prepareActivityForRemoteAttendee() { // bypassToS(); // RegistrationUtils.setRegisteredAttendee(InstrumentationRegistry.getTargetContext(), false); // selectFirstAccount(); // } // DISABLED: Broken // // TODO: revisit once the new auth flow is in place. // protected void prepareActivityForInPersonAttendee() { // bypassToS(); // RegistrationUtils.setRegisteredAttendee(InstrumentationRegistry.getTargetContext(), true); // selectFirstAccount(); // disableConferenceMessages(); // } // private void bypassToS() { // SettingsUtils.markTosAccepted(InstrumentationRegistry.getTargetContext(), true); // } private void selectFirstAccount() { List<Account> availableAccounts = new ArrayList<>( Arrays.asList(AccountManager.get(InstrumentationRegistry.getTargetContext()) .getAccountsByType( GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE))); if (availableAccounts.size() > 0) { AccountUtils.setActiveAccount(InstrumentationRegistry.getTargetContext(), availableAccounts.get(0).name); } } private void disableConferenceMessages() { ConfMessageCardUtils .markAnsweredConfMessageCardsPrompt(InstrumentationRegistry.getTargetContext(), true); } }
{ "content_hash": "67fe1fc7a259c1e3445e6fe2e2587a36", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 101, "avg_line_length": 35.642857142857146, "alnum_prop": 0.6825078728886345, "repo_name": "WeRockStar/iosched", "id": "af76ffcaf58fb6a2aad24bcbe43e341ebd639856", "size": "4081", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/src/androidTest/java/com/google/samples/apps/iosched/testutils/BaseActivityTestRule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2105" }, { "name": "HTML", "bytes": "36389" }, { "name": "Java", "bytes": "1517624" }, { "name": "Shell", "bytes": "10537" } ], "symlink_target": "" }
package com.didichuxing.doraemonkit.widget; import android.widget.RadioGroup; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TableLayout; import android.widget.TableRow; import com.didichuxing.doraemonkit.R; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-11-15-14:46 * 描 述:多方的RadioGroup * 修订历史: * ================================================ */ public class MultiLineRadioGroup extends RadioGroup { private static final String XML_DEFAULT_BUTTON_PREFIX_INDEX = "index:"; private static final String XML_DEFAULT_BUTTON_PREFIX_TEXT = "text:"; private static final int DEF_VAL_MAX_IN_ROW = 0; // for generating ids to APIs lower than 17 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); // the listener for callbacks to invoke when radio button checked state changes private OnCheckedChangeListener mOnCheckedChangeListener; // the listener for callbacks to invoke when radio button is clicked private OnClickListener mOnClickListener; // holds the maximum number of radio buttons that should be in a row private int mMaxInRow; // all buttons are stored in table layout private TableLayout mTableLayout; // list to store all the buttons private List<RadioButton> mRadioButtons; // the checked button private RadioButton mCheckedButton; /** * Creates a new MultiLineRadioGroup for the given context. * * @param context the application environment */ public MultiLineRadioGroup(Context context) { super(context); init(null); } /** * Creates a new MultiLineRadioGroup for the given context * and with the specified set attributes. * * @param context the application environment * @param attrs a collection of attributes */ public MultiLineRadioGroup(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } // initializes the layout private void init(AttributeSet attrs) { mRadioButtons = new ArrayList<>(); mTableLayout = getTableLayout(); addView(mTableLayout); if (attrs != null) initAttrs(attrs); } // initializes the layout with the specified attributes private void initAttrs(AttributeSet attrs) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes( attrs, R.styleable.dk_multi_line_radio_group, 0, 0); try { // gets and sets the max in row. setMaxInRow(typedArray.getInt(R.styleable.dk_multi_line_radio_group_max_in_row, DEF_VAL_MAX_IN_ROW)); // gets and adds the starting buttons CharSequence[] radioButtonStrings = typedArray.getTextArray( R.styleable.dk_multi_line_radio_group_radio_buttons); addButtons(radioButtonStrings); // gets the default button and checks it if presents. String string = typedArray.getString(R.styleable.dk_multi_line_radio_group_default_button); if (string != null) setDefaultButton(string); } finally { typedArray.recycle(); } } // checks the default button based on the passed string private void setDefaultButton(String string) { final int START_OF_INDEX = XML_DEFAULT_BUTTON_PREFIX_INDEX.length(); final int START_OF_TEXT = XML_DEFAULT_BUTTON_PREFIX_TEXT.length(); // the text of the button to check String buttonToCheck; if (string.startsWith(XML_DEFAULT_BUTTON_PREFIX_INDEX)) { String indexString = string.substring(START_OF_INDEX); int index = Integer.parseInt(indexString); if (index < 0 || index >= mRadioButtons.size()) throw new IllegalArgumentException("index must be between 0 to getRadioButtonCount() - 1 [" + (getRadioButtonCount() - 1) + "]: " + index); buttonToCheck = mRadioButtons.get(index).getText().toString(); } else if (string.startsWith(XML_DEFAULT_BUTTON_PREFIX_TEXT)) { buttonToCheck = string.substring(START_OF_TEXT); } else { // when there is no prefix assumes the string is the text of the button buttonToCheck = string; } check(buttonToCheck); } /** * Returns the table layout to set for this layout. * * @return the table layout */ protected TableLayout getTableLayout() { return (TableLayout) LayoutInflater.from(getContext()) .inflate(R.layout.dk_radio_table_layout, this, false); } /** * Returns the table row to set in this layout. * * @return the table row */ protected TableRow getTableRow() { return (TableRow) LayoutInflater.from(getContext()) .inflate(R.layout.dk_radio_table_row, mTableLayout, false); } /** * Returns the default radio button to set in this layout. * <p> * This radio button will be used when radio buttons are added * with the methods addButtons() that accept string varargs. * * @return the radio button */ protected RadioButton getRadioButton() { return (RadioButton) LayoutInflater.from(getContext()) .inflate(R.layout.dk_radio_button, null); } /** * Register a callback to be invoked when a radio button checked state changes. * The only time the listener is passed a button where isChecked is false will be when * you call clearCheck. * * @param onCheckedChangeListener the listener to attach */ public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) { this.mOnCheckedChangeListener = onCheckedChangeListener; } /** * Register a callback to be invoked when a radio button is clicked. * * @param listener the listener to attach */ public void setOnClickListener(OnClickListener listener) { this.mOnClickListener = listener; } /** * Returns the maximum radio buttons in a row, 0 for all in one line. * * @return the maximum radio buttons in a row, 0 for all in one line */ public int getMaxInRow() { return mMaxInRow; } /** * Sets the maximum radio buttons in a row, 0 for all in one line * and arranges the layout accordingly. * * @param maxInRow the maximum radio buttons in a row * @throws IllegalArgumentException if maxInRow is negative */ public void setMaxInRow(int maxInRow) { if (maxInRow < 0) throw new IllegalArgumentException("maxInRow must not be negative: " + maxInRow); this.mMaxInRow = maxInRow; arrangeButtons(); } /** * Adds a view to the layout * <p> * Consider using addButtons() instead * * @param child the view to add */ @Override public void addView(View child) { addView(child, -1, child.getLayoutParams()); } /** * Adds a view to the layout in the specified index * <p> * Consider using addButtons() instead * * @param child the view to add * @param index the index in which to insert the view */ @Override public void addView(View child, int index) { addView(child, index, child.getLayoutParams()); } /** * Adds a view to the layout with the specified width and height. * Note that for radio buttons the width and the height are ignored. * <p> * Consider using addButtons() instead * * @param child the view to add * @param width the width of the view * @param height the height of the view */ @Override public void addView(View child, int width, int height) { addView(child, -1, new LinearLayout.LayoutParams(width, height)); } /** * Adds a view to the layout with the specified layout params. * Note that for radio buttons the width and the height are ignored. * <p> * Consider using addButtons() instead * * @param child the view to add * @param params the layout params of the view */ @Override public void addView(View child, ViewGroup.LayoutParams params) { addView(child, -1, params); } /** * Adds a view to the layout in the specified index * with the specified layout params. * Note that for radio buttons the width and the height are ignored. * <p> * * Consider using addButtons() instead * * @param child the view to add * @param index the index in which to insert the view * @param params the layout params of the view */ @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof RadioButton) { addButtons(index, ((RadioButton) child)); } else { // if params are null sets them if (params == null) { params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } super.addView(child, index, params); } } /** * Adds radio buttons to the layout based on the texts in the radioButtons array. * Adds them in the last index. * If radioButtons is null does nothing. * * @param radioButtons the texts of the buttons to add */ public void addButtons(CharSequence... radioButtons) { addButtons(-1, radioButtons); } /** * Adds radio buttons to the layout based on the texts in the radioButtons array. * Adds them in the specified index, -1 for the last index. * If radioButtons is null does nothing. * * @param index the index in which to insert the radio buttons * @param radioButtons the texts of the buttons to add * @throws IllegalArgumentException if index is less than -1 or greater than the number of radio buttons */ public void addButtons(int index, CharSequence... radioButtons) { if (index < -1 || index > mRadioButtons.size()) throw new IllegalArgumentException("index must be between -1 to getRadioButtonCount() [" + getRadioButtonCount() + "]: " + index); if (radioButtons == null) return; // creates radio button array RadioButton[] buttons = new RadioButton[radioButtons.length]; for (int i = 0; i < buttons.length; i++) { RadioButton radioButton = getRadioButton(); radioButton.setText(radioButtons[i]); radioButton.setId(generateId()); buttons[i] = radioButton; } addButtons(index, buttons); } // generates an id private int generateId() { // for API 17 or higher if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return View.generateViewId(); // for API lower than 17 } else { while (true) { final int result = sNextGeneratedId.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (sNextGeneratedId.compareAndSet(result, newValue)) return result; } } } /** * Adds radio buttons to the layout. * Adds them in the last index. * If radioButtons is null does nothing. * * @param radioButtons the texts of the buttons to add */ public void addButtons(RadioButton... radioButtons) { addButtons(-1, radioButtons); } /** * Adds radio buttons to the layout. * Adds them in the specified index, -1 for the last index. * If radioButtons is null does nothing. * * @param index the index in which to insert the radio buttons * @param radioButtons the texts of the buttons to add * @throws IllegalArgumentException if index is less than -1 or greater than the number of radio buttons */ public void addButtons(int index, RadioButton... radioButtons) { if (index < -1 || index > mRadioButtons.size()) throw new IllegalArgumentException("index must be between -1 to getRadioButtonCount() [" + getRadioButtonCount() + "]: " + index); if (radioButtons == null) return; int realIndex = (index != -1) ? index : mRadioButtons.size(); // inits the buttons and adds them to the list for (RadioButton radioButton : radioButtons) { initRadioButton(radioButton); mRadioButtons.add(realIndex++, radioButton); } arrangeButtons(); } // inits the radio button private void initRadioButton(RadioButton radioButton) { radioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean didCheckStateChange = checkButton((RadioButton) v); if (didCheckStateChange && mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged(MultiLineRadioGroup.this, mCheckedButton); } if (mOnClickListener != null) { mOnClickListener.onClick(MultiLineRadioGroup.this, mCheckedButton); } } }); } /** * Removes a view from the layout. * <p> * Consider using removeButton(). * * @param view the view to remove */ @Override public void removeView(View view) { super.removeView(view); } /** * Removes a view from the layout in the specified index. * <p> * Consider using removeButton(). * * @param index the index from which to remove the view */ @Override public void removeViewAt(int index) { super.removeViewAt(index); } /** * Removes the specified range of views from the layout. * <p> * Consider using removeButtons(). * * @param start the start index to remove * @param count the number of views to remove */ @Override public void removeViews(int start, int count) { super.removeViews(start, count); } /** * Removes all the views from the layout. * <p> * Consider using removeAllButtons(). */ @Override public void removeAllViews() { super.removeAllViews(); } /** * Removes a radio button from the layout. * If the radio button is null does nothing. * * @param radioButton the radio button to remove */ public void removeButton(RadioButton radioButton) { if (radioButton == null) return; removeButton(radioButton.getText()); } /** * Removes a radio button from the layout based on its text. * Removes the first occurrence. * If the text is null does nothing. * * @param text the text of the radio button to remove */ public void removeButton(CharSequence text) { if (text == null) return; int index = -1; for (int i = 0, len = mRadioButtons.size(); i < len; i++) { // checks if the texts are equal if (mRadioButtons.get(i).getText().equals(text)) { index = i; break; } } // removes just if the index was found if (index != -1) removeButton(index); } /** * Removes the radio button in the specified index from the layout. * * @param index the index from which to remove the radio button * @throws IllegalArgumentException if index is less than 0 * or greater than the number of radio buttons - 1 */ public void removeButton(int index) { removeButtons(index, 1); } /** * Removes all the radio buttons in the specified range from the layout. * Count can be any non-negative number. * * @param start the start index to remove * @param count the number of radio buttons to remove * @throws IllegalArgumentException if index is less than 0 * or greater than the number of radio buttons - 1 * or count is negative */ public void removeButtons(int start, int count) { if (count == 0) { return; } if (start < 0 || start >= mRadioButtons.size()) throw new IllegalArgumentException("start index must be between 0 to getRadioButtonCount() - 1 [" + (getRadioButtonCount() - 1) + "]: " + start); if (count < 0) throw new IllegalArgumentException("count must not be negative: " + count); int endIndex = start + count - 1; // if endIndex is not in the range of the radio buttons sets it to the last index if (endIndex >= mRadioButtons.size()) endIndex = mRadioButtons.size() - 1; // iterates over the buttons to remove for (int i = endIndex; i >= start; i--) { RadioButton radiobutton = mRadioButtons.get(i); // if the button to remove is the checked button set mCheckedButton to null if (radiobutton == mCheckedButton) mCheckedButton = null; // removes the button from the list mRadioButtons.remove(i); } arrangeButtons(); } /** * Removes all the radio buttons from the layout. */ public void removeAllButtons() { removeButtons(0, mRadioButtons.size()); } // arrange the buttons in the layout private void arrangeButtons() { // iterates over each button and puts it in the right place for (int i = 0, len = mRadioButtons.size(); i < len; i++) { RadioButton radioButtonToPlace = mRadioButtons.get(i); int rowToInsert = (mMaxInRow != 0) ? i / mMaxInRow : 0; int columnToInsert = (mMaxInRow != 0) ? i % mMaxInRow : i; // gets the row to insert. if there is no row create one TableRow tableRowToInsert = (mTableLayout.getChildCount() <= rowToInsert) ? addTableRow() : (TableRow) mTableLayout.getChildAt(rowToInsert); int tableRowChildCount = tableRowToInsert.getChildCount(); // if there is already a button in the position if (tableRowChildCount > columnToInsert) { RadioButton currentButton = (RadioButton) tableRowToInsert.getChildAt(columnToInsert); // insert the button just if the current button is different if (currentButton != radioButtonToPlace) { // removes the current button removeButtonFromParent(currentButton, tableRowToInsert); // removes the button to place from its current position removeButtonFromParent(radioButtonToPlace, (ViewGroup) radioButtonToPlace.getParent()); // adds the button to the right place tableRowToInsert.addView(radioButtonToPlace, columnToInsert); } // if there isn't already a button in the position } else { // removes the button to place from its current position removeButtonFromParent(radioButtonToPlace, (ViewGroup) radioButtonToPlace.getParent()); // adds the button to the right place tableRowToInsert.addView(radioButtonToPlace, columnToInsert); } } removeRedundancies(); } // removes the redundant rows and radio buttons private void removeRedundancies() { // the number of rows to fit the buttons int rows; if (mRadioButtons.size() == 0) rows = 0; else if (mMaxInRow == 0) rows = 1; else rows = (mRadioButtons.size() - 1) / mMaxInRow + 1; int tableChildCount = mTableLayout.getChildCount(); // if there are redundant rows remove them if (tableChildCount > rows) mTableLayout.removeViews(rows, tableChildCount - rows); tableChildCount = mTableLayout.getChildCount(); int maxInRow = (mMaxInRow != 0) ? mMaxInRow : mRadioButtons.size(); // iterates over the rows for (int i = 0; i < tableChildCount; i++) { TableRow tableRow = (TableRow) mTableLayout.getChildAt(i); int tableRowChildCount = tableRow.getChildCount(); int startIndexToRemove; int count; // if it is the last row removes all redundancies after the last button in the list if (i == tableChildCount - 1) { startIndexToRemove = (mRadioButtons.size() - 1) % maxInRow + 1; count = tableRowChildCount - startIndexToRemove; // if it is not the last row removes all the buttons after maxInRow position } else { startIndexToRemove = maxInRow; count = tableRowChildCount - maxInRow; } if (count > 0) tableRow.removeViews(startIndexToRemove, count); } } // adds and returns a table row private TableRow addTableRow() { TableRow tableRow = getTableRow(); mTableLayout.addView(tableRow); return tableRow; } // removes a radio button from a parent private void removeButtonFromParent(RadioButton radioButton, ViewGroup parent) { if (radioButton == null || parent == null) return; parent.removeView(radioButton); } /** * Returns the number of radio buttons. * * @return the number of radio buttons */ public int getRadioButtonCount() { return mRadioButtons.size(); } /** * Returns the radio button in the specified index. * If the index is out of range returns null. * * @param index the index of the radio button * @return the radio button */ public RadioButton getRadioButtonAt(int index) { if (index < 0 || index >= mRadioButtons.size()) return null; return mRadioButtons.get(index); } /** * Returns true if there is a button with the specified text, false otherwise. * * @param button the text to search * @return true if there is a button with the specified text, false otherwise */ public boolean containsButton(String button) { for (RadioButton radioButton : mRadioButtons) if (radioButton.getText().equals(button)) return true; return false; } /** * Checks the radio button with the specified id. * If the specified id is not found does nothing. * * @param id the radio button's id */ @Override public void check(int id) { if (id <= 0) return; for (RadioButton radioButton : mRadioButtons) { if (radioButton.getId() == id) { if (checkButton(radioButton)) { // True if the button wasn't already checked. if (mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged( MultiLineRadioGroup.this, radioButton); } } return; } } } /** * Checks the radio button with the specified text. * If there is more than one radio button associated with this text * checks the first radio button. * If the specified text is not found does nothing. * * @param text the radio button's text */ public void check(CharSequence text) { if (text == null) return; for (RadioButton radioButton : mRadioButtons) { if (radioButton.getText().equals(text)) { if (checkButton(radioButton)) { // True if the button wasn't already checked. if (mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged( MultiLineRadioGroup.this, radioButton); } } return; } } } /** * Checks the radio button at the specified index. * If the specified index is invalid does nothing. * * @param index the radio button's index */ public void checkAt(int index) { if (index < 0 || index >= mRadioButtons.size()) return; if (checkButton(mRadioButtons.get(index))) { // True if the button wasn't already checked. if (mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged( MultiLineRadioGroup.this, mRadioButtons.get(index)); } } } /** * Checks and switches the button with mCheckedButton. * Returns true if check state changed, false otherwise. * * @param button the button to check. * @return true if check state changed, false otherwise. */ private boolean checkButton(RadioButton button) { if (button == null || button == mCheckedButton) { return false; } // if the button to check is different from the current checked button // if exists un-checks mCheckedButton if (mCheckedButton != null) { mCheckedButton.setChecked(false); } button.setChecked(true); mCheckedButton = button; return true; } /** * Clears the checked radio button. */ @Override public void clearCheck() { if (mCheckedButton != null) { mCheckedButton.setChecked(false); if (mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged(this, mCheckedButton); } } mCheckedButton = null; } /** * Returns the checked radio button's id. * If no radio buttons are checked returns -1. * * @return the checked radio button's id */ @Override public int getCheckedRadioButtonId() { if (mCheckedButton == null) return -1; return mCheckedButton.getId(); } /** * Returns the checked radio button's index. * If no radio buttons are checked returns -1. * * @return the checked radio button's index */ public int getCheckedRadioButtonIndex() { if (mCheckedButton == null) return -1; return mRadioButtons.indexOf(mCheckedButton); } /** * Returns the checked radio button's text. * If no radio buttons are checked returns null. * * @return the checked radio buttons's text */ public CharSequence getCheckedRadioButtonText() { if (mCheckedButton == null) return null; return mCheckedButton.getText(); } /** * Returns a parcelable representing the saved state of this layout. * * @return a parcelable representing the saved state of this layout */ @Override protected Parcelable onSaveInstanceState() { Parcelable parcelable = super.onSaveInstanceState(); SavedState savedState = new SavedState(parcelable); savedState.mMaxInRow = this.mMaxInRow; savedState.mCheckedButtonIndex = getCheckedRadioButtonIndex(); return savedState; } /** * Restores the state of this layout from a parcelable. * * @param state the parcelable */ @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); setMaxInRow(savedState.mMaxInRow); checkAt(savedState.mCheckedButtonIndex); } /** * Interface definition for a callback to be invoked when a radio button is checked. */ public interface OnCheckedChangeListener { /** * Called when a radio button is checked. * * @param group the group that stores the radio button * @param button the radio button that was checked */ void onCheckedChanged(ViewGroup group, RadioButton button); } /** * Interface definition for a callback to be invoked when a radio button is clicked. * Clicking a radio button multiple times will result in multiple callbacks. */ public interface OnClickListener { /** * Called when a radio button is clicked. * * @param group the group that stores the radio button * @param button the radio button that was clicked */ void onClick(ViewGroup group, RadioButton button); } /** * A class definition to save and restore a state of this layout. */ private static class SavedState extends BaseSavedState { /** * The creator of this class. */ public static final Parcelable.Creator CREATOR = new Creator<SavedState>() { /** * Creates SavedState instance from a specified parcel. * * @param in the parcel to create from * @return an instance of SavedState */ @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } /** * Creates a new array of the Parcelable class, * with every entry initialized to null. * * @param size the size of the array. * @return an array of the Parcelable class */ @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; int mMaxInRow; int mCheckedButtonIndex; /** * Constructor called by derived classes when creating their SavedState objects. * * @param superState the state of the superclass of this view */ SavedState(Parcelable superState) { super(superState); } /** * Constructor to create a new instance with the specified parcel. * * @param in the parcel */ SavedState(Parcel in) { super(in); mMaxInRow = in.readInt(); mCheckedButtonIndex = in.readInt(); } /** * Saves this object to a parcel. * * @param out the parcel to write to * @param flags additional flags about how the object should be written, * May be 0 or PARCELABLE_WRITE_RETURN_VALUE */ @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mMaxInRow); out.writeInt(mCheckedButtonIndex); } } }
{ "content_hash": "d0f6151d5687b5afed26329cd3526d1b", "timestamp": "", "source": "github", "line_count": 981, "max_line_length": 111, "avg_line_length": 32.82976554536187, "alnum_prop": 0.5922188412097125, "repo_name": "didi/DoraemonKit", "id": "55e054e7eceeb3382b914d099d19c5667b0d87e3", "size": "32258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/MultiLineRadioGroup.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "570" }, { "name": "C", "bytes": "31596" }, { "name": "C++", "bytes": "11759" }, { "name": "CMake", "bytes": "1598" }, { "name": "Dart", "bytes": "271190" }, { "name": "HTML", "bytes": "34347" }, { "name": "Java", "bytes": "4256090" }, { "name": "JavaScript", "bytes": "207266" }, { "name": "Kotlin", "bytes": "1450043" }, { "name": "Less", "bytes": "372" }, { "name": "Objective-C", "bytes": "1788521" }, { "name": "Objective-C++", "bytes": "12589" }, { "name": "Ruby", "bytes": "9059" }, { "name": "Shell", "bytes": "10258" }, { "name": "Swift", "bytes": "41938" }, { "name": "Vue", "bytes": "231621" } ], "symlink_target": "" }
ALTER TABLE gspanother.INDEX_TEST2 ADD CONSTRAINT PK_INDEX_TEST13 PRIMARY KEY ( INDEX_TEST2_ID );
{ "content_hash": "5e1d52ba6d9a182a123ef97ee3c3c447", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 77, "avg_line_length": 24.75, "alnum_prop": 0.7878787878787878, "repo_name": "coastland/gsp-dba-maven-plugin", "id": "2cc55eb4eadd395285894e27ca392854a7cfb43c", "size": "99", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/resources/jp/co/tis/gsp/tools/dba/mojo/ExecuteDdlMojo_test/another_schema_crud/postgresql/ddl/20_CREATE_PK_INDEX_TEST13.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "51937" }, { "name": "Java", "bytes": "923308" }, { "name": "PLpgSQL", "bytes": "3116" }, { "name": "TSQL", "bytes": "1870" } ], "symlink_target": "" }
#ifndef MPU6050_H_ #define MPU6050_H_ #include <avr/io.h> #include "mpu6050registers.h" //i2c settings #define MPU6050_I2CFLEURYPATH "../i2chw/i2cmaster.h" //define the path to i2c fleury lib #define MPU6050_I2CINIT 1 //init i2c //definitions #define MPU6050_ADDR (0x68 <<1) //device address - 0x68 pin low (GND), 0x69 pin high (VCC) //enable the getattitude functions //because we do not have a magnetometer, we have to start the chip always in the same position //then to obtain your object attitude you have to apply the aerospace sequence //0 disabled //1 mahony filter //2 dmp chip processor #define MPU6050_GETATTITUDE 2 #ifndef F_CPU #define F_CPU 16000000UL #endif //definitions for raw data //gyro and acc scale #define MPU6050_GYRO_FS MPU6050_GYRO_FS_2000 #define MPU6050_ACCEL_FS MPU6050_ACCEL_FS_2 #define MPU6050_GYRO_LSB_250 131.0 #define MPU6050_GYRO_LSB_500 65.5 #define MPU6050_GYRO_LSB_1000 32.8 #define MPU6050_GYRO_LSB_2000 16.4 #if MPU6050_GYRO_FS == MPU6050_GYRO_FS_250 #define MPU6050_GGAIN MPU6050_GYRO_LSB_250 #elif MPU6050_GYRO_FS == MPU6050_GYRO_FS_500 #define MPU6050_GGAIN MPU6050_GYRO_LSB_500 #elif MPU6050_GYRO_FS == MPU6050_GYRO_FS_1000 #define MPU6050_GGAIN MPU6050_GYRO_LSB_1000 #elif MPU6050_GYRO_FS == MPU6050_GYRO_FS_2000 #define MPU6050_GGAIN MPU6050_GYRO_LSB_2000 #endif #define MPU6050_ACCEL_LSB_2 16384.0 #define MPU6050_ACCEL_LSB_4 8192.0 #define MPU6050_ACCEL_LSB_8 4096.0 #define MPU6050_ACCEL_LSB_16 2048.0 #if MPU6050_ACCEL_FS == MPU6050_ACCEL_FS_2 #define MPU6050_AGAIN MPU6050_ACCEL_LSB_2 #elif MPU6050_ACCEL_FS == MPU6050_ACCEL_FS_4 #define MPU6050_AGAIN MPU6050_ACCEL_LSB_4 #elif MPU6050_ACCEL_FS == MPU6050_ACCEL_FS_8 #define MPU6050_AGAIN MPU6050_ACCEL_LSB_8 #elif MPU6050_ACCEL_FS == MPU6050_ACCEL_FS_16 #define MPU6050_AGAIN MPU6050_ACCEL_LSB_16 #endif #define MPU6050_CALIBRATEDACCGYRO 1 //set to 1 if is calibrated #if MPU6050_CALIBRATEDACCGYRO == 1 #define MPU6050_AXOFFSET 0 #define MPU6050_AYOFFSET 0 #define MPU6050_AZOFFSET 0 #define MPU6050_AXGAIN 16384.0 #define MPU6050_AYGAIN 16384.0 #define MPU6050_AZGAIN 16384.0 #define MPU6050_GXOFFSET -42 #define MPU6050_GYOFFSET 9 #define MPU6050_GZOFFSET -29 #define MPU6050_GXGAIN 16.4 #define MPU6050_GYGAIN 16.4 #define MPU6050_GZGAIN 16.4 #endif //definitions for attitude 1 function estimation #if MPU6050_GETATTITUDE == 1 //setup timer0 overflow event and define madgwickAHRSsampleFreq equal to timer0 frequency //timerfreq = (FCPU / prescaler) / timerscale // timerscale 8-bit = 256 // es. 61 = (16000000 / 1024) / 256 #define MPU6050_TIMER0INIT TCCR0B |=(1<<CS02)|(1<<CS00); \ TIMSK0 |=(1<<TOIE0); #define mpu6050_mahonysampleFreq 61.0f // sample frequency in Hz #define mpu6050_mahonytwoKpDef (2.0f * 0.5f) // 2 * proportional gain #define mpu6050_mahonytwoKiDef (2.0f * 0.1f) // 2 * integral gain #endif #if MPU6050_GETATTITUDE == 2 //dmp definitions //packet size #define MPU6050_DMP_dmpPacketSize 42 //define INT0 rise edge interrupt #define MPU6050_DMP_INT0SETUP EICRA |= (1<<ISC01) | (1<<ISC00) //define enable and disable INT0 rise edge interrupt #define MPU6050_DMP_INT0DISABLE EIMSK &= ~(1<<INT0) #define MPU6050_DMP_INT0ENABLE EIMSK |= (1<<INT0) extern volatile uint8_t mpu6050_mpuInterrupt; #endif //functions extern void mpu6050_init(void); extern uint8_t mpu6050_testConnection(void); extern void mpu6050_getRawGyro(int16_t *gx, int16_t *gy, int16_t *gz); extern void mpu6050_getRawData(int16_t* ax, int16_t* ay, int16_t* az, int16_t* gx, int16_t* gy, int16_t* gz); extern void mpu6050_getConvData(double* axg, double* ayg, double* azg, double* gxds, double* gyds, double* gzds); extern void mpu6050_setSleepDisabled(void); extern void mpu6050_setSleepEnabled(void); extern int8_t mpu6050_readBytes(uint8_t regAddr, uint8_t length, uint8_t *data); extern int8_t mpu6050_readByte(uint8_t regAddr, uint8_t *data); extern void mpu6050_writeBytes(uint8_t regAddr, uint8_t length, uint8_t* data); extern void mpu6050_writeByte(uint8_t regAddr, uint8_t data); extern int8_t mpu6050_readBits(uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data); extern int8_t mpu6050_readBit(uint8_t regAddr, uint8_t bitNum, uint8_t *data); extern void mpu6050_writeBits(uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data); extern void mpu6050_writeBit(uint8_t regAddr, uint8_t bitNum, uint8_t data); #if MPU6050_GETATTITUDE == 1 extern void mpu6050_updateQuaternion(void); extern void mpu6050_getQuaternion(double *qw, double *qx, double *qy, double *qz); extern void mpu6050_getRollPitchYaw(double *pitch, double *roll, double *yaw); #endif #if MPU6050_GETATTITUDE == 2 extern void mpu6050_writeWords(uint8_t regAddr, uint8_t length, uint16_t* data); extern void mpu6050_setMemoryBank(uint8_t bank, uint8_t prefetchEnabled, uint8_t userBank); extern void mpu6050_setMemoryStartAddress(uint8_t address); extern void mpu6050_readMemoryBlock(uint8_t *data, uint16_t dataSize, uint8_t bank, uint8_t address); extern uint8_t mpu6050_writeMemoryBlock(const uint8_t *data, uint16_t dataSize, uint8_t bank, uint8_t address, uint8_t verify, uint8_t useProgMem); extern uint8_t mpu6050_writeDMPConfigurationSet(const uint8_t *data, uint16_t dataSize, uint8_t useProgMem); extern uint16_t mpu6050_getFIFOCount(void); extern void mpu6050_getFIFOBytes(uint8_t *data, uint8_t length); extern uint8_t mpu6050_getIntStatus(void); extern void mpu6050_resetFIFO(void); extern int8_t mpu6050_getXGyroOffset(void); extern void mpu6050_setXGyroOffset(int8_t offset); extern int8_t mpu6050_getYGyroOffset(void); extern void mpu6050_setYGyroOffset(int8_t offset); extern int8_t mpu6050_getZGyroOffset(void); extern void mpu6050_setZGyroOffset(int8_t offset); //base dmp extern uint8_t mpu6050_dmpInitialize(void); extern void mpu6050_dmpEnable(void); extern void mpu6050_dmpDisable(void); extern void mpu6050_getQuaternion(const uint8_t* packet, double *qw, double *qx, double *qy, double *qz); extern void mpu6050_getRollPitchYaw(double qw, double qx, double qy, double qz, double *roll, double *pitch, double *yaw); extern uint8_t mpu6050_getQuaternionWait(double *qw, double *qx, double *qy, double *qz); #endif #endif
{ "content_hash": "8031ae2f14f67077e6890becbbe4e626", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 147, "avg_line_length": 39.48076923076923, "alnum_prop": 0.7681441792498782, "repo_name": "ndanyliw/nanoquad", "id": "1ee6226f0ba60f8e84a43cef36f01d8d79e79181", "size": "6510", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "firmware/libraries/mpu6050/mpu6050.h", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "22356" }, { "name": "C", "bytes": "67168" }, { "name": "C++", "bytes": "131708" }, { "name": "CSS", "bytes": "12348" }, { "name": "Elixir", "bytes": "391" }, { "name": "JavaScript", "bytes": "65325" }, { "name": "Perl", "bytes": "275" }, { "name": "Processing", "bytes": "82946" }, { "name": "Python", "bytes": "821" }, { "name": "Shell", "bytes": "68853" }, { "name": "XSLT", "bytes": "2042" } ], "symlink_target": "" }
/* CWebDAVDelete.h Author: Description: <describe the CWebDAVDelete class here> */ #ifndef CWebDAVDelete_H #define CWebDAVDelete_H #include "CWebDAVRequestResponse.h" using namespace http; namespace http { namespace webdav { class CWebDAVDelete: public CWebDAVRequestResponse { public: CWebDAVDelete(CWebDAVSession* session, const cdstring& ruri); virtual ~CWebDAVDelete(); void SetData(); void SetData(const cdstring& etag); }; } // namespace webdav } // namespace http #endif // CWebDAVDelete_H
{ "content_hash": "fb7370f3640082d1dc312831d42e6898", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 62, "avg_line_length": 14.527777777777779, "alnum_prop": 0.7437858508604207, "repo_name": "mbert/mulberry-main", "id": "650e2dd28e202233c8b4ed9eeb52c002bcb217aa", "size": "1158", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Sources_Common/HTTP/WebDAVClient/CWebDAVDelete.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "569106" }, { "name": "Batchfile", "bytes": "80126" }, { "name": "C", "bytes": "13996926" }, { "name": "C++", "bytes": "36795816" }, { "name": "Component Pascal", "bytes": "63931" }, { "name": "DIGITAL Command Language", "bytes": "273849" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "Groff", "bytes": "5" }, { "name": "HTML", "bytes": "219178" }, { "name": "Logos", "bytes": "108920" }, { "name": "Makefile", "bytes": "11884" }, { "name": "Objective-C", "bytes": "129690" }, { "name": "Perl", "bytes": "1749015" }, { "name": "Perl6", "bytes": "27602" }, { "name": "Prolog", "bytes": "29177" }, { "name": "Python", "bytes": "8651" }, { "name": "R", "bytes": "741731" }, { "name": "Rebol", "bytes": "179366" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "172439" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "4568" } ], "symlink_target": "" }
<?php /** * Adminhtml sales order column renderer * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Adminhtml_Block_Sales_Items_Column_Default extends Mage_Adminhtml_Block_Template { public function getItem() { if ($this->_getData('item') instanceof Mage_Sales_Model_Order_Item) { return $this->_getData('item'); } else { return $this->_getData('item')->getOrderItem(); } } public function getOrderOptions() { $result = array(); if ($options = $this->getItem()->getProductOptions()) { if (isset($options['options'])) { $result = array_merge($result, $options['options']); } if (isset($options['additional_options'])) { $result = array_merge($result, $options['additional_options']); } if (!empty($options['attributes_info'])) { $result = array_merge($options['attributes_info'], $result); } } return $result; } /** * Return custom option html * * @param array $optionInfo * @return string */ public function getCustomizedOptionValue($optionInfo) { // render customized option view $_default = $optionInfo['value']; if (isset($optionInfo['option_type'])) { try { $group = Mage::getModel('catalog/product_option')->groupFactory($optionInfo['option_type']); return $group->getCustomizedView($optionInfo); } catch (Exception $e) { return $_default; } } return $_default; } public function getSku() { /*if ($this->getItem()->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { return $this->getItem()->getProductOptionByCode('simple_sku'); }*/ return $this->getItem()->getSku(); } }
{ "content_hash": "61ea8aa52392cec5de9f33798ce295a6", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 108, "avg_line_length": 29.318840579710145, "alnum_prop": 0.5447355412753336, "repo_name": "StudioBOZ/thirdClass", "id": "2da616f0bafed59e445745dbef276b5f901a01b5", "size": "2981", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "app/code/core/Mage/Adminhtml/Block/Sales/Items/Column/Default.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "19946" }, { "name": "CSS", "bytes": "1291126" }, { "name": "JavaScript", "bytes": "1277438" }, { "name": "PHP", "bytes": "43528858" }, { "name": "Shell", "bytes": "717" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes, Component } from 'react'; import styles from './ContactPage.scss'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class ContactPage extends Component { static contextTypes = { onSetTitle: PropTypes.func.isRequired, }; render() { const title = 'Contact Us'; this.context.onSetTitle(title); return ( <div className="ContactPage"> <div className="ContactPage-container"> <h1>{title}</h1> <p>...</p> </div> </div> ); } } export default ContactPage;
{ "content_hash": "20026cfc6688627bcc00fdfda29160d5", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 72, "avg_line_length": 22.551724137931036, "alnum_prop": 0.6284403669724771, "repo_name": "Malinin88/SaratovJS", "id": "2ff3ef1f7ca9ba86fdef036c3ea73a97643e8bb7", "size": "654", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "src/components/ContactPage/ContactPage.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8815" }, { "name": "HTML", "bytes": "6626" }, { "name": "JavaScript", "bytes": "29213" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>interval: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0~camlp4 / interval - 3.4.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> interval <small> 3.4.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-15 10:36:52 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-15 10:36:52 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp4 4.03+1 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.5.0~camlp4 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0.14.2 OCamlbuild is a build system with builtin rules to easily build most OCaml projects # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;guillaume.melquiond@inria.fr&quot; homepage: &quot;https://coqinterval.gitlabpages.inria.fr/&quot; dev-repo: &quot;git+https://gitlab.inria.fr/coqinterval/interval.git&quot; bug-reports: &quot;https://gitlab.inria.fr/coqinterval/interval/issues&quot; license: &quot;CeCILL-C&quot; build: [ [&quot;./configure&quot;] [&quot;./remake&quot; &quot;-j%{jobs}%&quot;] ] install: [&quot;./remake&quot; &quot;install&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.12~&quot;} &quot;coq-bignums&quot; &quot;coq-flocq&quot; {&gt;= &quot;3.0&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6&quot;} &quot;coq-coquelicot&quot; {&gt;= &quot;3.0&quot;} (&quot;conf-g++&quot; | &quot;conf-clang&quot;) ] tags: [ &quot;keyword:interval arithmetic&quot; &quot;keyword:decision procedure&quot; &quot;keyword:floating-point arithmetic&quot; &quot;keyword:reflexive tactic&quot; &quot;keyword:Taylor models&quot; &quot;category:Mathematics/Real Calculus and Topology&quot; &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;date:2020-02-25&quot; ] authors: [ &quot;Guillaume Melquiond &lt;guillaume.melquiond@inria.fr&gt;&quot; &quot;Érik Martin-Dorel &lt;erik.martin-dorel@irit.fr&gt;&quot; &quot;Thomas Sibut-Pinote &lt;thomas.sibut-pinote@inria.fr&gt;&quot; ] synopsis: &quot;A Coq tactic for proving bounds on real-valued expressions automatically&quot; url { src: &quot;https://coqinterval.gitlabpages.inria.fr/releases/interval-3.4.2.tar.gz&quot; checksum: &quot;sha512=4e61a3bfe5f8758db8a09dec4f690213bb369a1ae960237ecfeb3c1d999619f9ef5afd5daeeeecc44dfe64bd4c46ffcca7a2872c11febd47ecbb0d799bc478fe&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-interval.3.4.2 coq.8.5.0~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4). The following dependencies couldn&#39;t be met: - coq-interval -&gt; coq &gt;= 8.7 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-interval.3.4.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "e4561f47b3ddec09de10a2919ba7941e", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 214, "avg_line_length": 43.42134831460674, "alnum_prop": 0.5650148790270411, "repo_name": "coq-bench/coq-bench.github.io", "id": "0f339a648e155ab599abe69455d05b393d36e2aa", "size": "7755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.0~camlp4/interval/3.4.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.elasticsearch.action.bulk; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.elasticsearch.test.ElasticsearchIntegrationTest.Scope; import org.junit.Test; @ClusterScope(scope = Scope.TEST, numDataNodes = 0) public class BulkProcessorClusterSettingsTests extends ElasticsearchIntegrationTest { @Test public void testBulkProcessorAutoCreateRestrictions() throws Exception { // See issue #8125 Settings settings = ImmutableSettings.settingsBuilder().put("action.auto_create_index", false).build(); internalCluster().startNode(settings); createIndex("willwork"); client().admin().cluster().prepareHealth("willwork").setWaitForGreenStatus().execute().actionGet(); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); bulkRequestBuilder.add(client().prepareIndex("willwork", "type1", "1").setSource("{\"foo\":1}")); bulkRequestBuilder.add(client().prepareIndex("wontwork", "type1", "2").setSource("{\"foo\":2}")); bulkRequestBuilder.add(client().prepareIndex("willwork", "type1", "3").setSource("{\"foo\":3}")); BulkResponse br = bulkRequestBuilder.get(); BulkItemResponse[] responses = br.getItems(); assertEquals(3, responses.length); assertFalse("Operation on existing index should succeed", responses[0].isFailed()); assertTrue("Missing index should have been flagged", responses[1].isFailed()); assertEquals("[wontwork] no such index", responses[1].getFailureMessage()); assertFalse("Operation on existing index should succeed", responses[2].isFailed()); } }
{ "content_hash": "31079be80f7a5e376500f31a397f84c2", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 111, "avg_line_length": 49.567567567567565, "alnum_prop": 0.7273718647764449, "repo_name": "vrkansagara/elasticsearch", "id": "5140df378ddfd7d607a581f37f37e2f1cabd71ca", "size": "2622", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/elasticsearch/action/bulk/BulkProcessorClusterSettingsTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "451" }, { "name": "HTML", "bytes": "1212" }, { "name": "Java", "bytes": "27038633" }, { "name": "Perl", "bytes": "6949" }, { "name": "Python", "bytes": "74553" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "57643" } ], "symlink_target": "" }
// flow-typed signature: 79abfc88eed0c96703e149075dd338f6 // flow-typed version: <<STUB>>/eslint-plugin-flowtype_v^2.30.0/flow_v0.74.0 /** * This is an autogenerated libdef stub for: * * 'eslint-plugin-flowtype' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-plugin-flowtype' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'eslint-plugin-flowtype/bin/readmeAssertions' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/index' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/booleanStyle' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/defineFlowType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/delimiterDangle' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/genericSpacing' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noDupeKeys' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noFlowFixMeComments' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noMutableArray' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noPrimitiveConstructorTypes' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noTypesMissingFileAnnotation' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noUnusedExpressions' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/noWeakTypes' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/objectTypeDelimiter' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/requireParameterType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/requireReturnType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/requireValidFileAnnotation' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/requireVariableType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/semi' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/sortKeys' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/spaceAfterTypeColon' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/spaceBeforeGenericBracket' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/spaceBeforeTypeColon' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateFunctions' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeIndexer' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeProperty' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateReturnType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypeCastExpression' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypical' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/index' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/reporter' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/typeIdMatch' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/unionIntersectionSpacing' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/useFlowType' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/rules/validSyntax' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/checkFlowFileAnnotation' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/fuzzyStringMatch' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/getParameterName' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/getTokenAfterParens' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/getTokenBeforeParens' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/index' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/isFlowFile' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/isFlowFileAnnotation' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/iterateFunctionNodes' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/quoteName' { declare module.exports: any; } declare module 'eslint-plugin-flowtype/dist/utilities/spacingFixers' { declare module.exports: any; } // Filename aliases declare module 'eslint-plugin-flowtype/bin/readmeAssertions.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/bin/readmeAssertions'>; } declare module 'eslint-plugin-flowtype/dist/index.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/index'>; } declare module 'eslint-plugin-flowtype/dist/rules/booleanStyle.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/booleanStyle'>; } declare module 'eslint-plugin-flowtype/dist/rules/defineFlowType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/defineFlowType'>; } declare module 'eslint-plugin-flowtype/dist/rules/delimiterDangle.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/delimiterDangle'>; } declare module 'eslint-plugin-flowtype/dist/rules/genericSpacing.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/genericSpacing'>; } declare module 'eslint-plugin-flowtype/dist/rules/noDupeKeys.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noDupeKeys'>; } declare module 'eslint-plugin-flowtype/dist/rules/noFlowFixMeComments.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noFlowFixMeComments'>; } declare module 'eslint-plugin-flowtype/dist/rules/noMutableArray.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noMutableArray'>; } declare module 'eslint-plugin-flowtype/dist/rules/noPrimitiveConstructorTypes.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noPrimitiveConstructorTypes'>; } declare module 'eslint-plugin-flowtype/dist/rules/noTypesMissingFileAnnotation.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noTypesMissingFileAnnotation'>; } declare module 'eslint-plugin-flowtype/dist/rules/noUnusedExpressions.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noUnusedExpressions'>; } declare module 'eslint-plugin-flowtype/dist/rules/noWeakTypes.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/noWeakTypes'>; } declare module 'eslint-plugin-flowtype/dist/rules/objectTypeDelimiter.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/objectTypeDelimiter'>; } declare module 'eslint-plugin-flowtype/dist/rules/requireParameterType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/requireParameterType'>; } declare module 'eslint-plugin-flowtype/dist/rules/requireReturnType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/requireReturnType'>; } declare module 'eslint-plugin-flowtype/dist/rules/requireValidFileAnnotation.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/requireValidFileAnnotation'>; } declare module 'eslint-plugin-flowtype/dist/rules/requireVariableType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/requireVariableType'>; } declare module 'eslint-plugin-flowtype/dist/rules/semi.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/semi'>; } declare module 'eslint-plugin-flowtype/dist/rules/sortKeys.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/sortKeys'>; } declare module 'eslint-plugin-flowtype/dist/rules/spaceAfterTypeColon.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/spaceAfterTypeColon'>; } declare module 'eslint-plugin-flowtype/dist/rules/spaceBeforeGenericBracket.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/spaceBeforeGenericBracket'>; } declare module 'eslint-plugin-flowtype/dist/rules/spaceBeforeTypeColon.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/spaceBeforeTypeColon'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateFunctions.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateFunctions'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeIndexer.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeIndexer'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeProperty.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateObjectTypeProperty'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateReturnType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateReturnType'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypeCastExpression.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypeCastExpression'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypical.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/evaluateTypical'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/index.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/index'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeColonSpacing/reporter.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeColonSpacing/reporter'>; } declare module 'eslint-plugin-flowtype/dist/rules/typeIdMatch.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/typeIdMatch'>; } declare module 'eslint-plugin-flowtype/dist/rules/unionIntersectionSpacing.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/unionIntersectionSpacing'>; } declare module 'eslint-plugin-flowtype/dist/rules/useFlowType.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/useFlowType'>; } declare module 'eslint-plugin-flowtype/dist/rules/validSyntax.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/rules/validSyntax'>; } declare module 'eslint-plugin-flowtype/dist/utilities/checkFlowFileAnnotation.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/checkFlowFileAnnotation'>; } declare module 'eslint-plugin-flowtype/dist/utilities/fuzzyStringMatch.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/fuzzyStringMatch'>; } declare module 'eslint-plugin-flowtype/dist/utilities/getParameterName.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/getParameterName'>; } declare module 'eslint-plugin-flowtype/dist/utilities/getTokenAfterParens.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/getTokenAfterParens'>; } declare module 'eslint-plugin-flowtype/dist/utilities/getTokenBeforeParens.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/getTokenBeforeParens'>; } declare module 'eslint-plugin-flowtype/dist/utilities/index.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/index'>; } declare module 'eslint-plugin-flowtype/dist/utilities/isFlowFile.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/isFlowFile'>; } declare module 'eslint-plugin-flowtype/dist/utilities/isFlowFileAnnotation.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/isFlowFileAnnotation'>; } declare module 'eslint-plugin-flowtype/dist/utilities/iterateFunctionNodes.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/iterateFunctionNodes'>; } declare module 'eslint-plugin-flowtype/dist/utilities/quoteName.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/quoteName'>; } declare module 'eslint-plugin-flowtype/dist/utilities/spacingFixers.js' { declare module.exports: $Exports<'eslint-plugin-flowtype/dist/utilities/spacingFixers'>; }
{ "content_hash": "f0abf0d95c77ad720f267adbc4b30b84", "timestamp": "", "source": "github", "line_count": 347, "max_line_length": 116, "avg_line_length": 39.242074927953894, "alnum_prop": 0.7949621796284057, "repo_name": "jcoreio/redux-features", "id": "5404264ed08c27446528f11df22b6e693163c58b", "size": "13617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flow-typed/npm/eslint-plugin-flowtype_vx.x.x.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "39357" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////////////////////////// // Orkid // Copyright 1996-2010, Michael T. Mayers /////////////////////////////////////////////////////////////////////////////// #pragma once #include <memory.h> #include <ork/stream/IInputStream.h> namespace ork { namespace stream { template<size_t buffersize_> class InputStreamBuffer : public IInputStream { public: InputStreamBuffer(IInputStream &stream); /*virtual*/ size_t Read(unsigned char dst[], size_t size); size_t Peek(unsigned char dst[], size_t size); /*virtual*/ void Discard(size_t size); private: size_t PeekFromBuffer(unsigned char dst[], size_t size); void ReadFromBuffer(unsigned char dst[], size_t size); void ReadToBuffer(size_t size); IInputStream &mStream; size_t mAvailable; size_t mBufferStart; unsigned char mBuffer[buffersize_]; }; //////////////////////////////////////////////////////////////////// template<size_t buffersize_> inline InputStreamBuffer<buffersize_>::InputStreamBuffer(IInputStream &stream) : mStream(stream) , mAvailable(0) , mBufferStart(0) {} template<size_t buffersize_> inline size_t InputStreamBuffer<buffersize_>::Read(unsigned char dst[], size_t size) { size_t read = 0; if(mAvailable > 0) { size_t piecesize = size < mAvailable ? size : mAvailable; ReadFromBuffer(dst, piecesize); read += piecesize; size -= piecesize; dst += piecesize; } if(size > 0) { size_t amount = mStream.Read(dst, size); if(amount != IInputStream::kEOF) read += amount; } if(read == 0 && size > 0) return IInputStream::kEOF; return read; } template<size_t buffersize_> inline size_t InputStreamBuffer<buffersize_>::Peek(unsigned char dst[], size_t size) { if(mAvailable < size) ReadToBuffer(size - mAvailable); if(mAvailable == 0 && size > 0) return IInputStream::kEOF; else return PeekFromBuffer(dst, size); } template<size_t buffersize_> inline void InputStreamBuffer<buffersize_>::Discard(size_t size) { if(size < mAvailable) { mAvailable -= size; mBufferStart += size; while(mBufferStart >= buffersize_) mBufferStart -= buffersize_; } else { size -= mAvailable; mAvailable = 0; mBufferStart = 0; Read(NULL, size); // mStream.Discard(size); /* unsigned char c; while(size > 0 && Read(&c, 1) != IInputStream::kEOF) { size--; }*/ } } template<size_t buffersize_> inline size_t InputStreamBuffer<buffersize_>::PeekFromBuffer(unsigned char dst[], size_t size) { size_t first_transfer = buffersize_ - mBufferStart; if(size > mAvailable) size = mAvailable; if(size <= first_transfer) { /* if (size == 1) *dst = mBuffer[mBufferStart]; else*/ memcpy(dst, &mBuffer[mBufferStart], size); } else { size_t second_transfer = size - first_transfer; memcpy(dst, &mBuffer[mBufferStart], first_transfer); memcpy(dst + first_transfer, &mBuffer[0], second_transfer); } return size; } template<size_t buffersize_> inline void InputStreamBuffer<buffersize_>::ReadFromBuffer(unsigned char dst[], size_t size) { if (dst != NULL) PeekFromBuffer(dst, size); Discard(size); } template<size_t buffersize_> inline void InputStreamBuffer<buffersize_>::ReadToBuffer(size_t size) { size_t bufferend = (mBufferStart + mAvailable) % buffersize_; size_t first_transfer = buffersize_ - bufferend; if(first_transfer > size) first_transfer = size; size_t amount = mStream.Read(&mBuffer[bufferend], first_transfer); if(amount != IInputStream::kEOF) { mAvailable += amount; if(first_transfer < size) { size -= first_transfer; amount = mStream.Read(&mBuffer[0], size); if(amount != IInputStream::kEOF) mAvailable += amount; } } } } }
{ "content_hash": "1118ce63a625a2f78f232652f4eef12d", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 94, "avg_line_length": 24.864516129032257, "alnum_prop": 0.6211728074727556, "repo_name": "tweakoz/oculusx", "id": "3b5815b3f1f349495c004b212cb1300c206f64ca", "size": "3854", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ork/inc/ork/stream/InputStreamBuffer.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "114" }, { "name": "C", "bytes": "283309" }, { "name": "C++", "bytes": "1090582" }, { "name": "CMake", "bytes": "2233" }, { "name": "Makefile", "bytes": "370" }, { "name": "Objective-C++", "bytes": "12759" }, { "name": "Python", "bytes": "29617" }, { "name": "Ruby", "bytes": "8631" }, { "name": "Shell", "bytes": "31" } ], "symlink_target": "" }
``` diff +namespace Microsoft.Build.Utilities { + public abstract class AppDomainIsolatedTask : MarshalByRefObject, ITask { + protected AppDomainIsolatedTask(); + protected AppDomainIsolatedTask(ResourceManager taskResources); + protected AppDomainIsolatedTask(ResourceManager taskResources, string helpKeywordPrefix); + public IBuildEngine BuildEngine { get; set; } + protected string HelpKeywordPrefix { get; set; } + public ITaskHost HostObject { get; set; } + public TaskLoggingHelper Log { get; } + protected ResourceManager TaskResources { get; set; } + public abstract bool Execute(); + public override object InitializeLifetimeService(); + } + public class AssemblyFoldersExInfo { + public AssemblyFoldersExInfo(RegistryHive hive, RegistryView view, string registryKey, string directoryPath, Version targetFrameworkVersion); + public string DirectoryPath { get; private set; } + public RegistryHive Hive { get; private set; } + public string Key { get; private set; } + public Version TargetFrameworkVersion { get; private set; } + public RegistryView View { get; private set; } + } + public class CanonicalTrackedInputFiles { + public CanonicalTrackedInputFiles(ITask ownerTask, ITaskItem[] tlogFiles, ITaskItem sourceFile, ITaskItem[] excludedInputPaths, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers); + public CanonicalTrackedInputFiles(ITask ownerTask, ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, ITaskItem[] excludedInputPaths, ITaskItem[] outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers); + public CanonicalTrackedInputFiles(ITask ownerTask, ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, ITaskItem[] excludedInputPaths, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers); + public CanonicalTrackedInputFiles(ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, ITaskItem[] excludedInputPaths, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers); + public CanonicalTrackedInputFiles(ITaskItem[] tlogFiles, ITaskItem[] sourceFiles, CanonicalTrackedOutputFiles outputs, bool useMinimalRebuildOptimization, bool maintainCompositeRootingMarkers); + public Dictionary<string, Dictionary<string, string>> DependencyTable { get; } + public ITaskItem[] ComputeSourcesNeedingCompilation(); + public ITaskItem[] ComputeSourcesNeedingCompilation(bool searchForSubRootsInCompositeRootingMarkers); + public bool FileIsExcludedFromDependencyCheck(string fileName); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem source); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem source, ITaskItem correspondingOutput); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem[] source); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem[] source, ITaskItem[] correspondingOutputs); + public void RemoveDependencyFromEntry(ITaskItem source, ITaskItem dependencyToRemove); + public void RemoveDependencyFromEntry(ITaskItem[] sources, ITaskItem dependencyToRemove); + public void RemoveEntriesForSource(ITaskItem source); + public void RemoveEntriesForSource(ITaskItem[] source); + public void RemoveEntryForSourceRoot(string rootingMarker); + public void SaveTlog(); + public void SaveTlog(DependencyFilter includeInTLog); + } + public class CanonicalTrackedOutputFiles { + public CanonicalTrackedOutputFiles(ITask ownerTask, ITaskItem[] tlogFiles); + public CanonicalTrackedOutputFiles(ITask ownerTask, ITaskItem[] tlogFiles, bool constructOutputsFromTLogs); + public CanonicalTrackedOutputFiles(ITaskItem[] tlogFiles); + public Dictionary<string, Dictionary<string, DateTime>> DependencyTable { get; } + public void AddComputedOutputForSourceRoot(string sourceKey, string computedOutput); + public void AddComputedOutputsForSourceRoot(string sourceKey, ITaskItem[] computedOutputs); + public void AddComputedOutputsForSourceRoot(string sourceKey, string[] computedOutputs); + public ITaskItem[] OutputsForNonCompositeSource(params ITaskItem[] sources); + public ITaskItem[] OutputsForSource(params ITaskItem[] sources); + public ITaskItem[] OutputsForSource(ITaskItem[] sources, bool searchForSubRootsInCompositeRootingMarkers); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem source); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem source, ITaskItem correspondingOutput); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem[] source); + public void RemoveDependenciesFromEntryIfMissing(ITaskItem[] source, ITaskItem[] correspondingOutputs); + public void RemoveDependencyFromEntry(ITaskItem source, ITaskItem dependencyToRemove); + public void RemoveDependencyFromEntry(ITaskItem[] sources, ITaskItem dependencyToRemove); + public void RemoveEntriesForSource(ITaskItem source); + public void RemoveEntriesForSource(ITaskItem source, ITaskItem correspondingOutput); + public void RemoveEntriesForSource(ITaskItem[] source); + public void RemoveEntriesForSource(ITaskItem[] source, ITaskItem[] correspondingOutputs); + public bool RemoveOutputForSourceRoot(string sourceRoot, string outputPathToRemove); + public string[] RemoveRootsWithSharedOutputs(ITaskItem[] sources); + public void SaveTlog(); + public void SaveTlog(DependencyFilter includeInTLog); + } + public class CommandLineBuilder { + public CommandLineBuilder(); + public CommandLineBuilder(bool quoteHyphensOnCommandLine); + protected StringBuilder CommandLine { get; } + public int Length { get; } + public void AppendFileNameIfNotNull(ITaskItem fileItem); + public void AppendFileNameIfNotNull(string fileName); + public void AppendFileNamesIfNotNull(ITaskItem[] fileItems, string delimiter); + public void AppendFileNamesIfNotNull(string[] fileNames, string delimiter); + protected void AppendFileNameWithQuoting(string fileName); + protected void AppendQuotedTextToBuffer(StringBuilder buffer, string unquotedTextToAppend); + protected void AppendSpaceIfNotEmpty(); + public void AppendSwitch(string switchName); + public void AppendSwitchIfNotNull(string switchName, ITaskItem parameter); + public void AppendSwitchIfNotNull(string switchName, ITaskItem[] parameters, string delimiter); + public void AppendSwitchIfNotNull(string switchName, string parameter); + public void AppendSwitchIfNotNull(string switchName, string[] parameters, string delimiter); + public void AppendSwitchUnquotedIfNotNull(string switchName, ITaskItem parameter); + public void AppendSwitchUnquotedIfNotNull(string switchName, ITaskItem[] parameters, string delimiter); + public void AppendSwitchUnquotedIfNotNull(string switchName, string parameter); + public void AppendSwitchUnquotedIfNotNull(string switchName, string[] parameters, string delimiter); + public void AppendTextUnquoted(string textToAppend); + protected void AppendTextWithQuoting(string textToAppend); + protected virtual bool IsQuotingRequired(string parameter); + public override string ToString(); + protected virtual void VerifyThrowNoEmbeddedDoubleQuotes(string switchName, string parameter); + } + public delegate bool DependencyFilter(string fullPath); + public enum DotNetFrameworkArchitecture { + Bitness32 = 1, + Bitness64 = 2, + Current = 0, + } + public enum ExecutableType { + Managed32Bit = 3, + Managed64Bit = 4, + ManagedIL = 2, + Native32Bit = 0, + Native64Bit = 1, + SameAsCurrentProcess = 5, + } + public static class FileTracker { + public static string CreateRootingMarkerResponseFile(ITaskItem[] sources); + public static string CreateRootingMarkerResponseFile(string rootMarker); + public static void EndTrackingContext(); + public static string EnsureFileTrackerOnPath(); + public static string EnsureFileTrackerOnPath(string rootPath); + public static bool FileIsExcludedFromDependencies(string fileName); + public static bool FileIsUnderPath(string fileName, string path); + public static string FindTrackerOnPath(); + public static bool ForceOutOfProcTracking(ExecutableType toolType); + public static bool ForceOutOfProcTracking(ExecutableType toolType, string dllName, string cancelEventName); + public static string FormatRootingMarker(ITaskItem source); + public static string FormatRootingMarker(ITaskItem source, ITaskItem output); + public static string FormatRootingMarker(ITaskItem[] sources); + public static string FormatRootingMarker(ITaskItem[] sources, ITaskItem[] outputs); + public static string GetFileTrackerPath(ExecutableType toolType); + public static string GetFileTrackerPath(ExecutableType toolType, string rootPath); + public static string GetTrackerPath(ExecutableType toolType); + public static string GetTrackerPath(ExecutableType toolType, string rootPath); + public static void ResumeTracking(); + public static void SetThreadCount(int threadCount); + public static Process StartProcess(string command, string arguments, ExecutableType toolType); + public static Process StartProcess(string command, string arguments, ExecutableType toolType, string rootFiles); + public static Process StartProcess(string command, string arguments, ExecutableType toolType, string intermediateDirectory, string rootFiles); + public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles); + public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName); + public static void StartTrackingContext(string intermediateDirectory, string taskName); + public static void StartTrackingContextWithRoot(string intermediateDirectory, string taskName, string rootMarkerResponseFile); + public static void StopTrackingAndCleanup(); + public static void SuspendTracking(); + public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles); + public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName); + public static string TrackerCommandArguments(string command, string arguments); + public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles); + public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles, string cancelEventName); + public static void WriteAllTLogs(string intermediateDirectory, string taskName); + public static void WriteContextTLogs(string intermediateDirectory, string taskName); + } + public class FlatTrackingData { + public FlatTrackingData(ITask ownerTask, ITaskItem[] tlogFiles, bool skipMissingFiles); + public FlatTrackingData(ITask ownerTask, ITaskItem[] tlogFiles, DateTime missingFileTimeUtc); + public FlatTrackingData(ITaskItem[] tlogFiles, ITaskItem[] tlogFilesToIgnore, DateTime missingFileTimeUtc); + public FlatTrackingData(ITaskItem[] tlogFiles, ITaskItem[] tlogFilesToIgnore, DateTime missingFileTimeUtc, string[] excludedInputPaths, IDictionary<string, DateTime> sharedLastWriteTimeUtcCache); + public FlatTrackingData(ITaskItem[] tlogFiles, bool skipMissingFiles); + public FlatTrackingData(ITaskItem[] tlogFiles, DateTime missingFileTimeUtc); + public IDictionary<string, DateTime> DependencyTable { get; } + public List<string> MissingFiles { get; set; } + public string NewestFileName { get; set; } + public DateTime NewestFileTime { get; set; } + public DateTime NewestFileTimeUtc { get; set; } + public string NewestTLogFileName { get; set; } + public DateTime NewestTLogTime { get; set; } + public DateTime NewestTLogTimeUtc { get; set; } + public string OldestFileName { get; set; } + public DateTime OldestFileTime { get; set; } + public DateTime OldestFileTimeUtc { get; set; } + public bool SkipMissingFiles { get; set; } + public ITaskItem[] TlogFiles { get; set; } + public bool TlogsAvailable { get; set; } + public bool TreatRootMarkersAsEntries { get; set; } + public bool FileIsExcludedFromDependencyCheck(string fileName); + public static void FinalizeTLogs(bool trackedOperationsSucceeded, ITaskItem[] readTLogNames, ITaskItem[] writeTLogNames, ITaskItem[] trackedFilesToRemoveFromTLogs); + public DateTime GetLastWriteTimeUtc(string file); + public static bool IsUpToDate(Task hostTask, UpToDateCheckType upToDateCheckType, ITaskItem[] readTLogNames, ITaskItem[] writeTLogNames); + public static bool IsUpToDate(TaskLoggingHelper Log, UpToDateCheckType upToDateCheckType, FlatTrackingData inputs, FlatTrackingData outputs); + public void SaveTlog(); + public void SaveTlog(DependencyFilter includeInTLog); + public void UpdateFileEntryDetails(); + } + public enum HostObjectInitializationStatus { + NoActionReturnFailure = 3, + NoActionReturnSuccess = 2, + UseAlternateToolToExecute = 1, + UseHostObjectToExecute = 0, + } + public abstract class Logger : ILogger { + protected Logger(); + public virtual string Parameters { get; set; } + public virtual LoggerVerbosity Verbosity { get; set; } + public virtual string FormatErrorEvent(BuildErrorEventArgs args); + public virtual string FormatWarningEvent(BuildWarningEventArgs args); + public abstract void Initialize(IEventSource eventSource); + public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity); + public virtual void Shutdown(); + } + public class MuxLogger : ILogger, INodeLogger { + public MuxLogger(); + public string Parameters { get; set; } + public LoggerVerbosity Verbosity { get; set; } + public void Initialize(IEventSource eventSource); + public void Initialize(IEventSource eventSource, int maxNodeCount); + public void RegisterLogger(int submissionId, ILogger logger); + public void Shutdown(); + public bool UnregisterLoggers(int submissionId); + } + public static class ProcessorArchitecture { + public const string AMD64 = "AMD64"; + public const string ARM = "ARM"; + public const string IA64 = "IA64"; + public const string MSIL = "MSIL"; + public const string X86 = "x86"; + public static string CurrentProcessArchitecture { get; } + } + public enum TargetDotNetFrameworkVersion { + Version11 = 0, + Version20 = 1, + Version30 = 2, + Version35 = 3, + Version40 = 4, + Version45 = 5, + VersionLatest = 5, + } + public class TargetPlatformSDK : IEquatable<TargetPlatformSDK> { + public TargetPlatformSDK(string targetPlatformIdentifier, Version targetPlatformVersion, string path); + public string Path { get; set; } + public string TargetPlatformIdentifier { get; private set; } + public Version TargetPlatformVersion { get; private set; } + public bool Equals(TargetPlatformSDK other); + public override bool Equals(object obj); + public override int GetHashCode(); + } + public abstract class Task : ITask { + protected Task(); + protected Task(ResourceManager taskResources); + protected Task(ResourceManager taskResources, string helpKeywordPrefix); + public IBuildEngine BuildEngine { get; set; } + public IBuildEngine2 BuildEngine2 { get; } + public IBuildEngine3 BuildEngine3 { get; } + public IBuildEngine4 BuildEngine4 { get; } + protected string HelpKeywordPrefix { get; set; } + public ITaskHost HostObject { get; set; } + public TaskLoggingHelper Log { get; } + protected ResourceManager TaskResources { get; set; } + public abstract bool Execute(); + } + public sealed class TaskItem : MarshalByRefObject, ITaskItem, ITaskItem2 { + public TaskItem(); + public TaskItem(ITaskItem sourceItem); + public TaskItem(string itemSpec); + public TaskItem(string itemSpec, IDictionary itemMetadata); + public string ItemSpec { get; set; } + public int MetadataCount { get; } + public ICollection MetadataNames { get; } + string Microsoft.Build.Framework.ITaskItem2.EvaluatedIncludeEscaped { get; set; } + public IDictionary CloneCustomMetadata(); + public void CopyMetadataTo(ITaskItem destinationItem); + public string GetMetadata(string metadataName); + public override object InitializeLifetimeService(); + IDictionary Microsoft.Build.Framework.ITaskItem2.CloneCustomMetadataEscaped(); + string Microsoft.Build.Framework.ITaskItem2.GetMetadataValueEscaped(string metadataName); + void Microsoft.Build.Framework.ITaskItem2.SetMetadataValueLiteral(string metadataName, string metadataValue); + public static explicit operator string (TaskItem taskItemToCast); + public void RemoveMetadata(string metadataName); + public void SetMetadata(string metadataName, string metadataValue); + public override string ToString(); + } + public class TaskLoggingHelper : MarshalByRefObject { + public TaskLoggingHelper(IBuildEngine buildEngine, string taskName); + public TaskLoggingHelper(ITask taskInstance); + protected IBuildEngine BuildEngine { get; } + public bool HasLoggedErrors { get; } + public string HelpKeywordPrefix { get; set; } + protected string TaskName { get; } + public ResourceManager TaskResources { get; set; } + public string ExtractMessageCode(string message, out string messageWithoutCodePrefix); + public virtual string FormatResourceString(string resourceName, params object[] args); + public virtual string FormatString(string unformatted, params object[] args); + public virtual string GetResourceMessage(string resourceName); + public override object InitializeLifetimeService(); + public void LogCommandLine(MessageImportance importance, string commandLine); + public void LogCommandLine(string commandLine); + public void LogCriticalMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs); + public void LogError(string message, params object[] messageArgs); + public void LogError(string subcategory, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs); + public void LogErrorFromException(Exception exception); + public void LogErrorFromException(Exception exception, bool showStackTrace); + public void LogErrorFromException(Exception exception, bool showStackTrace, bool showDetail, string file); + public void LogErrorFromResources(string messageResourceName, params object[] messageArgs); + public void LogErrorFromResources(string subcategoryResourceName, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs); + public void LogErrorWithCodeFromResources(string messageResourceName, params object[] messageArgs); + public void LogErrorWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs); + public void LogExternalProjectFinished(string message, string helpKeyword, string projectFile, bool succeeded); + public void LogExternalProjectStarted(string message, string helpKeyword, string projectFile, string targetNames); + public void LogMessage(MessageImportance importance, string message, params object[] messageArgs); + public void LogMessage(string message, params object[] messageArgs); + public void LogMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, MessageImportance importance, string message, params object[] messageArgs); + public void LogMessageFromResources(MessageImportance importance, string messageResourceName, params object[] messageArgs); + public void LogMessageFromResources(string messageResourceName, params object[] messageArgs); + public bool LogMessageFromText(string lineOfText, MessageImportance messageImportance); + public bool LogMessagesFromFile(string fileName); + public bool LogMessagesFromFile(string fileName, MessageImportance messageImportance); + public bool LogMessagesFromStream(TextReader stream, MessageImportance messageImportance); + public void LogWarning(string message, params object[] messageArgs); + public void LogWarning(string subcategory, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs); + public void LogWarningFromException(Exception exception); + public void LogWarningFromException(Exception exception, bool showStackTrace); + public void LogWarningFromResources(string messageResourceName, params object[] messageArgs); + public void LogWarningFromResources(string subcategoryResourceName, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs); + public void LogWarningWithCodeFromResources(string messageResourceName, params object[] messageArgs); + public void LogWarningWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs); + public void MarkAsInactive(); + } + public static class ToolLocationHelper { + public static string PathToSystem { get; } + public static void ClearSDKStaticCache(); + public static IList<AssemblyFoldersExInfo> GetAssemblyFoldersExInfo(string registryRoot, string targetFrameworkVersion, string registryKeySuffix, string osVersion, string platform, ProcessorArchitecture targetProcessorArchitecture); + public static string GetDisplayNameForTargetFrameworkDirectory(string targetFrameworkDirectory, FrameworkName frameworkName); + public static string GetDotNetFrameworkRootRegistryKey(TargetDotNetFrameworkVersion version); + public static string GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion version); + public static string GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion version); + public static string GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFramework(TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFramework(TargetDotNetFrameworkVersion version, DotNetFrameworkArchitecture architecture); + public static string GetPathToDotNetFrameworkFile(string fileName, TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFrameworkFile(string fileName, TargetDotNetFrameworkVersion version, DotNetFrameworkArchitecture architecture); + public static string GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotNetFrameworkVersion version); + public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotNetFrameworkVersion version, DotNetFrameworkArchitecture architecture); + public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion, DotNetFrameworkArchitecture architecture); + public static IList<string> GetPathToReferenceAssemblies(FrameworkName frameworkName); + public static IList<string> GetPathToReferenceAssemblies(string targetFrameworkRootPath, FrameworkName frameworkName); + public static IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile); + public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile); + public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget); + public static string GetPathToSystemFile(string fileName); + public static string GetPathToWindowsSdk(TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetPathToWindowsSdkFile(string fileName, TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion); + public static string GetPathToWindowsSdkFile(string fileName, TargetDotNetFrameworkVersion version, VisualStudioVersion visualStudioVersion, DotNetFrameworkArchitecture architecture); + public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion); + public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot); + public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, Version targetPlatformVersion); + public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, Version targetPlatformVersion, string[] diskRoots, string registryRoot); + public static IDictionary<string, string> GetPlatformExtensionSDKLocations(string targetPlatformIdentifier, Version targetPlatformVersion); + public static IDictionary<string, string> GetPlatformExtensionSDKLocations(string[] diskRoots, string registryRoot, string targetPlatformIdentifier, Version targetPlatformVersion); + public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion); + public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot); + public static string GetPlatformSDKLocation(string targetPlatformIdentifier, Version targetPlatformVersion); + public static string GetPlatformSDKLocation(string targetPlatformIdentifier, Version targetPlatformVersion, string[] diskRoots, string registryRoot); + public static string GetProgramFilesReferenceAssemblyRoot(); + public static IList<string> GetSDKDesignTimeFolders(string sdkRoot); + public static IList<string> GetSDKDesignTimeFolders(string sdkRoot, string targetConfiguration, string targetArchitecture); + public static IList<string> GetSDKRedistFolders(string sdkRoot); + public static IList<string> GetSDKRedistFolders(string sdkRoot, string targetConfiguration, string targetArchitecture); + public static IList<string> GetSDKReferenceFolders(string sdkRoot); + public static IList<string> GetSDKReferenceFolders(string sdkRoot, string targetConfiguration, string targetArchitecture); + public static IList<string> GetSupportedTargetFrameworks(); + public static IList<TargetPlatformSDK> GetTargetPlatformSdks(); + public static IList<TargetPlatformSDK> GetTargetPlatformSdks(string[] diskRoots, string registryRoot); + public static FrameworkName HighestVersionOfTargetFrameworkIdentifier(string targetFrameworkRootDirectory, string frameworkIdentifier); + } + public abstract class ToolTask : Task, ICancelableTask, ITask { + protected ToolTask(); + protected ToolTask(ResourceManager taskResources); + protected ToolTask(ResourceManager taskResources, string helpKeywordPrefix); + public bool EchoOff { get; set; } + protected virtual StringDictionary EnvironmentOverride { get; } + public string[] EnvironmentVariables { get; set; } + public int ExitCode { get; } + protected virtual bool HasLoggedErrors { get; } + public bool LogStandardErrorAsError { get; set; } + protected virtual Encoding ResponseFileEncoding { get; } + protected virtual Encoding StandardErrorEncoding { get; } + public string StandardErrorImportance { get; set; } + protected MessageImportance StandardErrorImportanceToUse { get; } + protected virtual MessageImportance StandardErrorLoggingImportance { get; } + protected virtual Encoding StandardOutputEncoding { get; } + public string StandardOutputImportance { get; set; } + protected MessageImportance StandardOutputImportanceToUse { get; } + protected virtual MessageImportance StandardOutputLoggingImportance { get; } + protected int TaskProcessTerminationTimeout { get; set; } + public virtual int Timeout { get; set; } + protected ManualResetEvent ToolCanceled { get; private set; } + public virtual string ToolExe { get; set; } + protected abstract string ToolName { get; } + public string ToolPath { get; set; } + public bool UseCommandProcessor { get; set; } + public bool YieldDuringToolExecution { get; set; } + protected virtual bool CallHostObjectToExecute(); + public virtual void Cancel(); + protected void DeleteTempFile(string fileName); + public override bool Execute(); + protected virtual int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands); + protected virtual string GenerateCommandLineCommands(); + protected abstract string GenerateFullPathToTool(); + protected virtual string GenerateResponseFileCommands(); + protected ProcessStartInfo GetProcessStartInfo(string pathToTool, string commandLineCommands, string responseFileSwitch); + protected virtual string GetResponseFileSwitch(string responseFilePath); + protected virtual string GetWorkingDirectory(); + protected virtual bool HandleTaskExecutionErrors(); + protected virtual HostObjectInitializationStatus InitializeHostObject(); + protected virtual void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance); + protected virtual void LogPathToTool(string toolName, string pathToTool); + protected virtual void LogToolCommand(string message); + protected virtual string ResponseFileEscape(string responseString); + protected virtual bool SkipTaskExecution(); + protected internal virtual bool ValidateParameters(); + } + public static class TrackedDependencies { + public static ITaskItem[] ExpandWildcards(ITaskItem[] expand); + } + public enum UpToDateCheckType { + InputNewerThanOutput = 0, + InputNewerThanTracking = 2, + InputOrOutputNewerThanTracking = 1, + } + public enum VisualStudioVersion { + Version100 = 0, + Version110 = 1, + VersionLatest = 1, + } +} ```
{ "content_hash": "a6235b0804bf62851fac866574a42e20", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 261, "avg_line_length": 77.61305361305361, "alnum_prop": 0.7591302258529553, "repo_name": "ericstj/standard", "id": "bedb2ce828e84177405fd7a2f13a62b6c04687a8", "size": "33325", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/comparisons/netstandard2.0_vs_net461/Microsoft.Build.Utilities.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11626" }, { "name": "C#", "bytes": "24604928" }, { "name": "CMake", "bytes": "9153" }, { "name": "PowerShell", "bytes": "69131" }, { "name": "Shell", "bytes": "64844" } ], "symlink_target": "" }
namespace blink { VirtualKeyboardOverlayChangedObserver::VirtualKeyboardOverlayChangedObserver( LocalFrame* frame) { if (frame) frame->RegisterVirtualKeyboardOverlayChangedObserver(this); } } // namespace blink
{ "content_hash": "df9aa4109ef18ba4368925bb90e1736e", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 77, "avg_line_length": 24.88888888888889, "alnum_prop": 0.7946428571428571, "repo_name": "scheib/chromium", "id": "6b230b8add6155e772fd148e8d71b408ca7ba35f", "size": "548", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/frame/virtual_keyboard_overlay_changed_observer.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.lhg.test.designpattern.command; /** * Created by liuhg on 16-3-14. */ public class CommandPatternDemo { public static void main(String[] args) { Broker broker = new Broker(); Stock stock = new Stock(); Order buyStock = new BuyStock(stock); Order sellStock = new SellStock(stock); broker.takeOrder(buyStock); broker.takeOrder(sellStock); broker.placeOrder(); } }
{ "content_hash": "b20d6dda7e41bc7cc0c52fe7ce2c5e39", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 47, "avg_line_length": 22.25, "alnum_prop": 0.6269662921348315, "repo_name": "dunyuling/javabase", "id": "ef916c9b7fd5b13c8425ad36cf6cb8e320e12c7c", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/lhg/test/designpattern/command/CommandPatternDemo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "481" }, { "name": "Groff", "bytes": "10795" }, { "name": "HTML", "bytes": "249" }, { "name": "Java", "bytes": "140317" } ], "symlink_target": "" }
void initializeScatteringDistribution( const double atomic_weight_ratio, Teuchos::RCP<MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState> >& scattering_dist ) { Teuchos::RCP<Utility::TabularOneDDistribution> delta_dist( new Utility::DeltaDistribution( 0.0 ) ); Teuchos::Array<Utility::Pair<double, Teuchos::RCP<const Utility::TabularOneDDistribution> > > raw_scattering_distribution( 2 ); raw_scattering_distribution[0].first = 1e-11; raw_scattering_distribution[0].second = delta_dist; raw_scattering_distribution[1].first = 2e1; raw_scattering_distribution[1].second = delta_dist; Teuchos::RCP<MonteCarlo::NuclearScatteringAngularDistribution> angular_dist( new MonteCarlo::NuclearScatteringAngularDistribution( raw_scattering_distribution ) ); // Q value is 1 and A is 1 // param_a = (A + 1)/A * |Q| = 2.0 // param_b = (A/(A + 1)^2 = 0.25 Teuchos::RCP<MonteCarlo::NuclearScatteringEnergyDistribution> energy_dist( new MonteCarlo::AceLaw3NuclearScatteringEnergyDistribution( 6.516454, 0.8848775 ) ); scattering_dist.reset( new MonteCarlo::IndependentEnergyAngleNuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState,MonteCarlo::CMSystemConversionPolicy>( atomic_weight_ratio, energy_dist, angular_dist ) ); } //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that an incoming neutron can be scattered TEUCHOS_UNIT_TEST( InelasticLevelNeutronScatteringDistribution, scatterParticle_hydrogen ) { Teuchos::RCP<MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState> > scattering_dist; initializeScatteringDistribution( 15.857510, scattering_dist ); MonteCarlo::NeutronState neutron( 0ull ); double initial_angle[3]; initial_angle[0] = 0.0; initial_angle[1] = 0.0; initial_angle[2] = 1.0; neutron.setDirection( initial_angle ); double start_energy = 7.0; neutron.setEnergy( start_energy ); scattering_dist->scatterParticle( neutron, 2.53010e-8 ); TEST_FLOATING_EQUALITY( neutron.getEnergy(), 0.452512, 1e-6); double angle = Utility::calculateCosineOfAngleBetweenVectors( initial_angle, neutron.getDirection() ); TEST_FLOATING_EQUALITY( angle, 0.233314, 1e-6); // start_energy = 5.0; // neutron.setEnergy( start_energy ); // // scattering_dist->scatterParticle( neutron, 2.53010e-8 ); // // TEST_FLOATING_EQUALITY( neutron.getEnergy(), 2.0, 1e-15 ); } //---------------------------------------------------------------------------// // Custom main function //---------------------------------------------------------------------------// int main( int argc, char** argv ) { // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); Teuchos::GlobalMPISession mpiSession( &argc, &argv ); return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv ); } //---------------------------------------------------------------------------// // tstInelasticLevelNeutronScatteringDistribution.cpp //---------------------------------------------------------------------------//
{ "content_hash": "e0e03b2e9b71394ed17706c6adc9bb0c", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 161, "avg_line_length": 39.2093023255814, "alnum_prop": 0.6159549228944247, "repo_name": "lkersting/SCR-2123", "id": "8c1bd2d710dacd60c67b74c7b5cf4c11c266997f", "size": "4476", "binary": false, "copies": "1", "ref": "refs/heads/0.2.0", "path": "packages/monte_carlo/collision/native/test/tstInelasticLevelNeutronScatteringDistribution.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4738" }, { "name": "C++", "bytes": "10606387" }, { "name": "CMake", "bytes": "140280" }, { "name": "FORTRAN", "bytes": "33135" }, { "name": "Python", "bytes": "4630" }, { "name": "Shell", "bytes": "12702" } ], "symlink_target": "" }
package com.allanbank.mongodb.client; import static com.allanbank.mongodb.AnswerCallback.callback; import static com.allanbank.mongodb.bson.builder.BuilderFactory.a; import static com.allanbank.mongodb.bson.builder.BuilderFactory.d; import static com.allanbank.mongodb.bson.builder.BuilderFactory.e; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.allanbank.mongodb.Callback; import com.allanbank.mongodb.Durability; import com.allanbank.mongodb.MongoClientConfiguration; import com.allanbank.mongodb.MongoDatabase; import com.allanbank.mongodb.Version; import com.allanbank.mongodb.bson.Document; import com.allanbank.mongodb.bson.DocumentAssignable; import com.allanbank.mongodb.bson.builder.BuilderFactory; import com.allanbank.mongodb.bson.element.ObjectId; import com.allanbank.mongodb.client.message.BatchedWriteCommand; import com.allanbank.mongodb.client.message.Command; import com.allanbank.mongodb.client.message.Delete; import com.allanbank.mongodb.client.message.GetLastError; import com.allanbank.mongodb.client.message.Insert; import com.allanbank.mongodb.client.message.Reply; import com.allanbank.mongodb.client.message.Update; import com.allanbank.mongodb.client.state.Server; /** * BatchedAsyncMongoCollectionImplTest provides tests for the * {@link BatchedAsyncMongoCollectionImpl} class. * * @copyright 2014, Allanbank Consulting, Inc., All Rights Reserved */ public class BatchedAsyncMongoCollectionImplTest { /** The client the collection interacts with. */ private Client myMockClient = null; /** The parent database for the collection. */ private MongoDatabase myMockDatabase = null; /** The stats for our fake cluster. */ private ClusterStats myMockStats = null; /** The instance under test. */ private BatchedAsyncMongoCollectionImpl myTestInstance = null; /** * Creates the base set of objects for the test. */ @Before public void setUp() { myMockClient = EasyMock.createMock(SerialClientImpl.class); myMockDatabase = EasyMock.createMock(MongoDatabase.class); myMockStats = EasyMock.createMock(ClusterStats.class); myTestInstance = new BatchedAsyncMongoCollectionImpl(myMockClient, myMockDatabase, "test"); expect(myMockClient.getConfig()).andReturn( new MongoClientConfiguration()).anyTimes(); } /** * Cleans up the base set of objects for the test. */ @After public void tearDown() { myMockClient = null; myMockDatabase = null; myTestInstance = null; } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#cancel()}. * * @throws InterruptedException * On a test failure. */ @SuppressWarnings("unchecked") @Test public void testCancel() throws InterruptedException { final Document doc = BuilderFactory.start().build(); final Callback<Long> mockCallback = createMock(Callback.class); expect(myMockDatabase.getName()).andReturn("test").times(8); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 4); replay(mockCallback); final Future<Long> future1 = myTestInstance.deleteAsync(doc); final Future<Long> future2 = myTestInstance.deleteAsync(doc); final Future<Long> future3 = myTestInstance.deleteAsync(doc); myTestInstance.deleteAsync(mockCallback, doc); verify(mockCallback); reset(mockCallback); // No sends. mockCallback.exception(anyObject(CancellationException.class)); expectLastCall(); replay(mockCallback); myTestInstance.cancel(); myTestInstance.flush(); verify(mockCallback); try { future1.get(); fail("The future should have been cancelled."); } catch (final ExecutionException expected) { assertThat(expected.getCause(), instanceOf(CancellationException.class)); } try { future2.get(); fail("The future should have been cancelled."); } catch (final ExecutionException expected) { assertThat(expected.getCause(), instanceOf(CancellationException.class)); } try { future3.get(); fail("The future should have been cancelled."); } catch (final ExecutionException expected) { assertThat(expected.getCause(), instanceOf(CancellationException.class)); } } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#close()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testCloseNoBatchDeleteCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 1) .build(); final Delete message = new Delete("test", "test", doc, false); final GetLastError getLastError = new GetLastError("test", false, false, 1, 0); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); replay(); final Future<Long> future1 = myTestInstance.deleteAsync(doc); final Future<Long> future2 = myTestInstance.deleteAsync(doc); final Future<Long> future3 = myTestInstance.deleteAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_4, Version.VERSION_2_4)); myMockClient.send(eq(message), eq(getLastError), callback(reply(replyDoc))); expectLastCall().times(3); replay(); myTestInstance.close(); verify(); assertThat(future1.get(), is(1L)); assertThat(future2.get(), is(1L)); assertThat(future3.get(), is(1L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#close()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testCloseNoBatchUpdateCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().build(); final Document update = BuilderFactory.start().addInteger("foo", 1) .build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 1) .build(); final Update message = new Update("test", "test", doc, update, false, false); final GetLastError getLastError = new GetLastError("test", false, false, 1, 0); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(3); replay(); final Future<Long> future1 = myTestInstance.updateAsync(doc, update, Durability.ACK); final Future<Long> future2 = myTestInstance.updateAsync(doc, update, Durability.ACK); final Future<Long> future3 = myTestInstance.updateAsync(doc, update, Durability.ACK); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_4, Version.VERSION_2_4)); myMockClient.send(eq(message), eq(getLastError), callback(reply(replyDoc))); expectLastCall().times(3); replay(); myTestInstance.close(); verify(); assertThat(future1.get(), is(1L)); assertThat(future2.get(), is(1L)); assertThat(future3.get(), is(1L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#close()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testCloseWithBatchDeleteCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 1) .build(); final DocumentAssignable deleteCommand = d( e("delete", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("deletes", a(d(e("q", doc), e("limit", 0)), d(e("q", doc), e("limit", 0)), d(e("q", doc), e("limit", 0))))); final Command deleteMessage = new BatchedWriteCommand("test", "test", deleteCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expectLastCall(); replay(); final Future<Long> future1 = myTestInstance.deleteAsync(doc); final Future<Long> future2 = myTestInstance.deleteAsync(doc); final Future<Long> future3 = myTestInstance.deleteAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(deleteMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.setBatchDeletes(true); myTestInstance.close(); verify(); assertThat(future1.get(), is(1L)); assertThat(future2.get(), is(1L)); assertThat(future3.get(), is(1L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#close()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testCloseWithBatchUpdateCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().build(); final Document update = BuilderFactory.start().addInteger("foo", 1) .build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 1) .build(); final DocumentAssignable updateCommand = d( e("update", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("updates", a(d(e("q", doc), e("u", update)), d(e("q", doc), e("u", update)), d(e("q", doc), e("u", update))))); final Command updateMessage = new BatchedWriteCommand("test", "test", updateCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(3); replay(); final Future<Long> future1 = myTestInstance.updateAsync(doc, update, Durability.ACK); final Future<Long> future2 = myTestInstance.updateAsync(doc, update, Durability.ACK); final Future<Long> future3 = myTestInstance.updateAsync(doc, update, Durability.ACK); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(updateMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.setBatchUpdates(true); myTestInstance.close(); verify(); assertThat(future1.get(), is(1L)); assertThat(future2.get(), is(1L)); assertThat(future3.get(), is(1L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushNoBatchInsertCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final Insert message = new Insert("test", "test", Collections.singletonList(doc), false); final GetLastError getLastError = new GetLastError("test", false, false, 1, 0); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(3); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Integer> future2 = myTestInstance.insertAsync(doc); final Future<Integer> future3 = myTestInstance.insertAsync(doc); verify(); reset(); // No batch command. expect(myMockClient.getClusterStats()).andReturn(myMockStats); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_4, Version.VERSION_2_4)); myMockClient.send(eq(message), eq(getLastError), callback(reply(replyDoc))); expectLastCall().times(3); replay(); myTestInstance.flush(); verify(); assertThat(future1.get(), is(2)); assertThat(future2.get(), is(2)); assertThat(future3.get(), is(2)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushWithBatchInsertCommand() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().add("_id", new ObjectId()) .build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final DocumentAssignable insertCommand = d(e("insert", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("documents", a(doc, doc, doc))); final Command insertMessage = new BatchedWriteCommand("test", "test", insertCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(3); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Integer> future2 = myTestInstance.insertAsync(doc); final Future<Integer> future3 = myTestInstance.insertAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(insertMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.flush(); verify(); assertThat(future1.get(), is(1)); assertThat(future2.get(), is(1)); assertThat(future3.get(), is(1)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushWithBatchInterleavedCommands() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().add("_id", new ObjectId()) .build(); final Document update = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final DocumentAssignable insertCommand = d(e("insert", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("documents", a(doc))); final Command insertMessage = new BatchedWriteCommand("test", "test", insertCommand.asDocument()); final Update updateMessage = new Update("test", "test", doc, update, false, false); final Delete deleteMessage = new Delete("test", "test", doc, false); final GetLastError getLastError = new GetLastError("test", false, false, 1, 0); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Long> future2 = myTestInstance.updateAsync(doc, update); final Future<Long> future3 = myTestInstance.deleteAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(4); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE).times(3); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT).times(3); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(insertMessage), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(updateMessage), eq(getLastError), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(deleteMessage), eq(getLastError), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.flush(); verify(); assertThat(future1.get(), is(1)); // Note - fixed to Match the number of // documents. assertThat(future2.get(), is(2L)); assertThat(future3.get(), is(2L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushWithBatchInterleavedCommandsAndCanBatchDeleteWithMultipleDeletes() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().add("_id", new ObjectId()) .build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final DocumentAssignable insertCommand = d(e("insert", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("documents", a(doc))); final Command insertMessage = new BatchedWriteCommand("test", "test", insertCommand.asDocument()); final DocumentAssignable deleteCommand = d( e("delete", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("deletes", a(d(e("q", doc), e("limit", 0)), d(e("q", doc), e("limit", 0))))); final Command deleteMessage = new BatchedWriteCommand("test", "test", deleteCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Long> future2 = myTestInstance.deleteAsync(doc); final Future<Long> future3 = myTestInstance.deleteAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(insertMessage), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(deleteMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.setBatchDeletes(true); myTestInstance.setBatchUpdates(true); myTestInstance.flush(); verify(); assertThat(future1.get(), is(1)); // Note - fixed to Match the number of // documents. assertThat(future2.get(), is(2L)); assertThat(future3.get(), is(2L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushWithBatchInterleavedCommandsAndCanBatchUpdateAndDelete() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().add("_id", new ObjectId()) .build(); final Document update = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final DocumentAssignable insertCommand = d(e("insert", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("documents", a(doc))); final Command insertMessage = new BatchedWriteCommand("test", "test", insertCommand.asDocument()); final DocumentAssignable updateCommand = d(e("update", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("updates", a(d(e("q", doc), e("u", update))))); final Command updateMessage = new BatchedWriteCommand("test", "test", updateCommand.asDocument()); final DocumentAssignable deleteCommand = d(e("delete", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("deletes", a(d(e("q", doc), e("limit", 0))))); final Command deleteMessage = new BatchedWriteCommand("test", "test", deleteCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Long> future2 = myTestInstance.updateAsync(doc, update); final Future<Long> future3 = myTestInstance.deleteAsync(doc); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(insertMessage), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(updateMessage), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(deleteMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.setBatchDeletes(true); myTestInstance.setBatchUpdates(true); myTestInstance.flush(); verify(); assertThat(future1.get(), is(1)); // Note - fixed to Match the number of // documents. assertThat(future2.get(), is(2L)); assertThat(future3.get(), is(2L)); } /** * Test method for {@link BatchedAsyncMongoCollectionImpl#flush()}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. */ @Test public void testFlushWithBatchInterleavedCommandsAndCanBatchUpdateWithMultipleUpdates() throws InterruptedException, ExecutionException { final Document doc = BuilderFactory.start().add("_id", new ObjectId()) .build(); final Document update = BuilderFactory.start().build(); final Document replyDoc = BuilderFactory.start().addInteger("n", 2) .build(); final DocumentAssignable insertCommand = d(e("insert", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("documents", a(doc))); final Command insertMessage = new BatchedWriteCommand("test", "test", insertCommand.asDocument()); final DocumentAssignable updateCommand = d( e("update", "test"), e("ordered", false), e("writeConcern", d(e("w", 1))), e("updates", a(d(e("q", doc), e("u", update)), d(e("q", doc), e("u", update))))); final Command updateMessage = new BatchedWriteCommand("test", "test", updateCommand.asDocument()); expect(myMockDatabase.getName()).andReturn("test").times(6); expect(myMockDatabase.getDurability()).andReturn(Durability.ACK).times( 3); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(3); replay(); final Future<Integer> future1 = myTestInstance.insertAsync(doc); final Future<Long> future2 = myTestInstance.updateAsync(doc, update); final Future<Long> future3 = myTestInstance.updateAsync(doc, update); verify(); reset(); expect(myMockClient.getClusterStats()).andReturn(myMockStats).times(2); expect(myMockStats.getServerVersionRange()).andReturn( VersionRange.range(Version.VERSION_2_6, Version.VERSION_2_6)); expect(myMockStats.getSmallestMaxBsonObjectSize()).andReturn( (long) Client.MAX_DOCUMENT_SIZE); expect(myMockStats.getSmallestMaxBatchedWriteOperations()).andReturn( Server.MAX_BATCHED_WRITE_OPERATIONS_DEFAULT); expect(myMockDatabase.getName()).andReturn("test"); myMockClient.send(eq(insertMessage), callback(reply(replyDoc))); expectLastCall(); myMockClient.send(eq(updateMessage), callback(reply(replyDoc))); expectLastCall(); replay(); myTestInstance.setBatchDeletes(true); myTestInstance.setBatchUpdates(true); myTestInstance.flush(); verify(); assertThat(future1.get(), is(1)); // Note - fixed to match the number of // documents. assertThat(future2.get(), is(2L)); assertThat(future3.get(), is(2L)); } /** * Performs a {@link EasyMock#replay(Object...)} on the provided mocks and * the {@link #myMockClient} and {@link #myMockDatabase} objects. * * @param mocks * The mock to replay. */ private void replay(final Object... mocks) { EasyMock.replay(mocks); EasyMock.replay(myMockClient, myMockDatabase, myMockStats); } /** * Creates a reply around the document. * * @param replyDoc * The document to include in the reply. * @return The {@link Reply} */ private Reply reply(final Document... replyDoc) { return new Reply(1, 0, 0, Arrays.asList(replyDoc), false, false, false, false); } /** * Performs a {@link EasyMock#reset(Object...)} on the provided mocks and * the {@link #myMockClient} and {@link #myMockDatabase} objects. * * @param mocks * The mock to replay. */ private void reset(final Object... mocks) { EasyMock.reset(mocks); EasyMock.reset(myMockClient, myMockDatabase, myMockStats); } /** * Performs a {@link EasyMock#verify(Object...)} on the provided mocks and * the {@link #myMockClient} and {@link #myMockDatabase} objects. * * @param mocks * The mock to replay. */ private void verify(final Object... mocks) { EasyMock.verify(mocks); EasyMock.verify(myMockClient, myMockDatabase, myMockStats); } }
{ "content_hash": "f23912de5b7cfc2037c33e8d777c9932", "timestamp": "", "source": "github", "line_count": 831, "max_line_length": 91, "avg_line_length": 38.30324909747292, "alnum_prop": 0.6161168708765316, "repo_name": "allanbank/mongodb-async-driver", "id": "3252b42cd17b1d2ea91d4ce6a8cd14a383b4be34", "size": "32570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/allanbank/mongodb/client/BatchedAsyncMongoCollectionImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6914627" }, { "name": "JavaScript", "bytes": "4075" }, { "name": "Shell", "bytes": "4566" } ], "symlink_target": "" }
<?php namespace workshop\BlogBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * Category * * @ORM\Table() * @ORM\Entity(repositoryClass="workshop\BlogBundle\Entity\CategoryRepository") * @ORM\HasLifecycleCallbacks */ class Category { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var string * * @ORM\Column(name="slug", type="string", length=255) */ private $slug; /** * @ORM\OneToMany(targetEntity="Post",mappedBy="category") * @ORM\OrderBy({"date" = "DESC"}) * */ private $posts; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Category */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Constructor */ public function __construct() { $this->posts = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add posts * * @param \workshop\BlogBundle\Entity\Post $posts * @return Category */ public function addPost(\workshop\BlogBundle\Entity\Post $posts) { $this->posts[] = $posts; return $this; } /** * Remove posts * * @param \workshop\BlogBundle\Entity\Post $posts */ public function removePost(\workshop\BlogBundle\Entity\Post $posts) { $this->posts->removeElement($posts); } /** * Get posts * * @return \Doctrine\Common\Collections\Collection */ public function getPosts() { return $this->posts; } /** * Set slug * * @param string $slug * @return Category */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } public function __toString() { return $this->getName(); } /** * @ORM\PrePersist */ public function BeforeSaveData() { $this->setSlug(strtolower(str_replace(' ','-',trim($this->getName(),'.')))); } }
{ "content_hash": "cc577147285119e44a4f27f9da0573e7", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 83, "avg_line_length": 16.838509316770185, "alnum_prop": 0.5094061232017706, "repo_name": "neoshadybeat/workshop-uca-sf2", "id": "22ee30d6c08e6d5789f6c34347b6399c7de328f0", "size": "2711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/workshop/BlogBundle/Entity/Category.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1" }, { "name": "PHP", "bytes": "100032" }, { "name": "Perl", "bytes": "794" } ], "symlink_target": "" }
/** * */ package test.aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.core.Ordered; @Aspect("pertarget(execution(* *.getSpouse()))") public class PerTargetAspect implements Ordered { public int count; private int order = Ordered.LOWEST_PRECEDENCE; @Around("execution(int *.getAge())") public int returnCountAsAge() { return count++; } @Before("execution(void *.set*(int))") public void countSetter() { ++count; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } }
{ "content_hash": "cd0a14c10e86858985b1e7b19069c67a", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 49, "avg_line_length": 18.18918918918919, "alnum_prop": 0.711738484398217, "repo_name": "shivpun/spring-framework", "id": "aaa2c6ed45f25129fbde7e42f9a0941d6040ae42", "size": "673", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spring-context/src/test/java/test/aspect/PerTargetAspect.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "6137" }, { "name": "Groovy", "bytes": "3685" }, { "name": "HTML", "bytes": "713" }, { "name": "Java", "bytes": "9777605" } ], "symlink_target": "" }
// Copyright John Maddock 2006. // Use, modification and distribution are subject to 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) #ifndef BOOST_STATS_LOGNORMAL_HPP #define BOOST_STATS_LOGNORMAL_HPP // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3669.htm // http://mathworld.wolfram.com/LogNormalDistribution.html // http://en.wikipedia.org/wiki/Lognormal_distribution #include <boost/math/distributions/fwd.hpp> #include <boost/math/distributions/normal.hpp> #include <boost/math/special_functions/expm1.hpp> #include <boost/math/distributions/detail/common_error_handling.hpp> #include <utility> namespace boost{ namespace math { namespace detail { template <class RealType, class Policy> inline bool check_lognormal_x( const char* function, RealType const& x, RealType* result, const Policy& pol) { if((x < 0) || !(boost::math::isfinite)(x)) { *result = policies::raise_domain_error<RealType>( function, "Random variate is %1% but must be >= 0 !", x, pol); return false; } return true; } } // namespace detail template <class RealType = double, class Policy = policies::policy<> > class lognormal_distribution { public: typedef RealType value_type; typedef Policy policy_type; lognormal_distribution(RealType location = 0, RealType scale = 1) : m_location(location), m_scale(scale) { RealType result; detail::check_scale("boost::math::lognormal_distribution<%1%>::lognormal_distribution", scale, &result, Policy()); } RealType location()const { return m_location; } RealType scale()const { return m_scale; } private: // // Data members: // RealType m_location; // distribution location. RealType m_scale; // distribution scale. }; typedef lognormal_distribution<double> lognormal; template <class RealType, class Policy> inline const std::pair<RealType, RealType> range(const lognormal_distribution<RealType, Policy>& /*dist*/) { // Range of permissible values for random variable x is >0 to +infinity. using boost::math::tools::max_value; return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); } template <class RealType, class Policy> inline const std::pair<RealType, RealType> support(const lognormal_distribution<RealType, Policy>& /*dist*/) { // Range of supported values for random variable x. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero. using boost::math::tools::max_value; return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); } template <class RealType, class Policy> RealType pdf(const lognormal_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_MATH_STD_USING // for ADL of std functions RealType mu = dist.location(); RealType sigma = dist.scale(); static const char* function = "boost::math::pdf(const lognormal_distribution<%1%>&, %1%)"; RealType result; if(0 == detail::check_scale(function, sigma, &result, Policy())) return result; if(0 == detail::check_lognormal_x(function, x, &result, Policy())) return result; if(x == 0) return 0; RealType exponent = log(x) - mu; exponent *= -exponent; exponent /= 2 * sigma * sigma; result = exp(exponent); result /= sigma * sqrt(2 * constants::pi<RealType>()) * x; return result; } template <class RealType, class Policy> inline RealType cdf(const lognormal_distribution<RealType, Policy>& dist, const RealType& x) { BOOST_MATH_STD_USING // for ADL of std functions static const char* function = "boost::math::cdf(const lognormal_distribution<%1%>&, %1%)"; RealType result; if(0 == detail::check_lognormal_x(function, x, &result, Policy())) return result; if(x == 0) return 0; normal_distribution<RealType, Policy> norm(dist.location(), dist.scale()); return cdf(norm, log(x)); } template <class RealType, class Policy> inline RealType quantile(const lognormal_distribution<RealType, Policy>& dist, const RealType& p) { BOOST_MATH_STD_USING // for ADL of std functions static const char* function = "boost::math::quantile(const lognormal_distribution<%1%>&, %1%)"; RealType result; if(0 == detail::check_probability(function, p, &result, Policy())) return result; if(p == 0) return 0; if(p == 1) return policies::raise_overflow_error<RealType>(function, 0, Policy()); normal_distribution<RealType, Policy> norm(dist.location(), dist.scale()); return exp(quantile(norm, p)); } template <class RealType, class Policy> inline RealType cdf(const complemented2_type<lognormal_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING // for ADL of std functions static const char* function = "boost::math::cdf(const lognormal_distribution<%1%>&, %1%)"; RealType result; if(0 == detail::check_lognormal_x(function, c.param, &result, Policy())) return result; if(c.param == 0) return 1; normal_distribution<RealType, Policy> norm(c.dist.location(), c.dist.scale()); return cdf(complement(norm, log(c.param))); } template <class RealType, class Policy> inline RealType quantile(const complemented2_type<lognormal_distribution<RealType, Policy>, RealType>& c) { BOOST_MATH_STD_USING // for ADL of std functions static const char* function = "boost::math::quantile(const lognormal_distribution<%1%>&, %1%)"; RealType result; if(0 == detail::check_probability(function, c.param, &result, Policy())) return result; if(c.param == 1) return 0; if(c.param == 0) return policies::raise_overflow_error<RealType>(function, 0, Policy()); normal_distribution<RealType, Policy> norm(c.dist.location(), c.dist.scale()); return exp(quantile(complement(norm, c.param))); } template <class RealType, class Policy> inline RealType mean(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions RealType mu = dist.location(); RealType sigma = dist.scale(); RealType result; if(0 == detail::check_scale("boost::math::mean(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return exp(mu + sigma * sigma / 2); } template <class RealType, class Policy> inline RealType variance(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions RealType mu = dist.location(); RealType sigma = dist.scale(); RealType result; if(0 == detail::check_scale("boost::math::variance(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return boost::math::expm1(sigma * sigma, Policy()) * exp(2 * mu + sigma * sigma); } template <class RealType, class Policy> inline RealType mode(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions RealType mu = dist.location(); RealType sigma = dist.scale(); RealType result; if(0 == detail::check_scale("boost::math::mode(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return exp(mu - sigma * sigma); } template <class RealType, class Policy> inline RealType median(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions RealType mu = dist.location(); return exp(mu); // e^mu } template <class RealType, class Policy> inline RealType skewness(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions //RealType mu = dist.location(); RealType sigma = dist.scale(); RealType ss = sigma * sigma; RealType ess = exp(ss); RealType result; if(0 == detail::check_scale("boost::math::skewness(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return (ess + 2) * sqrt(boost::math::expm1(ss, Policy())); } template <class RealType, class Policy> inline RealType kurtosis(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions //RealType mu = dist.location(); RealType sigma = dist.scale(); RealType ss = sigma * sigma; RealType result; if(0 == detail::check_scale("boost::math::kurtosis(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return exp(4 * ss) + 2 * exp(3 * ss) + 3 * exp(2 * ss) - 3; } template <class RealType, class Policy> inline RealType kurtosis_excess(const lognormal_distribution<RealType, Policy>& dist) { BOOST_MATH_STD_USING // for ADL of std functions // RealType mu = dist.location(); RealType sigma = dist.scale(); RealType ss = sigma * sigma; RealType result; if(0 == detail::check_scale("boost::math::kurtosis_excess(const lognormal_distribution<%1%>&)", sigma, &result, Policy())) return result; return exp(4 * ss) + 2 * exp(3 * ss) + 3 * exp(2 * ss) - 6; } } // namespace math } // namespace boost // This include must be at the end, *after* the accessors // for this distribution have been defined, in order to // keep compilers that support two-phase lookup happy. #include <boost/math/distributions/detail/derived_accessors.hpp> #endif // BOOST_STATS_STUDENTS_T_HPP
{ "content_hash": "26262996ce999127373e14328af44930", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 125, "avg_line_length": 31.529032258064515, "alnum_prop": 0.661244117045222, "repo_name": "pennwin2013/netsvr", "id": "5b2d892ec25c7ed6a14945824812256c4bf8ad65", "size": "9774", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "include/boost/math/distributions/lognormal.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "67355" }, { "name": "C++", "bytes": "52439988" }, { "name": "Python", "bytes": "2525" } ], "symlink_target": "" }
package com.fifino.patterns.composite; import java.util.ArrayList; import java.util.List; /** * Created by porfiriopartida on 2/19/16. */ public class EntityComposite extends Entity { private List<Entity> entities; public EntityComposite(){ entities = new ArrayList<Entity>(); } @Override public void addEntity(Entity e) { entities.add(e); } @Override public String getInfo() { String info = getName() + "\n"; for (Entity entity : entities){ info += " " + entity.getInfo() + "\n"; } return info; } }
{ "content_hash": "ab0fdcf488e33d6ad1dc9a9346698ba6", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 51, "avg_line_length": 21.535714285714285, "alnum_prop": 0.593698175787728, "repo_name": "ppartida/jdesign-patterns", "id": "c32f0a28f807a1b013c5d4052d73a208018fcdda", "size": "603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/fifino/patterns/composite/EntityComposite.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "55750" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: arch/mips/stacktrace.cc File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="classes.html"><span>Classes</span></a></li> <li id="current"><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul></div> <h1>arch/mips/stacktrace.cc File Reference</h1><code>#include &lt;string&gt;</code><br> <code>#include &quot;<a class="el" href="mips_2isa__traits_8hh-source.html">arch/mips/isa_traits.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="mips_2stacktrace_8hh-source.html">arch/mips/stacktrace.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="mips_2vtophys_8hh-source.html">arch/mips/vtophys.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="bitfield_8hh-source.html">base/bitfield.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="base_2trace_8hh-source.html">base/trace.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="cpu_2base_8hh-source.html">cpu/base.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="thread__context_8hh-source.html">cpu/thread_context.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="fs__translating__port__proxy_8hh-source.html">mem/fs_translating_port_proxy.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="sim_2system_8hh-source.html">sim/system.hh</a>&quot;</code><br> <p> <a href="mips_2stacktrace_8cc-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> </table> <hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:39:01 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
{ "content_hash": "473a3d172f370e61071798b9c16f9a2f", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 140, "avg_line_length": 55.15686274509804, "alnum_prop": 0.6441521507287593, "repo_name": "wnoc-drexel/gem5-stable", "id": "44f6dc467a2d9708a4a5d75cb41879ce0d5b18d1", "size": "2813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/doxygen/html/mips_2stacktrace_8cc.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "239800" }, { "name": "C", "bytes": "957228" }, { "name": "C++", "bytes": "13915041" }, { "name": "CSS", "bytes": "9813" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Groff", "bytes": "11130043" }, { "name": "HTML", "bytes": "132838214" }, { "name": "Java", "bytes": "3096" }, { "name": "Makefile", "bytes": "20709" }, { "name": "PHP", "bytes": "10107" }, { "name": "Perl", "bytes": "36183" }, { "name": "Protocol Buffer", "bytes": "3246" }, { "name": "Python", "bytes": "3739380" }, { "name": "Shell", "bytes": "49333" }, { "name": "Visual Basic", "bytes": "2884" } ], "symlink_target": "" }
<?php namespace HB\ProxMoxBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('hb_prox_mox'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "b273e1fc73e87517f6a5175dfeed5d82", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.20689655172414, "alnum_prop": 0.7146118721461188, "repo_name": "HumanBooster/SymfonyProxMox", "id": "9911ad4a6788894089876ca702ceedb128a4ba8f", "size": "876", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/HB/ProxMoxBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "PHP", "bytes": "53567" } ], "symlink_target": "" }
namespace boost { namespace detail { namespace multi_array { template <int NumRanges, int NumDims> struct index_gen { private: typedef ::boost::detail::multi_array::index index; typedef ::boost::detail::multi_array::size_type size_type; typedef index_range<index,size_type> range; public: template <int Dims, int Ranges> struct gen_type { typedef index_gen<Ranges,Dims> type; }; typedef typename range_list_generator<range,NumRanges>::type range_list; range_list ranges_; index_gen() { } template <int ND> explicit index_gen(const index_gen<NumRanges-1,ND>& rhs, const range& r) { std::copy(rhs.ranges_.begin(),rhs.ranges_.end(),ranges_.begin()); *ranges_.rbegin() = r; } index_gen<NumRanges+1,NumDims+1> operator[](const range& r) const { index_gen<NumRanges+1,NumDims+1> tmp; std::copy(ranges_.begin(),ranges_.end(),tmp.ranges_.begin()); *tmp.ranges_.rbegin() = r; return tmp; } index_gen<NumRanges+1,NumDims> operator[](index idx) const { index_gen<NumRanges+1,NumDims> tmp; std::copy(ranges_.begin(),ranges_.end(),tmp.ranges_.begin()); *tmp.ranges_.rbegin() = range(idx); return tmp; } static index_gen<0,0> indices() { return index_gen<0,0>(); } }; } // namespace multi_array } // namespace detail } // namespace boost #endif
{ "content_hash": "c30acdd3b1a6293811923727ddaedcc3", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 74, "avg_line_length": 22.915254237288135, "alnum_prop": 0.650887573964497, "repo_name": "kumakoko/KumaGL", "id": "a4fdaced7ad8ccd9c5579daebf46ec6427ca3ae9", "size": "2051", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "third_lib/boost/1.75.0/boost/multi_array/index_gen.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "763" }, { "name": "Batchfile", "bytes": "1610" }, { "name": "C", "bytes": "10066221" }, { "name": "C++", "bytes": "122279207" }, { "name": "CMake", "bytes": "32438" }, { "name": "CSS", "bytes": "97842" }, { "name": "GLSL", "bytes": "288465" }, { "name": "HTML", "bytes": "28003047" }, { "name": "JavaScript", "bytes": "512828" }, { "name": "M4", "bytes": "10000" }, { "name": "Makefile", "bytes": "12990" }, { "name": "Objective-C", "bytes": "100340" }, { "name": "Objective-C++", "bytes": "2520" }, { "name": "Perl", "bytes": "6275" }, { "name": "Roff", "bytes": "332021" }, { "name": "Ruby", "bytes": "9186" }, { "name": "Shell", "bytes": "37826" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; namespace Foundation { /// <summary> /// Enhances an <see cref="IEnumerable"/> collection by providing pagination information. /// </summary> public interface IPaginatedCollection : IEnumerable { /// <summary> /// Gets or sets the current page number. /// </summary> /// <value>The page.</value> int Page { get; } /// <summary> /// Gets or sets the number of records to return per page. /// </summary> /// <value>The size of the page.</value> int PageSize { get; } /// <summary> /// Gets the total number of records. /// </summary> /// <value>The record count.</value> int RecordCount { get; } /// <summary> /// Gets the total number of pages. /// </summary> /// <value>The page count.</value> int PageCount { get; } /// <summary> /// Gets a value indicating whether there is a page of results preceding this one. /// </summary> /// <value> /// <c>true</c> if this instance has a previous page; otherwise, <c>false</c>. /// </value> bool HasPreviousPage { get; } /// <summary> /// Gets a value indicating whether there is another page of results following this one. /// </summary> /// <value> /// <c>true</c> if this instance has a next page; otherwise, <c>false</c>. /// </value> bool HasNextPage { get; } /// <summary> /// A collection of names for the pages. Usually this defaults to the page numbers but can /// be changed depending on the pagination strategy, i.e. alphabetical names for alphabetical pagination /// </summary> IEnumerable<string> PageNames { get; } } }
{ "content_hash": "e272a98759ff00110dfb7e81c2230481", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 112, "avg_line_length": 33.94736842105263, "alnum_prop": 0.5405684754521963, "repo_name": "DavidMoore/Foundation", "id": "ab4ca357f58f996a2aa201b6eccd0be1d19b95e1", "size": "1935", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Code/Foundation/IPaginatedCollection.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "411" }, { "name": "C#", "bytes": "4421000" }, { "name": "C++", "bytes": "810" }, { "name": "Objective-C", "bytes": "733" }, { "name": "Visual Basic", "bytes": "26641" } ], "symlink_target": "" }
@implementation BETableViewCell - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextFillRect(context, rect); //下分割线 CGContextSetStrokeColorWithColor(context, [UIColor be_colorWithHex:0xe2e2e2].CGColor); CGContextStrokeRect(context, CGRectMake(0, rect.size.height, rect.size.width, 0.5)); } @end
{ "content_hash": "3e4d95a5f0988636ecbfd2c563e8bc1f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 90, "avg_line_length": 36.25, "alnum_prop": 0.767816091954023, "repo_name": "iosmvn/BEKit", "id": "ddbcad24c1ad44e976443e6bef7afc9e1400124e", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BEKit/Classes/ui/BETableViewCell.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "202496" }, { "name": "Ruby", "bytes": "2009" } ], "symlink_target": "" }
SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PotPy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PotPy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PotPy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PotPy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
{ "content_hash": "bb7d0e0e463631940a93371a79ffbbeb", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 141, "avg_line_length": 36.69798657718121, "alnum_prop": 0.7009875640087784, "repo_name": "dhain/potpy", "id": "a814712233186c2b9072819dea1487efaaa2ae3e", "size": "5560", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "89633" } ], "symlink_target": "" }
import zhstructures.*; import junit.framework.*; /** * A JUnit test case class for the ZHTreeMap class. * * Every method starting with the word "test" will be called when running * the test with JUnit. */ public class TreeMapTest extends TestCase { private ZHTreeMap<Integer,Integer> treeMap; public void setUp() { treeMap=new ZHTreeMap<Integer,Integer>(); } public void testAll() { int i=0; while(i<9) { int temp=(int)(Math.random()*90.0)+10; /* Note that we print out temp, the null that occurs when * temp is first "put" in the map associated with temp+5 * and temp+5 when we "re-put" temp associated with temp+10. * Look in the interactions panel to see the result.*/ if(!treeMap.containsKey(temp)) { Integer val=treeMap.put(temp,temp+5); System.out.print("|"+temp+" "+val+" "); assertEquals("failed put",val,null); val=treeMap.put(temp,temp+10); System.out.print(val+"|"); assertEquals("failed put",val,new Integer(temp+5)); i++; } } System.out.println(); /* Note that in this for loop we print out what each key * is associated with as well as doing the test. */ for(Integer i2:treeMap.keySet()) { System.out.print("<"+i2+" -> "+treeMap.get(i2)+"> "); //Compare i with i+10 assertEquals("failed",treeMap.get(i2),new Integer(i2+10)); } System.out.println(); //For each exception we print out what happened. try { treeMap.get(null); fail("got a null value"); } catch(Exception e) { System.out.println("Got an exception on a null key for get."); } try { treeMap.put(null,100); fail("put a null key"); } catch(Exception e) { System.out.println("Got an exception when putting a null key."); } try { treeMap.put(100,null); fail("put a null key"); } catch(Exception e) { System.out.println("Got an exception when putting a null value."); } } }
{ "content_hash": "dd291e1395990feaca2d174af2ce480a", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 73, "avg_line_length": 29.941176470588236, "alnum_prop": 0.6041257367387033, "repo_name": "AndrewZurn/sju-compsci-archive", "id": "d2fe84e22241b2e41b45bd97e7757913b95d1dd5", "size": "2036", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CS100s/CS162/Lab/Lab12/SpringJustin_and_ZurnAndrewLab12/TreeMapTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "18272" }, { "name": "Bison", "bytes": "278" }, { "name": "C", "bytes": "151324" }, { "name": "C++", "bytes": "587" }, { "name": "CSS", "bytes": "19503" }, { "name": "Haskell", "bytes": "13675" }, { "name": "Java", "bytes": "5735261" }, { "name": "JavaScript", "bytes": "274" }, { "name": "Makefile", "bytes": "3010" }, { "name": "Mathematica", "bytes": "53105" }, { "name": "Perl", "bytes": "7350" }, { "name": "Shell", "bytes": "1010" }, { "name": "TeX", "bytes": "197561" } ], "symlink_target": "" }
import { inject } from 'aurelia-dependency-injection'; import { CommandCoordinator } from '@dolittle/commands'; import { QueryCoordinator } from '@dolittle/queries'; import { AllProjects } from './Projects/AllProjects'; import { ImprovementsForProject } from './Projects/ImprovementsForProject'; @inject(CommandCoordinator, QueryCoordinator) export class index { projects=[]; improvements=[]; constructor(commandCoordinator, queryCoordinator) { let self = this; this._commandCoordinator = commandCoordinator; this._queryCoordinator = queryCoordinator; var query = new AllProjects(); this._queryCoordinator.execute(query).then(result => { self.projects = result.items; }); } submit() { } getBuilds(id) { let self = this; var query = new ImprovementsForProject(); query.project = id; this._queryCoordinator.execute(query).then(result => { self.improvements = result.items; }); } }
{ "content_hash": "06d382d9b1f0991e17be39440688b991", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 75, "avg_line_length": 26.53846153846154, "alnum_prop": 0.6454106280193237, "repo_name": "doLittle-Samples/Basic", "id": "25fa61ad32413b27b4e8f6824f3cc3df32cd4a97", "size": "1037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Basic/Web/Features/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "103361" }, { "name": "HTML", "bytes": "4159" }, { "name": "JavaScript", "bytes": "31444" } ], "symlink_target": "" }
<%# Copyright 2013-2017 the original author or authors. This file is part of the JHipster project, see https://jhipster.github.io/ for more information. 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. -%> <form action="{{ providerURL }}" method="POST"> <button type="submit" class="btn btn-block jh-btn-social jh-btn-{{ provider }}"> <span data-translate="social.btnLabel" translate-values="{ label: label }">Sign in with {{ label }}</span> </button> <input name="scope" type="hidden" value="{{ providerSetting }}"/> <input name="_csrf" type="hidden" value="{{ csrf }}"/> </form>
{ "content_hash": "476542be5e95518bc969fcf9b936ea25", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 114, "avg_line_length": 43.8, "alnum_prop": 0.7150684931506849, "repo_name": "fjuriolli/scribble", "id": "6a4e18703009a8738594e49c84a26fb8f1990fb7", "size": "1097", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/generator-jhipster/generators/client/templates/angularjs/src/main/webapp/app/account/social/directive/_social.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "8951" }, { "name": "HTML", "bytes": "148514" }, { "name": "Java", "bytes": "266008" }, { "name": "JavaScript", "bytes": "212200" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
import { Injectable } from '@angular/core'; @Injectable() export class Visibility { /** * Is the visibility API supported? */ public supported: boolean = document.hasOwnProperty('hidden'); private _changeVisibility: any = () => this.onChange(); constructor() { if (this.supported) { document.addEventListener('visibilityChange', this._changeVisibility); } } destroy() { if (this.supported) { document.removeEventListener('visibilityChange', this._changeVisibility); } } onChange() { // switch (document.visibilityState) { // case 'visible': // break; // case 'hidden': // break; // case 'prerender': // break; // case 'unloaded': // break; // // } } }
{ "content_hash": "2e45063c9ef59ae43470ab04613bd262", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 79, "avg_line_length": 21, "alnum_prop": 0.5804375804375804, "repo_name": "justindujardin/angular2-rpg", "id": "67545020238b197fb420fab487c1111bced594b3", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/app/services/visibility.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104242" }, { "name": "HTML", "bytes": "12548" }, { "name": "Shell", "bytes": "579" }, { "name": "TypeScript", "bytes": "216048" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Omega</td><td>MID9711</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [family] => Omega MID9711 [brand] => Omega [model] => MID9711 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.1</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.03</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.1.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.1* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.1 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.005</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-42bb56ba-b834-47c5-bea0-c0270e9ab371">Detail</a> <!-- Modal Structure --> <div id="modal-42bb56ba-b834-47c5-bea0-c0270e9ab371" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapLite result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => unknown [browser_modus] => unknown [version] => 4.0 [majorver] => 0 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => false [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.028</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td>AndroidOS 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => Safari [browserVersion] => 4.0 [osName] => AndroidOS [osVersion] => 4.1.1 [deviceModel] => WebKit [isMobile] => 1 [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td>OMEGA-MID9711</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.30202</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => OMEGA-MID9711 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.1.1 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.1.x Jelly Bean [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Android Browser </td><td>WebKit </td><td>Android 4.1</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.006</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.1 [platform] => ) [device] => Array ( [brand] => [brandName] => [model] => [device] => [deviceName] => ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a> <!-- Modal Structure --> <div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => [isFacebookWebView:Sinergi\BrowserDetector\Browser:private] => [isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.1.1 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Android 4.1.1</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">Omega</td><td>MID9711</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 1 [patch] => 1 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 1 [patch] => 1 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Omega [model] => MID9711 [family] => Omega MID9711 ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Safari 534.30</td><td>WebKit 534.30</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => Android [platform_version] => 4.1.1 [platform_type] => Mobile [browser_name] => Safari [browser_version] => 534.30 [engine_name] => WebKit [engine_version] => 534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.091</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a> <!-- Modal Structure --> <div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.1.1 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => German - Germany [agent_languageTag] => de-de ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.24201</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Jelly Bean) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => JRO03H ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Jelly Bean [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Jelly Bean) [operating_system_version_full] => 4.1.1 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.1.1; de-de; OMEGA-MID9711 Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td>OMEGA-MID9711</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.003</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.1.1 ) [device] => Array ( [type] => tablet [model] => OMEGA-MID9711 ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a> <!-- Modal Structure --> <div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.1.1 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Android Webkit 4.1.1</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td></td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.017</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.1.1 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.1.1 [complete_device_name] => Generic Android 4.1 Tablet [device_name] => Generic Android 4.1 Tablet [form_factor] => Tablet [is_phone] => false [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 4.1 Tablet [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.1 [pointing_method] => touchscreen [release_date] => 2012_july [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => false [is_tablet] => true [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 480 [resolution_height] => 800 [columns] => 60 [max_image_width] => 600 [max_image_height] => 1024 [rows] => 40 [physical_screen_width] => 92 [physical_screen_height] => 153 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => true [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => false [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://developer.android.com/reference/android/webkit/package-summary.html [title] => Android Webkit 4.0 [name] => Android Webkit [version] => 4.0 [code] => android-webkit [image] => img/16/browser/android-webkit.png ) [os] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 4.1.1 [code] => android [x64] => [title] => Android 4.1.1 [type] => os [dir] => os [image] => img/16/os/android.png ) [device] => Array ( [link] => [title] => [model] => [brand] => [code] => null [dir] => device [type] => device [image] => img/16/device/null.png ) [platform] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 4.1.1 [code] => android [x64] => [title] => Android 4.1.1 [type] => os [dir] => os [image] => img/16/os/android.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 08:10:40</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "1b1f30b4a22892883471e4dd4a045bfa", "timestamp": "", "source": "github", "line_count": 1369, "max_line_length": 960, "avg_line_length": 41.201607012417824, "alnum_prop": 0.5470614307242265, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "f99d685f77a6a5b59fa24041242fb7118252159e", "size": "56406", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v5/user-agent-detail/ed/90/ed908423-dc26-4c87-8a29-cb123df1f9f0.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
import warnings import numpy as np from skimage.viewer.qt import QtWidgets, has_qt, FigureManagerQT, FigureCanvasQTAgg import matplotlib as mpl from matplotlib.figure import Figure from matplotlib import _pylab_helpers from matplotlib.colors import LinearSegmentedColormap if has_qt and 'agg' not in mpl.get_backend().lower(): warnings.warn("Recommended matplotlib backend is `Agg` for full " "skimage.viewer functionality.") __all__ = ['init_qtapp', 'start_qtapp', 'RequiredAttr', 'figimage', 'LinearColormap', 'ClearColormap', 'FigureCanvas', 'new_plot', 'update_axes_image'] QApp = None def init_qtapp(): """Initialize QAppliction. The QApplication needs to be initialized before creating any QWidgets """ global QApp QApp = QtWidgets.QApplication.instance() if QApp is None: QApp = QtWidgets.QApplication([]) return QApp def is_event_loop_running(app=None): """Return True if event loop is running.""" if app is None: app = init_qtapp() if hasattr(app, '_in_event_loop'): return app._in_event_loop else: return False def start_qtapp(app=None): """Start Qt mainloop""" if app is None: app = init_qtapp() if not is_event_loop_running(app): app._in_event_loop = True app.exec_() app._in_event_loop = False else: app._in_event_loop = True class RequiredAttr(object): """A class attribute that must be set before use.""" instances = dict() def __init__(self, init_val=None): self.instances[self, None] = init_val def __get__(self, obj, objtype): value = self.instances[self, obj] if value is None: raise AttributeError('Required attribute not set') return value def __set__(self, obj, value): self.instances[self, obj] = value class LinearColormap(LinearSegmentedColormap): """LinearSegmentedColormap in which color varies smoothly. This class is a simplification of LinearSegmentedColormap, which doesn't support jumps in color intensities. Parameters ---------- name : str Name of colormap. segmented_data : dict Dictionary of 'red', 'green', 'blue', and (optionally) 'alpha' values. Each color key contains a list of `x`, `y` tuples. `x` must increase monotonically from 0 to 1 and corresponds to input values for a mappable object (e.g. an image). `y` corresponds to the color intensity. """ def __init__(self, name, segmented_data, **kwargs): segmented_data = dict((key, [(x, y, y) for x, y in value]) for key, value in segmented_data.items()) LinearSegmentedColormap.__init__(self, name, segmented_data, **kwargs) class ClearColormap(LinearColormap): """Color map that varies linearly from alpha = 0 to 1 """ def __init__(self, rgb, max_alpha=1, name='clear_color'): r, g, b = rgb cg_speq = {'blue': [(0.0, b), (1.0, b)], 'green': [(0.0, g), (1.0, g)], 'red': [(0.0, r), (1.0, r)], 'alpha': [(0.0, 0.0), (1.0, max_alpha)]} LinearColormap.__init__(self, name, cg_speq) class FigureCanvas(FigureCanvasQTAgg): """Canvas for displaying images.""" def __init__(self, figure, **kwargs): self.fig = figure FigureCanvasQTAgg.__init__(self, self.fig) FigureCanvasQTAgg.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvasQTAgg.updateGeometry(self) def resizeEvent(self, event): FigureCanvasQTAgg.resizeEvent(self, event) # Call to `resize_event` missing in FigureManagerQT. # See https://github.com/matplotlib/matplotlib/pull/1585 self.resize_event() def new_canvas(*args, **kwargs): """Return a new figure canvas.""" allnums = _pylab_helpers.Gcf.figs.keys() num = max(allnums) + 1 if allnums else 1 FigureClass = kwargs.pop('FigureClass', Figure) figure = FigureClass(*args, **kwargs) canvas = FigureCanvas(figure) fig_manager = FigureManagerQT(canvas, num) return fig_manager.canvas def new_plot(parent=None, subplot_kw=None, **fig_kw): """Return new figure and axes. Parameters ---------- parent : QtWidget Qt widget that displays the plot objects. If None, you must manually call ``canvas.setParent`` and pass the parent widget. subplot_kw : dict Keyword arguments passed ``matplotlib.figure.Figure.add_subplot``. fig_kw : dict Keyword arguments passed ``matplotlib.figure.Figure``. """ if subplot_kw is None: subplot_kw = {} canvas = new_canvas(**fig_kw) canvas.setParent(parent) fig = canvas.figure ax = fig.add_subplot(1, 1, 1, **subplot_kw) return fig, ax def figimage(image, scale=1, dpi=None, **kwargs): """Return figure and axes with figure tightly surrounding image. Unlike pyplot.figimage, this actually plots onto an axes object, which fills the figure. Plotting the image onto an axes allows for subsequent overlays of axes artists. Parameters ---------- image : array image to plot scale : float If scale is 1, the figure and axes have the same dimension as the image. Smaller values of `scale` will shrink the figure. dpi : int Dots per inch for figure. If None, use the default rcParam. """ dpi = dpi if dpi is not None else mpl.rcParams['figure.dpi'] kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') h, w, d = np.atleast_3d(image).shape figsize = np.array((w, h), dtype=float) / dpi * scale fig, ax = new_plot(figsize=figsize, dpi=dpi) fig.subplots_adjust(left=0, bottom=0, right=1, top=1) ax.set_axis_off() ax.imshow(image, **kwargs) ax.figure.canvas.draw() return fig, ax def update_axes_image(image_axes, image): """Update the image displayed by an image plot. This sets the image plot's array and updates its shape appropriately Parameters ---------- image_axes : `matplotlib.image.AxesImage` Image axes to update. image : array Image array. """ image_axes.set_array(image) # Adjust size if new image shape doesn't match the original h, w = image.shape[:2] image_axes.set_extent((0, w, h, 0))
{ "content_hash": "02c38d04bf713d88ab62f837321e4c3e", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 83, "avg_line_length": 30.84037558685446, "alnum_prop": 0.6229258639062262, "repo_name": "newville/scikit-image", "id": "524e9b6166c4d2dc0cef47c9acb0723bcd64baba", "size": "6569", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "skimage/viewer/utils/core.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "76670" }, { "name": "Makefile", "bytes": "449" }, { "name": "Python", "bytes": "2158081" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2013 The Netty Project ~ ~ The Netty Project 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>io.netty</groupId> <artifactId>netty-parent</artifactId> <version>4.1.0.Alpha1-SNAPSHOT</version> </parent> <artifactId>netty-transport-rxtx</artifactId> <packaging>bundle</packaging> <name>Netty/Transport/RXTX</name> <dependencies> <dependency> <groupId>${project.groupId}</groupId> <artifactId>netty-buffer</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>netty-transport</artifactId> <version>${project.version}</version> </dependency> <!-- FIXME find/make osgi bundle --> <dependency> <groupId>org.rxtx</groupId> <artifactId>rxtx</artifactId> </dependency> </dependencies> </project>
{ "content_hash": "371ef0b802c7240bbd7ffc9853014ea4", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 201, "avg_line_length": 34.52, "alnum_prop": 0.6894553881807648, "repo_name": "apigee/netty", "id": "17e0c2536e0874df959c0a0919606dcde68a11d1", "size": "1726", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "transport-rxtx/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.program.model.data; import java.util.NoSuchElementException; import ghidra.docking.settings.EnumSettingsDefinition; import ghidra.docking.settings.Settings; /** * The settings definition for the numeric display format */ public class PointerTypeSettingsDefinition implements EnumSettingsDefinition, TypeDefSettingsDefinition { private static final String POINTER_TYPE_SETTINGS_NAME = "ptr_type"; private static final String DESCRIPTION = "Specifies the pointer type which affects interpretation of offset"; private static final String DISPLAY_NAME = "Pointer Type"; // Choices correspond to the enumerated PointerType values private static final String[] choices = { "default", "image-base-relative", "relative", "file-offset" }; public static final PointerTypeSettingsDefinition DEF = new PointerTypeSettingsDefinition(); // Format with HEX default private PointerTypeSettingsDefinition() { } /** * Returns the format based on the specified settings * @param settings the instance settings or null for default value. * @return the {@link PointerType}. {@link PointerType#DEFAULT} will be returned * if no setting has been made. */ public PointerType getType(Settings settings) { if (settings == null) { return PointerType.DEFAULT; } Long value = settings.getLong(POINTER_TYPE_SETTINGS_NAME); if (value == null) { return PointerType.DEFAULT; } int type = (int) value.longValue(); try { return PointerType.valueOf(type); } catch (NoSuchElementException e) { return PointerType.DEFAULT; } } @Override public int getChoice(Settings settings) { return getType(settings).value; } @Override public String getValueString(Settings settings) { return choices[getChoice(settings)]; } @Override public void setChoice(Settings settings, int value) { try { setType(settings, PointerType.valueOf(value)); } catch (NoSuchElementException e) { settings.clearSetting(POINTER_TYPE_SETTINGS_NAME); } } public void setType(Settings settings, PointerType type) { if (type == PointerType.DEFAULT) { settings.clearSetting(POINTER_TYPE_SETTINGS_NAME); } else { settings.setLong(POINTER_TYPE_SETTINGS_NAME, type.value); } } @Override public String[] getDisplayChoices(Settings settings) { return choices; } @Override public String getName() { return DISPLAY_NAME; } @Override public String getStorageKey() { return POINTER_TYPE_SETTINGS_NAME; } @Override public String getDescription() { return DESCRIPTION; } @Override public String getDisplayChoice(int value, Settings s1) { return choices[value]; } @Override public void clear(Settings settings) { settings.clearSetting(POINTER_TYPE_SETTINGS_NAME); } @Override public void copySetting(Settings settings, Settings destSettings) { Long l = settings.getLong(POINTER_TYPE_SETTINGS_NAME); if (l == null) { destSettings.clearSetting(POINTER_TYPE_SETTINGS_NAME); } else { destSettings.setLong(POINTER_TYPE_SETTINGS_NAME, l); } } @Override public boolean hasValue(Settings setting) { return setting.getValue(POINTER_TYPE_SETTINGS_NAME) != null; } public String getDisplayChoice(Settings settings) { return choices[getChoice(settings)]; } /** * Sets the settings object to the enum value indicating the specified choice as a string. * @param settings the settings to store the value. * @param choice enum string representing a choice in the enum. */ public void setDisplayChoice(Settings settings, String choice) { for (int i = 0; i < choices.length; i++) { if (choices[i].equals(choice)) { setChoice(settings, i); break; } } } @Override public String getAttributeSpecification(Settings settings) { int choice = getChoice(settings); if (choice != 0) { return choices[choice]; } return null; } }
{ "content_hash": "c0a732d7152160a88ec5a36d5ef1f7b7", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 120, "avg_line_length": 26.458333333333332, "alnum_prop": 0.730933633295838, "repo_name": "NationalSecurityAgency/ghidra", "id": "89e91675eac3c09b5f800186f3f3fe8141156942", "size": "4445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/PointerTypeSettingsDefinition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "77536" }, { "name": "Batchfile", "bytes": "21610" }, { "name": "C", "bytes": "1132868" }, { "name": "C++", "bytes": "7334484" }, { "name": "CSS", "bytes": "75788" }, { "name": "GAP", "bytes": "102771" }, { "name": "GDB", "bytes": "3094" }, { "name": "HTML", "bytes": "4121163" }, { "name": "Hack", "bytes": "31483" }, { "name": "Haskell", "bytes": "453" }, { "name": "Java", "bytes": "88669329" }, { "name": "JavaScript", "bytes": "1109" }, { "name": "Lex", "bytes": "22193" }, { "name": "Makefile", "bytes": "15883" }, { "name": "Objective-C", "bytes": "23937" }, { "name": "Pawn", "bytes": "82" }, { "name": "Python", "bytes": "587415" }, { "name": "Shell", "bytes": "234945" }, { "name": "TeX", "bytes": "54049" }, { "name": "XSLT", "bytes": "15056" }, { "name": "Xtend", "bytes": "115955" }, { "name": "Yacc", "bytes": "127754" } ], "symlink_target": "" }
package org.olat.course.nodes.info; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; import org.olat.core.gui.components.form.flexible.elements.SingleSelection; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.core.util.StringHelper; import org.olat.modules.ModuleConfiguration; /** * Description:<br> * Panel for the configuration of the info messages course node * <P> * Initial Date: 3 aug. 2010 <br> * * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com */ public class InfoConfigForm extends FormBasicController { private static final String[] maxDurationValues = new String[] { "5", "10", "30", "90", "365", "\u221E" }; private static final String[] maxLengthValues = new String[] { "1", "2", "3", "4", "5", "7", "10", "25", "\u221E" }; private static final String[] autoSubscribeKeys = new String[] { "on" }; private final String[] autoSubscribeValues = new String[] { null }; private final ModuleConfiguration config; private SingleSelection durationSelection; private SingleSelection lengthSelection; private MultipleSelectionElement autoSubscribeSelection; public InfoConfigForm(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config) { super(ureq, wControl); this.config = config; autoSubscribeValues[0] = translate("pane.tab.infos_config.auto_subscribe.on"); initForm(ureq); } @Override protected void initForm(final FormItemContainer formLayout, final Controller listener, final UserRequest ureq) { setFormTitle("pane.tab.infos_config.title"); setFormContextHelp(InfoConfigForm.class.getPackage().getName(), "ced-info-config.html", "help.hover.info.config"); final String page = velocity_root + "/editShow.html"; final FormLayoutContainer showLayout = FormLayoutContainer.createCustomFormLayout("pane.tab.infos_config.shown", getTranslator(), page); showLayout.setLabel("pane.tab.infos_config.shown", null); formLayout.add(showLayout); durationSelection = uifactory.addDropdownSingleselect("pane.tab.infos_config.max_duration", showLayout, maxDurationValues, maxDurationValues, null); durationSelection.setLabel("pane.tab.infos_config.max", null); final String durationStr = (String) config.get(InfoCourseNodeConfiguration.CONFIG_DURATION); if (StringHelper.containsNonWhitespace(durationStr)) { durationSelection.select(durationStr, true); } else { durationSelection.select("30", true); } lengthSelection = uifactory.addDropdownSingleselect("pane.tab.infos_config.max_shown", showLayout, maxLengthValues, maxLengthValues, null); lengthSelection.setLabel("pane.tab.infos_config.max", null); final String lengthStr = (String) config.get(InfoCourseNodeConfiguration.CONFIG_LENGTH); if (StringHelper.containsNonWhitespace(lengthStr)) { lengthSelection.select(lengthStr, true); } else { lengthSelection.select("5", true); } autoSubscribeSelection = uifactory.addCheckboxesHorizontal("auto_subscribe", formLayout, autoSubscribeKeys, autoSubscribeValues, null); final String autoSubscribeStr = (String) config.get(InfoCourseNodeConfiguration.CONFIG_AUTOSUBSCRIBE); if ("on".equals(autoSubscribeStr) || !StringHelper.containsNonWhitespace(autoSubscribeStr)) { autoSubscribeSelection.select("on", true); } uifactory.addFormSubmitButton("save", formLayout); } protected ModuleConfiguration getUpdatedConfig() { final String durationStr = durationSelection.getSelectedKey(); config.set(InfoCourseNodeConfiguration.CONFIG_DURATION, durationStr); final String lengthStr = lengthSelection.getSelectedKey(); config.set(InfoCourseNodeConfiguration.CONFIG_LENGTH, lengthStr); final String autoSubscribeStr = autoSubscribeSelection.isSelected(0) ? "on" : "off"; config.set(InfoCourseNodeConfiguration.CONFIG_AUTOSUBSCRIBE, autoSubscribeStr); return config; } @Override protected void doDispose() { // } @Override protected void formOK(final UserRequest ureq) { fireEvent(ureq, Event.DONE_EVENT); } }
{ "content_hash": "55c83669851cff0d220191a85b360eee", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 150, "avg_line_length": 40.925233644859816, "alnum_prop": 0.7759762502854533, "repo_name": "RLDevOps/Scholastic", "id": "d2ae95f023dabdc3d226fcc0cd6ce025e0ea96b1", "size": "5112", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/org/olat/course/nodes/info/InfoConfigForm.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2279568" }, { "name": "Java", "bytes": "20345916" }, { "name": "JavaScript", "bytes": "31555977" }, { "name": "Perl", "bytes": "4117" }, { "name": "Shell", "bytes": "42296" }, { "name": "XSLT", "bytes": "169404" } ], "symlink_target": "" }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('em-table-column', 'Integration | Component | em table column', { integration: true }); test('Basic rendering test', function(assert) { this.render(hbs`{{em-table-column}}`); assert.equal(this.$().text().trim(), ''); });
{ "content_hash": "688634a206e1593848069f12d9b6d4e6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 84, "avg_line_length": 29.25, "alnum_prop": 0.6923076923076923, "repo_name": "sreenaths/em-table", "id": "0fb88abb2779198df23ae6f13c27838bee1a441f", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/integration/components/em-table-column-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14590" }, { "name": "HTML", "bytes": "12915" }, { "name": "JavaScript", "bytes": "81528" } ], "symlink_target": "" }
var AbstractListWidget = OcrJs.Base.extend({ init: function(parent, datasource, options) { this._super(); this.parent = parent; this.data = datasource; this.options = { multiselect: true, }; $.extend(this.options, options); // currently selected list entry // (the last one clicked) this._current = null; this._selected = {}; var self = this; this.data.addListener("dataChanged", function() { self.refreshEntries(); }); $(this.parent).html(""); $(this.parent).append(this.buildUi()); this.setupEvents(); this.setupMouseEvents(); this.data.refreshData(); }, dataSource: function() { return this.data; }, container: function() { return $(this.parent); }, setupEvents: function() { }, setupMouseEvents: function() { var self = this; // sync the headers when container size changes $(self.parent).resize(function() { self.syncHeadWidths(); }); // sort when the header is clicked function headSort(event) { self.data.sortByColumn($(this).data("index")); $(".sort_arrow").removeClass("order").removeClass("order_desc"); $(this).find(".sort_arrow").addClass( self.data.descending() ? "order_desc" : "order"); } // re-sort the list when the user clicks a column header $("th", self.parent).bind("click.headsort", headSort); // we don't want to sort the headers $(".header_drag", self.parent).bind("mouseover.sizenter mouseout.sizeleave", function(event) { if (event.type == "mouseover") { $("th", self.parent).unbind("click.headsort"); } else { $("th", self.parent).bind("click.headsort", headSort); } }); // when the user clicks on a header separator, bind the mouse move // event to resize the columns of both header and entry tables. $(".header_drag", self.parent).bind("mousedown.headsize", function(event) { var head = $(this).parent(); var cell = $($(".entrylist", self.parent).find("td").get(head.data("index"))); var leftpos = head.offset().left; // Note: using event namespaces here to add/remove the // correct events to the document. This allows us the // move the mouse anywhere and be sure of not missing // the mouseup event $(document).bind("mouseup.headsize", function(upevent) { $(document) .unbind("mousemove.headsize") .unbind("mouseup.headsize") .css("cursor", "auto"); }); $(document).bind("mousemove.headsize", function(moveevent) { var celldiff = cell.outerWidth(true) - cell.width(); cell.width(moveevent.pageX - leftpos - celldiff); self.syncHeadWidths(); }); event.preventDefault(); }); // highlight the header when the mouse is down. $("th", self.parent).live("mousedown.headclick", function(event) { var cell = $(this); cell.addClass("pressed"); $(document).bind("mouseup.press", function(mue) { cell.removeClass("pressed"); $(document).unbind("mouseup.press"); }); }); // don't allow selecting the list - it looks bad and makes // working with item selections dodgy $(".entry, th", self.parent).live("mousedown.noselect", function(e) { return false; }); // handle task selection and multiselection $(".entry", self.parent).live("click.entryselect", function(event) { // if ctrl is down TOGGLE selection, else select item self.selectEntry(this, event.ctrlKey ? !$(this).hasClass("ui-selected") : true ); // if shift is down, select between the new click // recipient and the 'current' (last selected) item. if (event.shiftKey && self.options.multiselect) { // deselect everything $(".ui-selected", self.parent).not($(this)).not(self._current).removeClass("ui-selected"); // if there's a current element and it's not the // one we've just clicked on, select everything in between if (self._current && self._current != this) { var traverser = parseInt($(self._current).data("row")) > parseInt($(this).data("row")) ? "prevUntil" : "nextUntil"; $(self._current)[traverser]("#" + this.id).each(function(i, elem) { self.selectEntry(elem, true); }); } // if ctrl is down, don't clear the last selection } else if (!self.options.multiselect || !event.ctrlKey) { var id = this.id; $(".ui-selected", self.parent).each(function(i, entry) { if (entry.id != id) { self.selectEntry(entry, false); } }); } // store the selector of the current element // to use when selecting a range if (self._current == null || !event.shiftKey) self._current = this; // finally, trigger any user callbacks self.rowClicked(event, parseInt($(this).data("row"))); }); $(".entry", self.parent).live("dblclick.rowdckick", function(event) { self.rowDoubleClicked(event, parseInt($(this).data("row"))); }); $(".entry > td", self.parent).live("click.rowclick", function(event) { self.cellClicked(event, parseInt($(this).parent().data("row")), parseInt($(this).data("col"))); }); $(".page_link", self.parent).live("click.linkclick", function(event) { self.data.setPage(parseInt($(this).data("page"))); event.preventDefault(); }); }, teardownEvents: function() { $(".entry", this.parent).die("dblclick.rowdckick"); $(".entry > td", this.parent).die("click.rowclick"); $(".page_link", this.parent).die("click.linkclick"); $(".entry, th", this.parent).die("mousedown.noselect"); $(".entry", this.parent).die("click.entryselect"); $("th", this.parent).die("mousedown.headclick"); $(".header_drag", this.parent).unbind("mousedown.headsize"); $(".header_drag", this.parent).unbind("mouseover mouseout"); $("th", this.parent).unbind("click.headsort"); $(".header_drag", this.parent).unbind("mouseover.sizenter mouseout.sizeleave"); }, onClose: function(event) { }, resized: function(event) { this.syncHeadWidths(); }, setHeight: function(height) { var diff = height - $("#lwscroll").height(); $("#lwscroll").height(height - 60); }, setWaiting: function(wait) { m_container.toggleClass("waiting", wait); }, // set a task in the list selected and store it's id // so the selection can be preserved after refresh selectEntry: function(entry, select) { $(entry).toggleClass("ui-selected", select); var key = $(entry).data("key"); if (key) { if (select) { this._selected[key] = true; } else { this._selected[key] = undefined; } } }, // update the data in the table when the file // data changes refreshEntries: function() { this.setTableLength(); var entries = $(".entry", this.parent); var data = this.data; //var entry, cells, cell; var key, entry, cells, cell; for (var row = 0; row < data.dataLength(); row++) { key = data.rowKey(row); entry = $(entries.get(row)); cells = entry.find("td"); entry .attr("class", "entry") .data("row", row) .data("key", key) .attr("id", "entry" + row) .addClass(row % 2 ? "odd" : ""); $.each(data.rowMetadata(row), function(k, v) { entry.data(k, v); }); $.each(data.rowClassNames(row), function(i, v) { entry.addClass(v); }); for (var col = 0; col < data.columnCount(); col++) { cell = $(cells.get(col)); cell.data("col", col).text(data.cellLabel(row, col)); $.each(data.cellMetadata(row, col), function(k, v) { cell.data(k, v); }); $.each(data.cellClassNames(row, col), function(i, v) { cell.addClass(v); }); } // if the data source defines a usable key, re-select // those elements that might've been selected before if (key && this._selected[key]) { entry.addClass("ui-selected"); } }; $(".entry").show(); this.syncHeadWidths(); }, clearSelection: function() { this._selected = {}; $(".entrylist", this.parent).find(".entry.ui-selected").removeClass("ui-selected"); }, // sync the header table's columns with the file list's widths syncHeadWidths: function() { for (var i in [0, 1, 2]) { var head = $($("#headtable", this.parent).find("th").get(i)); var pad = head.outerWidth() - head.width(); var w = $($(".entrylist", this.parent).find("td").get(i)).outerWidth(true) - pad; head.css("width", w); } }, // insert the appropriate number of empty rows // into the filetable setTableLength: function() { $(".paginators", this.parent).remove(); if (this.data.isPaginated()) { $(this.parent).append(this.buildPaginators()); } var row = $("<tr></tr>") .addClass("entry") .css("MozUserSelect", "none"); for (var col = 0; col < this.data.columnCount(); col++) { row.append($("<td></td>")); } var entrytable = $(".entrylist", this.parent).first(); var entries = entrytable.find(".entry"); var diff = entries.length - this.data.dataLength(); if (diff < 0) { while (diff++) { entrytable.append(row.clone()); } } else if (diff > 0) { for (var i = this.data.dataLength(); i < entries.length; i++) { entries.slice(i).remove(); } } }, buildUi: function(data) { // we need a separate table for the header because // we don't want it to scroll when the table does var entrytable = $("<table></table>") .addClass("entrylist") .attr("id", "entrytable"); var tablescroll = $("<div></div>") .attr("id", "lwscroll") .append(entrytable); var innercontainer = $("<div></div>") .addClass("lwcontainer") .append(this.buildHeaderTable()) .append(tablescroll); return innercontainer; }, buildHeaderTable: function() { var headtable = $("<table></table>") .addClass("listhead") .attr("id", "headtable"); var thead = $("<thead></thead>"); var headrow = $("<tr></tr>"); headtable.append(thead.append(headrow)); var self = this; for (var col = 0; col < self.data.columnCount(); col++) { var th = $("<th></th>") .data("sort", col) .data("index", col); th.text(self.data.headerLabel(col)); // add a dragger to all but the last column if (col < self.data.columnCount() - 1) { th.append( $("<div></div>").addClass("header_drag") .append($("<div></div>").addClass("header_line")) ); } var sortdiv = $("<div></div>").addClass("sort_arrow"); if (col == self.data.sortColumn()) { sortdiv.addClass(self.data.descending() ? "order_desc" : "order"); } th.append(sortdiv); headrow.append(th); } return headtable; }, buildPaginators: function() { var data = this.data; var container = $("<div></div>").addClass("paginators"); var pag = $("<div></div>") .addClass("pagination") .addClass("step_links") pag.append($("<span></span>") .text("Page " + data.page() + " of " + data.numPages())); if (data.hasPrev()) { pag.prepend( $("<a></a>") .attr("href", data.url() + "?page=" + data.prevPage()) .addClass("page_link") .data("page", data.prevPage()) .text("Previous") ); } if (data.hasNext()) { pag.append( $("<a></a>") .attr("href", data.url() + "?page=" + data.nextPage()) .addClass("page_link") .data("page", data.nextPage()) .text("Next") ); } return container.append(pag); }, cellClicked: function(event, row, col) { }, rowClicked: function(event, row) { }, rowDoubleClicked: function(event, row) { }, });
{ "content_hash": "d86215d7be1cf57aa2f8afd180c19896", "timestamp": "", "source": "github", "line_count": 393, "max_line_length": 106, "avg_line_length": 35.56997455470738, "alnum_prop": 0.4931683239144431, "repo_name": "vitorio/ocropodium", "id": "138780b6f4c2ec983ea606f0a3e34d83f16db885", "size": "14036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ocradmin/static/js/abstract_list_widget.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "75173" }, { "name": "HTML", "bytes": "88397" }, { "name": "JavaScript", "bytes": "695068" }, { "name": "Python", "bytes": "403080" }, { "name": "Shell", "bytes": "2805" }, { "name": "XSLT", "bytes": "2772" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _states = require('./states'); var _states2 = _interopRequireDefault(_states); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { states: _states2.default };
{ "content_hash": "b3c0a06f9e4bf263b32b2edff769b6a1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 95, "avg_line_length": 23.846153846153847, "alnum_prop": 0.6806451612903226, "repo_name": "jackley/arrayz", "id": "bde54436869b7be11dbf201244bdc33663b23486", "size": "310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/regions/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "294" }, { "name": "JavaScript", "bytes": "115815" } ], "symlink_target": "" }
@class NSDictionary; #else class NSDictionary; #endif namespace content { class SystemHotkeyMap; // This singleton holds a global mapping of hotkeys reserved by OSX. class SystemHotkeyHelperMac { public: // Return pointer to the singleton instance for the current process. static SystemHotkeyHelperMac* GetInstance(); // Loads the system hot keys after a brief delay, to reduce file system access // immediately after launch. void DeferredLoadSystemHotkeys(); // Guaranteed to not be NULL. SystemHotkeyMap* map() { return map_.get(); } private: friend struct base::DefaultSingletonTraits<SystemHotkeyHelperMac>; SystemHotkeyHelperMac(); ~SystemHotkeyHelperMac(); // Must be called from the FILE thread. Loads the file containing the system // hotkeys into a NSDictionary* object, and passes the result to FileDidLoad // on the UI thread. void LoadSystemHotkeys(); // Must be called from the UI thread. This takes ownership of |dictionary|. // Parses the system hotkeys from the plist stored in |dictionary|. void FileDidLoad(NSDictionary* dictionary); std::unique_ptr<SystemHotkeyMap> map_; DISALLOW_COPY_AND_ASSIGN(SystemHotkeyHelperMac); }; } // namespace content #endif // CONTENT_BROWSER_COCOA_SYSTEM_HOTKEY_HELPER_MAC_H_
{ "content_hash": "eff2e7a2f94dab3184413dafc20795b8", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 80, "avg_line_length": 28.488888888888887, "alnum_prop": 0.7519500780031201, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "19ecb8889b96f911ab270d5545b95f6d5d5d8a25", "size": "1695", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "content/browser/cocoa/system_hotkey_helper_mac.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import React from 'react'; import { Platform, StyleSheet, TextInput, } from 'react-native'; class Composer extends React.Component { render() { return ( <TextInput placeholder={this.props.placeholder} placeholderTextColor={this.props.placeholderTextColor} multiline={this.props.multiline} onChange={(e) => { this.props.onChange(e); }} style={[styles.textInput, this.props.textInputStyle, { height: this.props.composerHeight, }]} value={this.props.text} accessibilityLabel={this.props.text || this.props.placeholder} enablesReturnKeyAutomatically={true} underlineColorAndroid="transparent" {...this.props.textInputProps} /> ); } } const styles = StyleSheet.create({ textInput: { flex: 1, marginLeft: 10, fontSize: 16, lineHeight: 16, borderRadius: 3, backgroundColor: '#ffffff', paddingLeft:5, marginTop: Platform.select({ ios: 6, android: 0, }), marginBottom: Platform.select({ ios: 5, android: 3, }), }, }); Composer.defaultProps = { onChange: () => {}, composerHeight: Platform.select({ ios: 33, android: 41, }), // TODO SHARE with YOChat.js and tests text: '', placeholder: '输入聊天信息', placeholderTextColor: '#b2b2b2', textInputProps: null, multiline: true, textInputStyle: {}, }; Composer.propTypes = { onChange: React.PropTypes.func, composerHeight: React.PropTypes.number, text: React.PropTypes.string, placeholder: React.PropTypes.string, placeholderTextColor: React.PropTypes.string, textInputProps: React.PropTypes.object, multiline: React.PropTypes.bool, textInputStyle: TextInput.propTypes.style, }; module.exports = Composer;
{ "content_hash": "855ec296c950d1e2429084d02545bda6", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 70, "avg_line_length": 23.68421052631579, "alnum_prop": 0.6455555555555555, "repo_name": "wph1129/react-native-chat", "id": "9752b8e05cfca0bb6184164a2bceee615a8d6ef8", "size": "1812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chat/chat/Composer.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1222" }, { "name": "JavaScript", "bytes": "60911" }, { "name": "Objective-C", "bytes": "4386" }, { "name": "Python", "bytes": "1633" } ], "symlink_target": "" }
/** * RemoteProjectRoleActors.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain; @SuppressWarnings("all") public class RemoteProjectRoleActors extends org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteRoleActors implements java.io.Serializable { private org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteProject project; public RemoteProjectRoleActors() { } public RemoteProjectRoleActors(org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteProjectRole projectRole, org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteRoleActor[] roleActors, org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteUser[] users, org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteProject project) { super(projectRole, roleActors, users); this.project = project; } /** * Gets the project value for this RemoteProjectRoleActors. * * @return project */ public org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteProject getProject() { return project; } /** * Sets the project value for this RemoteProjectRoleActors. * * @param project */ public void setProject(org.javelin.sws.ext.ws.axis1.jira.contractfirst.tm12_arraysplain.RemoteProject project) { this.project = project; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof RemoteProjectRoleActors)) return false; RemoteProjectRoleActors other = (RemoteProjectRoleActors) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.project == null && other.getProject() == null) || (this.project != null && this.project.equals(other.getProject()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getProject() != null) { _hashCode += getProject().hashCode(); } __hashCodeCalc = false; return _hashCode; } }
{ "content_hash": "9c7e4e17709ded6fed8f27b72cbd6c05", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 160, "avg_line_length": 31.746835443037973, "alnum_prop": 0.7049441786283892, "repo_name": "grgrzybek/sws-extensions", "id": "403ef2e02801340586f8038e03ebd2571e836923", "size": "2508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jws/src/test/java/org/javelin/sws/ext/ws/axis1/jira/contractfirst/tm12_arraysplain/RemoteProjectRoleActors.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "159065" }, { "name": "CSS", "bytes": "2651" }, { "name": "Java", "bytes": "2355000" }, { "name": "Shell", "bytes": "3252" }, { "name": "XSLT", "bytes": "6866" } ], "symlink_target": "" }
package com.cody.app.framework.hybrid.core; import android.text.TextUtils; import android.webkit.WebView; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.cody.app.framework.hybrid.core.async.AsyncTaskExecutor; import com.cody.xf.utils.LogUtil; import com.cody.xf.utils.http.Result; import java.lang.ref.WeakReference; import java.util.Locale; /** * native结果数据返回格式: * <p> * var resultJs = { * code: '200',//200成功,400失败 * message: '请求超时',//失败时候的提示,成功可为空 * data: {}//数据 * }; * <p> * Created by Cody.yi on 17/4/12. */ public class JsCallback { private static final String CALLBACK_JS_FORMAT = "javascript:JsBridge.onComplete(%s,%s);"; private static final String CALLBACK_JS_OLD_FORMAT = "javascript:_app_callback('%s','%s');"; private static final String CALLBACK_JS_PROTOCOL_PREFIX = "app_call_prefix"; private WeakReference<WebView> mWebViewWeakRef; private String mPort; private Gson mJsonUtil; private String mCallBackFormat = CALLBACK_JS_FORMAT; private JsCallback(WebView webView, String port) { this.mWebViewWeakRef = new WeakReference<>(webView); mJsonUtil = new Gson(); if (TextUtils.isEmpty(port))return; if (port.contains(CALLBACK_JS_PROTOCOL_PREFIX)){ mCallBackFormat = CALLBACK_JS_OLD_FORMAT; }else { mCallBackFormat = CALLBACK_JS_FORMAT; } this.mPort = port.replace(CALLBACK_JS_PROTOCOL_PREFIX,""); } public static JsCallback newInstance(WebView webView, String port) { return new JsCallback(webView, port); } /** * 返回结果给Js */ private void callJs(final String callbackJs) { final WebView webView = mWebViewWeakRef.get(); if (webView == null) { LogUtil.d("JsCallback", "The WebView related to the JsCallback has been recycled!"); } else { if (AsyncTaskExecutor.isMainThread()) { webView.loadUrl(callbackJs); } else { AsyncTaskExecutor.runOnMainThread(new Runnable() { @Override public void run() { webView.loadUrl(callbackJs); } }); } } } /** * 直接返回消息,不需要包含code,message 结构化,兼容老定义 */ public void oldFormat(JsonObject result) { if (result == null)return; callJs(getCallBackUrl(result)); LogUtil.d("JsCallback", result.toString()); } /** * 直接返回失败消息,不需要包含data部分 */ public void failure(String message) { Result<Object> result = new Result<>(JsCode.FAILURE, message, null); callJs(getCallBackUrl(result)); LogUtil.d("JsCallback", message); } /** * 直接返回成功消息,不需要包含data部分 */ public void success(String message) { Result<Object> result = new Result<>(JsCode.SUCCESS, message, null); callJs(getCallBackUrl(result)); } /** * 直接返回成功消息,需要包含data部分 */ public void success(String message, JsonObject data) { Result<JsonObject> result = new Result<>(JsCode.SUCCESS, message, data); callJs(getCallBackUrl(result)); } /** * 直接返回成功消息,需要包含data部分 */ public void success(JsonObject data) { Result<JsonObject> result = new Result<>(JsCode.SUCCESS, null, data); callJs(getCallBackUrl(result)); } /** * 直接返回成功消息,需要包含data部分 */ public void callback(JsonObject result) { callJs(getCallBackUrl(result)); } private String getCallBackUrl(Result result) { return String.format(Locale.getDefault(), mCallBackFormat, mPort, mJsonUtil.toJson(result)); } private String getCallBackUrl(JsonObject result) { return String.format(Locale.getDefault(), mCallBackFormat, mPort, result); } }
{ "content_hash": "b60471ea5aaa6abcb251229644f762ce", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 100, "avg_line_length": 29.7984496124031, "alnum_prop": 0.6243496357960457, "repo_name": "codyer/CleanFramework", "id": "e99a123c00db9e041f4cd4742668f4d35981bd45", "size": "4114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/cody/app/framework/hybrid/core/JsCallback.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "19368" }, { "name": "Java", "bytes": "1303415" }, { "name": "JavaScript", "bytes": "4480" } ], "symlink_target": "" }
package org.jgroups.protocols.jzookeeper.zabAARWAsync; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.Message.Flag; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.annotations.Property; import org.jgroups.stack.Protocol; /* * It is orignal protocol of Apache Zookeeper. Also it has features of testing throuhput, latency (in Nano), ant etc. * When using testing, it provides warm up test before starting real test. * @author Ibrahim EL-Sanosi */ public class Zab extends Protocol { private final static String ProtocolName = "ZabAA"; private final static int numberOfSenderInEachClient = 25; private final AtomicLong zxid = new AtomicLong(0); private ExecutorService executorProposal; private ExecutorService executorDelivery; private Address local_addr; private volatile Address leader; private volatile View view; private volatile boolean is_leader = false; private List<Address> zabMembers = Collections .synchronizedList(new ArrayList<Address>()); private long lastZxidProposed = 0, lastZxidCommitted = 0; private final Map<Long, Integer> followerACKs = Collections.synchronizedMap(new HashMap<Long, Integer>()); private final Set<MessageId> requestQueue = Collections .synchronizedSet(new HashSet<MessageId>()); private final Map<Long, ZabHeader> queuedCommitMessage = Collections .synchronizedMap(new HashMap<Long, ZabHeader>()); private final Map<Long, ZabHeader> queuedProposalMessage = Collections .synchronizedMap(new HashMap<Long, ZabHeader>()); private final LinkedBlockingQueue<ZabHeader> queuedMessages = new LinkedBlockingQueue<ZabHeader>(); private final LinkedBlockingQueue<Long> delivery = new LinkedBlockingQueue<Long>(); private ConcurrentMap<Long, Proposal> outstandingProposals = new ConcurrentHashMap<Long, Proposal>(); private final Map<MessageId, Message> messageStore = Collections .synchronizedMap(new HashMap<MessageId, Message>()); private volatile boolean running = true; private volatile boolean startThroughput = false; private final static String outDir = "/work/Zab2PN/"; private final static String percentRW = "25%:75%"; private ProtocolStats stats = new ProtocolStats(); @Property(name = "Zab_size", description = "It is Zab cluster size") private Timer timer = new Timer(); private int clusterSize = 3; private static int warmUp = 0; //private Timer checkFinished = new Timer(); private static AtomicInteger clientFinished = new AtomicInteger(); private static int numReadCoundRecieved=0; /* * Empty constructor */ public Zab() { } @ManagedAttribute public boolean isleaderinator() { return is_leader; } public Address getleaderinator() { return leader; } public Address getLocalAddress() { return local_addr; } @Override public void start() throws Exception { super.start(); running = true; executorProposal = Executors.newSingleThreadExecutor(); executorProposal.execute(new FollowerMessageHandler(this.id)); executorDelivery = Executors.newSingleThreadExecutor(); executorDelivery.execute(new MessageHandler()); this.stats = new ProtocolStats(ProtocolName, 10, numberOfSenderInEachClient, outDir, false); //checkFinished.schedule(new CheckFinished(), 5, 10000);//For tail proposal timeout log.setLevel("trace"); } /* * Reset all protocol fields, reset invokes after warm up has finished, then callback the clients to start * main test */ public void reset() { zxid.set(0); lastZxidProposed = 0; lastZxidCommitted = 0; requestQueue.clear(); //queuedCommitMessage.clear(); queuedProposalMessage.clear(); queuedMessages.clear(); outstandingProposals.clear(); messageStore.clear(); //startThroughput = false; warmUp = queuedCommitMessage.size(); log.info("Reset done"); } @Override public void stop() { running = false; executorProposal.shutdown(); executorDelivery.shutdown(); super.stop(); } public Object down(Event evt) { switch (evt.getType()) { case Event.MSG: return null; // don't pass down case Event.SET_LOCAL_ADDRESS: local_addr = (Address) evt.getArg(); break; } return down_prot.down(evt); } public Object up(Event evt) { Message msg = null; ZabHeader hdr; switch (evt.getType()) { case Event.MSG: msg = (Message) evt.getArg(); hdr = (ZabHeader) msg.getHeader(this.id); if (hdr == null) { break; // pass up } switch (hdr.getType()) { case ZabHeader.REQUESTW: forwardToLeader(msg); break; case ZabHeader.REQUESTR: //log.info(">>>>>>>>>>>>>>>>>Receive read<<<<<<<<<<<<<<<<<<<"); hdr.getMessageOrderInfo().getId().setStartTime(System.nanoTime()); readData(hdr.getMessageOrderInfo()); break; case ZabHeader.FORWARD: queuedMessages.add(hdr); break; case ZabHeader.PROPOSAL: sendACK(msg, hdr); break; case ZabHeader.ACK: processACK(msg); break; case ZabHeader.COMMIT: delivery.add(hdr.getZxid()); break; case ZabHeader.STARTWORKLOAD: startThroughput = true; stats.setStartThroughputTime(System.currentTimeMillis()); stats.setLastNumReqDeliveredBefore(0); stats.setLastThroughputTime(System.currentTimeMillis()); timer.schedule(new Throughput(), 1000, 1000); this.stats = new ProtocolStats(ProtocolName, 10, numberOfSenderInEachClient, outDir, false); reset(); break; case ZabHeader.COUNTMESSAGE: addCountReadToTotal(hdr); break; case ZabHeader.FINISHED: log.info("I Have notfied from Client----> "+msg.getSrc()); if (clientFinished.incrementAndGet() == 10) { running = false; timer.cancel(); sendCountRead(); log.info("Printing stats"); } break; } //s return null; case Event.VIEW_CHANGE: handleViewChange((View) evt.getArg()); break; } return up_prot.up(evt); } /* * --------------------------------- Private Methods -------------------------------- */ private void handleViewChange(View v) { List<Address> mbrs = v.getMembers(); //leader = mbrs.get(0); //make the first three joined server as ZK servers if (mbrs.size() == (clusterSize+2)) { for (int i=2;i<mbrs.size();i++){ zabMembers.add(mbrs.get(i)); } leader = zabMembers.get(0); if (leader.equals(local_addr)) { is_leader = true; } } if (mbrs.size() > (clusterSize+2) && zabMembers.isEmpty()) { for (int i = 2; i < mbrs.size(); i++) { zabMembers.add(mbrs.get(i)); if ((zabMembers.size()>=clusterSize)) break; } leader = zabMembers.get(0); if (leader.equals(local_addr)) { is_leader = true; } } log.info("zabMembers size = " + zabMembers); if (mbrs.isEmpty()) return; if (view == null || view.compareTo(v) < 0) view = v; else return; } private long getNewZxid() { return zxid.incrementAndGet(); } /* * If this server is a leader put the request in queue for processing it. * otherwise forwards request to the leader */ private void forwardToLeader(Message msg) { //stats.incNumRequest(); ZabHeader hdrReq = (ZabHeader) msg.getHeader(this.id); requestQueue.add(hdrReq.getMessageOrderInfo().getId()); if (is_leader) { long stp = System.nanoTime(); hdrReq.getMessageOrderInfo().getId().setStartTime(stp); queuedMessages.add(hdrReq); } else { long stf = System.nanoTime(); hdrReq.getMessageOrderInfo().getId().setStartTime(stf); forward(msg); } } /* * Forward request to the leader */ private void forward(Message msg) { Address target = leader; ZabHeader hdrReq = (ZabHeader) msg.getHeader(this.id); ZabHeader hdr = new ZabHeader(ZabHeader.FORWARD, hdrReq.getMessageOrderInfo()); Message forward_msg = new Message(target).putHeader(this.id, hdr); forward_msg.setBuffer(new byte[1000]); try { //forward_msg.setFlag(Message.Flag.DONT_BUNDLE); down_prot.down(new Event(Event.MSG, forward_msg)); } catch (Exception ex) { log.error("failed forwarding message to " + msg, ex); } } /* * This method is invoked by follower. * Follower receives a proposal. This method generates ACK message and send it to the leader. */ private void sendACK(Message msg, ZabHeader hdrAck){ Proposal p; p = new Proposal(); p.AckCount++; // Ack from leader p.setMessageOrderInfo(hdrAck.getMessageOrderInfo()); outstandingProposals.put(hdrAck.getMessageOrderInfo().getOrdering(), p); queuedProposalMessage.put(hdrAck.getMessageOrderInfo().getOrdering(), hdrAck); ZabHeader hdrACK = new ZabHeader(ZabHeader.ACK, hdrAck.getMessageOrderInfo().getOrdering()); Message ackMessage = new Message().putHeader(this.id, hdrACK); //ackMessage.setFlag(Message.Flag.DONT_BUNDLE); try{ for (Address address : zabMembers) { if (address.equals(local_addr)) { processACK(ackMessage); continue; } else{ Message cpy = ackMessage.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } } }catch(Exception ex) { log.error("failed proposing message to members"); } } /* * This method is invoked by leader. It receives ACK message from a follower * and check if a majority is reached for particular proposal. */ private synchronized void processACK(Message msgACK){ Proposal p = null; ZabHeader hdr = (ZabHeader) msgACK.getHeader(this.id); long ackZxid = hdr.getZxid(); if (lastZxidCommitted >= ackZxid) { return; } if (ackZxid > lastZxidCommitted && !outstandingProposals.containsKey(ackZxid)) { if (!followerACKs.containsKey(ackZxid)) followerACKs.put(ackZxid,1); else{ int count = followerACKs.get(ackZxid); followerACKs.put(ackZxid, count++); } } p = outstandingProposals.get(ackZxid); if (p == null) { return; } p.AckCount++; if (followerACKs.containsKey(ackZxid)){ p.AckCount = p.AckCount + followerACKs.get(ackZxid); followerACKs.remove(ackZxid); } if (isQuorum(p.getAckCount())) { if (ackZxid == lastZxidCommitted+1){ delivery.add(ackZxid); outstandingProposals.remove(ackZxid); lastZxidCommitted = ackZxid; } else { long zxidCommiting = lastZxidCommitted +1; for (long z = zxidCommiting; z < ackZxid+1; z++){ delivery.add(z); outstandingProposals.remove(z); lastZxidCommitted = z; } } } } /* * Deliver the proposal locally and if the current server is the receiver of the request, * replay to the client. */ private void deliver(long dZxid) { MessageOrderInfo messageOrderInfo = null; ZabHeader hdrOrginal = queuedProposalMessage.remove(dZxid); //log.info("hdrOrginal zxid = " + hdrOrginal.getZxid()); if(hdrOrginal==null){ log.info("delivering zxid=" + dZxid+" Lastdelivered="+lastZxidCommitted); } messageOrderInfo = hdrOrginal.getMessageOrderInfo(); queuedCommitMessage.put(dZxid, hdrOrginal); stats.incnumReqDelivered(); stats.setEndThroughputTime(System.currentTimeMillis()); //log.info("Zxid=:"+dZxid); if (requestQueue.contains(messageOrderInfo.getId())) { long startTime = hdrOrginal.getMessageOrderInfo().getId().getStartTime(); long endTime = System.nanoTime(); stats.addLatency((endTime - startTime)); sendOrderResponse(messageOrderInfo); requestQueue.remove((messageOrderInfo.getId())); } } private synchronized void readData(MessageOrderInfo messageInfo){ Message readReplay = null; CSInteractionHeader hdrResponse = null; ZabHeader hdrOrginal = null; synchronized(queuedCommitMessage){ hdrOrginal = queuedCommitMessage.get(messageInfo.getOrdering()); } if (hdrOrginal != null){ hdrResponse = new CSInteractionHeader(CSInteractionHeader.RESPONSER, messageInfo); readReplay = new Message(messageInfo.getId().getOriginator()).putHeader((short) 79, hdrResponse); } else{//Simulate return null if the requested data is not stored in Zab log.info(" Read null%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); hdrResponse = new CSInteractionHeader(CSInteractionHeader.RESPONSER, messageInfo); readReplay = new Message(messageInfo.getId().getOriginator()).putHeader((short) 79, hdrResponse); } long startTime = messageInfo.getId().getStartTime(); long endTime = System.nanoTime(); stats.addReadLatency((endTime - startTime)); messageInfo.getId().setStartTime(0); readReplay.setBuffer(new byte[1000]); stats.incnumReqDelivered(); //readReplay.setFlag(Message.Flag.DONT_BUNDLE); down_prot.down(new Event(Event.MSG, readReplay)); } private void sendOrderResponse(MessageOrderInfo messageOrderInfo){ CSInteractionHeader hdrResponse = new CSInteractionHeader(CSInteractionHeader.RESPONSEW, messageOrderInfo); Message msgResponse = new Message(messageOrderInfo.getId() .getOriginator()).putHeader((short) 79, hdrResponse); //msgResponse.setFlag(Message.Flag.DONT_BUNDLE); down_prot.down(new Event(Event.MSG, msgResponse)); } /* * Check a majority */ private boolean isQuorum(int majority) { return majority >= ((clusterSize / 2) + 1) ? true : false; //return majority >= (clusterSize) ? true : false; } private void sendCountRead(){ ZabHeader readCount = new ZabHeader( ZabHeader.COUNTMESSAGE, ((stats.getnumReqDelivered()-queuedCommitMessage.size())-warmUp)); Message countRead = new Message(leader).putHeader(this.id, readCount); countRead.setFlag(Flag.DONT_BUNDLE); for (Address address : zabMembers) { if (address.equals(local_addr)) continue; Message cpy = countRead.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } } private synchronized void addCountReadToTotal(ZabHeader countReadHeader) { long readCount = countReadHeader.getZxid(); stats.addToNumReqDelivered((int) readCount); numReadCoundRecieved++; if(numReadCoundRecieved==(zabMembers.size()-1)){ stats.printProtocolStats(queuedCommitMessage.size(), clusterSize, percentRW); } } /* * ----------------------------- End of Private Methods -------------------------------- */ final class FollowerMessageHandler implements Runnable { private short id; public FollowerMessageHandler(short id) { this.id = id; } /** * create a proposal and send it out to all the members * * @param message */ @Override public void run() { handleRequests(); } public void handleRequests() { ZabHeader hdrReq = null; while (running) { try { hdrReq = queuedMessages.take(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } long new_zxid = getNewZxid(); MessageOrderInfo messageOrderInfo = hdrReq.getMessageOrderInfo(); messageOrderInfo.setOrdering(new_zxid); ZabHeader hdrProposal = new ZabHeader(ZabHeader.PROPOSAL, messageOrderInfo); Message proposalMessage = new Message().putHeader(this.id, hdrProposal);//.setFlag(Message.Flag.DONT_BUNDLE); proposalMessage.setBuffer(new byte[1000]); proposalMessage.setSrc(local_addr); Proposal p = new Proposal(); p.setMessageOrderInfo(hdrReq.getMessageOrderInfo()); p.AckCount++; outstandingProposals.put(new_zxid, p); queuedProposalMessage.put(new_zxid, hdrProposal); try { for (Address address : zabMembers) { if (address.equals(leader)) continue; Message cpy = proposalMessage.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } } catch (Exception ex) { log.error("failed proposing message to members"); } } } } final class MessageHandler implements Runnable { @Override public void run() { log.info("call deliverMessages()"); deliverMessages(); } private void deliverMessages() { long zxidDeliver = 0; while (true) { try { zxidDeliver = delivery.take(); } catch (InterruptedException e) { e.printStackTrace(); } deliver(zxidDeliver); } } } class Throughput extends TimerTask { public Throughput() { } private long startTime = 0; private long currentTime = 0; private double currentThroughput = 0; private int finishedThroughput = 0; @Override public void run() { startTime = stats.getLastThroughputTime(); currentTime = System.currentTimeMillis(); finishedThroughput=stats.getnumReqDelivered(); currentThroughput = (((double)finishedThroughput - stats .getLastNumReqDeliveredBefore()) / ((double)(currentTime - startTime)/1000.0)); stats.setLastNumReqDeliveredBefore(finishedThroughput); stats.setLastThroughputTime(currentTime); stats.addThroughput(currentThroughput); } public String convertLongToTimeFormat(long time) { Date date = new Date(time); SimpleDateFormat longToTime = new SimpleDateFormat("HH:mm:ss.SSSZ"); return longToTime.format(date); } } // class CheckFinished extends TimerTask { // private int workload=1000000; // public CheckFinished() { // } // // public void run() { // if(lastZxidCommitted>=workload){ // stats.printProtocolStats(queuedCommitMessage.size(), clusterSize); // log.info("Printing stats"); // checkFinished.cancel(); // timer.cancel(); // } // // } // // } }
{ "content_hash": "6d4a0b5f4c388f3d8f79d5d89f63191b", "timestamp": "", "source": "github", "line_count": 618, "max_line_length": 118, "avg_line_length": 29.964401294498384, "alnum_prop": 0.6747488929690031, "repo_name": "ibrahimshbat/JGroups", "id": "0ccc8863020ab6ebc3f485a96564de0791b0ab4d", "size": "18518", "binary": false, "copies": "1", "ref": "refs/heads/Zab_4", "path": "src/org/jgroups/protocols/jzookeeper/zabAARWAsync/Zab.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3465" }, { "name": "Java", "bytes": "12917680" }, { "name": "Python", "bytes": "2267" }, { "name": "Shell", "bytes": "91017" } ], "symlink_target": "" }
describe("sap.m.Carousel", function() { browser.testrunner.currentSuite.meta.controlName = 'sap.m.Carousel'; var myCarousel = element(by.id("myCarousel")); // initial loading" it("should load test page", function () { expect(takeScreenshot()).toLookAs("0_initial"); }); // click right arrow it("should scroll right", function () { //hover on the carousel to show the arrows browser.actions().mouseMove(element(by.id('myCarousel'))).perform(); element(by.id("myCarousel-arrowScrollRight")).click(); expect(takeScreenshot(myCarousel)).toLookAs("1_click_right_arrow"); }); // change height to 50% it("should change the height to 50%", function () { element(by.id("btnHeight50")).click(); expect(takeScreenshot(myCarousel)).toLookAs("2_height_50_percent"); }); // change height to 600px it("should change the height to 600px", function () { element(by.id("btnHeight600px")).click(); expect(takeScreenshot(myCarousel)).toLookAs("3_height_600px"); element(by.id("btnReset")).click(); }); // change width to 60% it("should change the width to 60%", function () { element(by.id("btnWidth60")).click(); //hover on the carousel to show the arrows browser.actions().mouseMove(element(by.id('myCarousel'))).perform(); expect(takeScreenshot(myCarousel)).toLookAs("4_width_60_percent"); }); // change width to 400px it("should change the width to 400px", function () { element(by.id("btnWidth400px")).click(); //hover on the carousel to show the arrows browser.actions().mouseMove(element(by.id('myCarousel'))).perform(); expect(takeScreenshot(myCarousel)).toLookAs("5_width_400px"); element(by.id("btnReset")).click(); }); // change arrows position it("should change arrows placement", function() { element(by.id("RB-Indicator")).click(); expect(takeScreenshot(myCarousel)).toLookAs("6_arrow_placement"); }); // change page indicator position it("should change page indicator placement", function() { element(by.id("RB-Top")).click(); expect(takeScreenshot(myCarousel)).toLookAs("7_page_indicator_visibility"); }); // toggle page indicator visibility it("should change page indicator placement", function() { element(by.id("RB-No")).click(); expect(takeScreenshot(myCarousel)).toLookAs("8_page_indicator_placement"); }); // change the number of slides it("should change number of slides and see the change in the page indicator", function() { //click to show the page indicator element(by.id("RB-Yes")).click(); element(by.id('input-slides-number-inner')).clear().sendKeys('9'); expect(takeScreenshot(myCarousel)).toLookAs("9_page_indicator_type"); }); });
{ "content_hash": "49a75532ea0c32645d114cfad207c257", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 91, "avg_line_length": 31.97590361445783, "alnum_prop": 0.6978146194423511, "repo_name": "openui5/packaged-sap.m", "id": "b0c555b2cb83eb65dd8504e61fa29dae49aadf99", "size": "2654", "binary": false, "copies": "1", "ref": "refs/heads/rel-1.44", "path": "test-resources/sap/m/visual/Carousel.spec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2610355" }, { "name": "Gherkin", "bytes": "1908" }, { "name": "HTML", "bytes": "6081296" }, { "name": "JavaScript", "bytes": "7202501" } ], "symlink_target": "" }
namespace boost { namespace mpl { template<> struct front_impl< aux::half_open_range_tag > { template< typename Range > struct apply { typedef typename Range::start type; }; }; }} #endif // BOOST_MPL_AUX_RANGE_C_FRONT_HPP_INCLUDED
{ "content_hash": "ffc61f24a4abaa07cae428601dd21526", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 50, "avg_line_length": 18.142857142857142, "alnum_prop": 0.65748031496063, "repo_name": "fredericjoanis/Argorha-Pathfinding", "id": "97902b9b78cb69c7ba1c1aff23f2c63e6ebf82b1", "size": "816", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "extern/Boost/mpl/aux_/range_c/front.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "54217" }, { "name": "C++", "bytes": "1293972" }, { "name": "CSS", "bytes": "2711" }, { "name": "Lua", "bytes": "12708" }, { "name": "Objective-C", "bytes": "35311" }, { "name": "Shell", "bytes": "1465" } ], "symlink_target": "" }
using Poco::Net::Socket; using Poco::Net::SocketStream; using Poco::Net::StreamSocket; using Poco::Net::ServerSocket; using Poco::Net::SocketAddress; using Poco::Net::ConnectionRefusedException; using Poco::Timespan; using Poco::Stopwatch; using Poco::TimeoutException; using Poco::InvalidArgumentException; SocketStreamTest::SocketStreamTest(const std::string& name): CppUnit::TestCase(name) { } SocketStreamTest::~SocketStreamTest() { } void SocketStreamTest::testStreamEcho() { EchoServer echoServer; StreamSocket ss; ss.connect(SocketAddress("localhost", echoServer.port())); SocketStream str(ss); str << "hello"; assert (str.good()); str.flush(); assert (str.good()); ss.shutdownSend(); char buffer[5]; str.read(buffer, sizeof(buffer)); assert (str.good()); assert (str.gcount() == 5); assert (std::string(buffer, 5) == "hello"); ss.close(); } void SocketStreamTest::testEOF() { StreamSocket ss; SocketStream str(ss); { EchoServer echoServer; ss.connect(SocketAddress("localhost", echoServer.port())); str << "hello"; assert (str.good()); str.flush(); assert (str.good()); ss.shutdownSend(); char buffer[5]; str.read(buffer, sizeof(buffer)); assert (str.good()); assert (str.gcount() == 5); assert (std::string(buffer, 5) == "hello"); } int c = str.get(); assert (c == -1); assert (str.eof()); ss.close(); } void SocketStreamTest::setUp() { } void SocketStreamTest::tearDown() { } CppUnit::Test* SocketStreamTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SocketStreamTest"); CppUnit_addTest(pSuite, SocketStreamTest, testStreamEcho); CppUnit_addTest(pSuite, SocketStreamTest, testEOF); return pSuite; }
{ "content_hash": "bba2c42fc24902c29d23dfdf69276cd7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 84, "avg_line_length": 18.532608695652176, "alnum_prop": 0.6961876832844575, "repo_name": "119/vdc", "id": "7f395962f0d71849499b2874952293fb4c5744cc", "size": "3597", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "3rdparty/poco-1.4.6p1/Net/testsuite/src/SocketStreamTest.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package fr.inra.maiage.bibliome.util; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; import fr.inra.maiage.bibliome.util.filters.Filter; import fr.inra.maiage.bibliome.util.filters.Filters; import fr.inra.maiage.bibliome.util.mappers.Mapper; import fr.inra.maiage.bibliome.util.mappers.Mappers; import fr.inra.maiage.bibliome.util.mappers.ParamMapper; /** * Miscellanous iterator utilities. * @author rbossy * */ public abstract class Iterators { private final static class LoopIterable<T> implements Iterable<T> { private final Iterator<T> it; public LoopIterable(Iterator<T> it) { super(); this.it = it; } @Override public Iterator<T> iterator() { return it; } } /** * Returns an iterable whose iterator() method returns the specified iterator. * The returned iterable can be used in only one loop. * @param <T> * @param it * @return an iterable whose iterator() method returns the specified iterator */ public static final <T> Iterable<T> loop(Iterator<T> it) { return new LoopIterable<T>(it); } /** * NOP loop the specified iterator until there are no more elements. * @param it */ public static void deplete(Iterator<?> it) { while (it.hasNext()) it.next(); } /** * Returns an empty iterator. * The hasNext() method of the returned iterator always returns false. * @param <T> * @return an empty iterator */ public static final <T> Iterator<T> emptyIterator() { Collection<T> emptyCollection = Collections.emptySet(); return emptyCollection.iterator(); } private static final class SingletonIterator<T> implements Iterator<T> { private final T x; private boolean notSeen = true; private SingletonIterator(T x) { super(); this.x = x; } @Override public boolean hasNext() { return notSeen; } @Override public T next() { if (!notSeen) throw new NoSuchElementException(); notSeen = false; return x; } @Override public void remove() { throw new UnsupportedOperationException(); } } /** * Returns an iterator that iterates over a single value. * @param <T> * @param x the value * @return an iterator that iterates over a single value */ public static final <T,U extends T> Iterator<T> singletonIterator(U x) { return new SingletonIterator<T>(x); } public static final <T,U extends T> Iterator<T> nonNullSingleton(U x) { if (x == null) return emptyIterator(); return singletonIterator(x); } private static final class FlatIterator<T> implements Iterator<T> { private final Iterator<Iterator<T>> master; private Iterator<T> current = emptyIterator(); private FlatIterator(Iterator<Iterator<T>> master) { super(); this.master = master; } private void forward() { while (!current.hasNext()) { if (!master.hasNext()) break; current = master.next(); } } @Override public boolean hasNext() { forward(); return current.hasNext(); } @Override public T next() { forward(); return current.next(); } @Override public void remove() { current.remove(); } } /** * Returns an iterator that chains the elements in the specified iterators. * @param <T> * @param it * @return an iterator that chains the elements in the specified iterators */ public static final <T> Iterator<T> flatten(Iterator<Iterator<T>> it) { return new FlatIterator<T>(it); } private static final class FlatMapperIterator<T,U> implements Iterator<U> { private final Mapper<T,? extends Iterator<U>> mapper; private final Iterator<? extends T> masterIterator; private Iterator<U> currentIterator = emptyIterator(); private FlatMapperIterator(Mapper<T,? extends Iterator<U>> mapper, Iterator<? extends T> masterIterator) { super(); this.mapper = mapper; this.masterIterator = masterIterator; } @Override public boolean hasNext() { while (true) { if (currentIterator.hasNext()) return true; if (!masterIterator.hasNext()) return false; currentIterator = mapper.map(masterIterator.next()); } } @Override public U next() { while (true) { if (currentIterator.hasNext()) return currentIterator.next(); currentIterator = mapper.map(masterIterator.next()); } } @Override public void remove() { currentIterator.remove(); } } /** * Map and flatten composition. * @param it * @param mapper */ public static final <T,U> Iterator<U> mapAndFlatten(Iterator<? extends T> it, Mapper<T,? extends Iterator<U>> mapper) { return new FlatMapperIterator<T,U>(mapper, it); } /** * Adds the elements from the specified iterator to the specified collection. * @param <T> * @param it * @param target * @return target */ public static final <T> Collection<T> fill(Iterator<? extends T> it, Collection<T> target) { while (it.hasNext()) target.add(it.next()); return target; } /** * Upcasts an iterator. * @param <T> * @param <U> * @param it */ @SuppressWarnings("unchecked") public static final <T,U extends T> Iterator<T> upcast(Iterator<U> it) { return (Iterator<T>) it; } public static final class Item<T> { public final int index; public final T value; private Item(int index, T value) { super(); this.index = index; this.value = value; } } /** * Filter and map composition. * @param filter * @param mapper * @param it */ public static <T,U> Iterator<T> filterAndMap(Filter<U> filter, Mapper<U,T> mapper, Iterator<U> it) { return Mappers.apply(mapper, Filters.apply(filter, it)); } public static <T,U,P> Iterator<T> filterAndMap(Filter<U> filter, ParamMapper<U,T,P> mapper, P param, Iterator<U> it) { return Mappers.apply(mapper, param, Filters.apply(filter, it)); } /** * Map and filter composition. * @param mapper * @param filter * @param it */ public static <T,U> Iterator<T> mapAndFilter(Mapper<U,T> mapper, Filter<T> filter, Iterator<U> it) { return Filters.apply(filter, Mappers.apply(mapper, it)); } /** * Counts the remaining number of elements in the specified iterator. * This method depletes the iterator. * @param it * @return the number of elements that remained in the specified iterator. */ public static int count(Iterator<?> it) { int result = 0; while (it.hasNext()) { result++; it.next(); } return result; } private static final class EnumerationDecorator<T> implements Enumeration<T> { private final Iterator<T> iterator; private EnumerationDecorator(Iterator<T> iterator) { super(); this.iterator = iterator; } @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public T nextElement() { return iterator.next(); } } public static final <T> Enumeration<T> getEnumeration(Iterator<T> it) { return new EnumerationDecorator<T>(it); } public static final <T> void removeAll(Iterator<T> it) { while (it.hasNext()) { it.next(); it.remove(); } } public static final <T> Iterator<T> flatten(Collection<Iterator<T>> iterators) { return flatten(iterators.iterator()); } @SuppressWarnings("unchecked") public static final <T> Iterator<T> flatten(Iterator<T>... iterators) { return flatten(Arrays.asList(iterators)); } }
{ "content_hash": "8ab94df50fd39e43119c638d751bae8f", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 123, "avg_line_length": 25.449367088607595, "alnum_prop": 0.6243471773190749, "repo_name": "Bibliome/bibliome-java-utils", "id": "c6582d568c748c8b82513000f258a84e19b9f3e2", "size": "8643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/fr/inra/maiage/bibliome/util/Iterators.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "18242" }, { "name": "Java", "bytes": "1120043" }, { "name": "Shell", "bytes": "2414" } ], "symlink_target": "" }
/* eslint-env node, es6, mocha */ const PluginManager = require("../../src/PluginManager"); const Auth = require("../../src/helpers/Auth"); const TelegramBot = require("./helpers/TelegramBot"); const config = require("./sample-config.json"); const auth = new Auth(config); let i = 0; function makeSentinel() { return `Sentinel<${i++}>`; } function expectsAnyMessage(bot) { return new Promise(resolve => bot.on("_debug_message", resolve)); } function expectsMessage(bot, target) { // Todo: cleanup listener return new Promise(resolve => bot.on("_debug_message", ({text}) => { if (text === target) resolve(); })); } function notExpectsMessage(bot, target, errorText = "Should not have received message", delay = 500) { // Todo: cleanup listener return new Promise((resolve, reject) => { const timeout = setTimeout(resolve, delay); bot.on("_debug_message", ({text}) => { if (text !== target) return; clearTimeout(timeout); reject(new Error(errorText)); }); }); } describe("Bot", function() { let bot; let pluginManager; it("should start correctly with the Ping plugin", function() { bot = new TelegramBot(); pluginManager = new PluginManager(bot, config, auth); pluginManager.loadPlugins(["Ping"]); // [] = Active plugins }); it("should reply to /help", function() { const p = expectsAnyMessage(bot); bot.pushMessage({text: "/help"}); return p; }); it("should reply to /help Ping", function() { const p = expectsAnyMessage(bot); bot.pushMessage({text: "/help Ping"}); return p; }); it("should enable plugins", function() { const sentinel = makeSentinel(); const p = expectsMessage(bot, sentinel); bot.pushRootMessage({text: "/enable Echo"}); bot.pushMessage({text: `/echo ${sentinel}`}); return p; }); it("should disable plugins", function() { this.slow(1100); const sentinel = makeSentinel(); const p = notExpectsMessage(bot, sentinel, "Echo wasn't disabled"); bot.pushRootMessage({text: "/disable Echo"}); bot.pushMessage({text: `/echo ${sentinel}`}); return p; }); it("shouldn't let unauthorized users enable plugins", function() { this.slow(200); const sentinel = makeSentinel(); const p = notExpectsMessage(bot, sentinel, "Echo was enabled"); bot.pushEvilMessage({text: "/enable Echo"}); bot.pushMessage({text: `/echo ${sentinel}`}); return p; }); it("shouldn't let unauthorized users disable plugins", function() { pluginManager.loadPlugins(["Echo"]); const sentinel = makeSentinel(); const p = expectsMessage(bot, sentinel); bot.pushEvilMessage({text: "/disable Echo"}); bot.pushMessage({text: `/echo ${sentinel}`}); return p; }); it("should support multiline inputs", function() { pluginManager.loadPlugins(["Echo"]); const string = makeSentinel() + "\n" + makeSentinel(); const p = expectsMessage(bot, string); bot.pushMessage({text: `/echo ${string}`}); return p; }); }); describe("Ignore", function() { const bot = new TelegramBot(); const pluginManager = new PluginManager(bot, config, auth); pluginManager.loadPlugins(["Echo", "Ignore"]); it("should ignore", function() { const sentinel = makeSentinel(); const p = notExpectsMessage(bot, sentinel, "The bot replied to an echo"); bot.pushRootMessage({text: "/ignore 123"}); // Give Ignore some time to react setTimeout(() => bot.pushMessage({ text: `/echo ${sentinel}`, from: { id: 123, first_name: "Foo Bar", username: "foobar" } }), 50); return p; }); }); describe("Ping", function() { const bot = new TelegramBot(); const pluginManager = new PluginManager(bot, config, auth); pluginManager.loadPlugins(["Ping"]); it("should reply to /ping", function() { const p = expectsAnyMessage(bot); bot.pushMessage({text: "ping"}); return p; }); }); describe("Antiflood", function() { const bot = new TelegramBot(); const pluginManager = new PluginManager(bot, config, auth); pluginManager.loadPlugins(["Antiflood", "Echo"]); it("should reject spam", async function() { this.timeout(4000); this.slow(3000); const sentinel = makeSentinel(); const spamAmount = 50; const spamLimit = 5; let replies = 0; const callback = ({text}) => { if (text === sentinel) replies++; }; bot.on("_debug_message", callback); bot.pushRootMessage({text: `/floodignore ${spamLimit}`}); // Leave the plugin some time to set up the thing await (new Promise(resolve => setTimeout(() => resolve(), 100))); for (let i = 0; i < spamAmount; i++) bot.pushMessage({text: `/echo ${sentinel}`}); return new Promise((resolve, reject) => setTimeout(function() { // bot.removeListener("_debug_message", callback); if (replies === spamLimit) resolve(); else reject(new Error(`The bot replied ${replies} times.`)); }, 50 * spamAmount)); // The bot shouldn't take longer than 50 ms avg per message }); }); describe("Scheduler", function() { it("should initialize correctly", function() { require("../../src/helpers/Scheduler"); }); it.skip("should schedule events", function(done) { this.slow(1500); const scheduler = require("../../src/helpers/Scheduler"); const sentinel = makeSentinel(); const delay = 1000; const start = new Date(); scheduler.on(sentinel, () => { const end = new Date(); // Margin of error: +/- 100 ms if ((start - end) > (delay + 100)) done(new Error(`Takes too long: ${start - end} ms`)); else if ((start - end) < (delay - 100)) done(new Error(`Takes too little: ${start - end} ms`)); else done(); }); scheduler.schedule(sentinel, {}, new Date(start + delay)); }); it.skip("should cancel events", function(done) { this.slow(1500); const scheduler = require("../../src/helpers/Scheduler"); const sentinel = makeSentinel(); const doneTimeout = setTimeout(() => done(), 1000); sentinel.on(sentinel, () => { clearTimeout(doneTimeout); done(new Error("Event was not cancelled")); }, {}, new Date(new Date() + 500)); const errorEvent = scheduler.schedule(sentinel, {}); scheduler.cancel(errorEvent); }); it.skip("should look up events by metadata", function(done) { this.slow(1500); const scheduler = require("../../src/helpers/Scheduler"); const sentinel = makeSentinel(); let isFinished = false; const doneTimeout = setTimeout(() => done(), 1000); scheduler.on(sentinel, () => { if (isFinished) return; // Prevents "done called twice" errors clearTimeout(doneTimeout); done(new Error("Event was not cancelled")); }); scheduler.schedule(sentinel, { name: "My test event", color: "red" }, new Date(new Date() + 500)); const errorEvent = scheduler.search(event => event.name === "My test event" && event.color === "red"); if (!errorEvent) { isFinished = true; clearTimeout(doneTimeout); done(new Error("Event not found")); return; } scheduler.cancel(errorEvent); }); });
{ "content_hash": "80902a4d688bb8fabe91a319ec1e75eb", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 110, "avg_line_length": 35.30530973451327, "alnum_prop": 0.5622258428374483, "repo_name": "crisbal/Telegram-Bot-Node", "id": "a77d694cc99798130c78eaebe5ce51a894bfa3e3", "size": "7979", "binary": false, "copies": "2", "ref": "refs/heads/es6", "path": "tests/integration/indexTest.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "133546" }, { "name": "Shell", "bytes": "927" } ], "symlink_target": "" }
package io.katharsis.legacy.repository.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import io.katharsis.legacy.queryParams.QueryParams; /** * Method annotated with this annotation will be used to perform find all * operation constrained by a list of identifiers. The method must be defined in * a class annotated with {@link JsonApiResourceRepository}. * <p> * The requirements for the method parameters are as follows: * </p> * <ol> * <li>An {@link Iterable} of resource identifiers</li> * </ol> * <p> * The return value must be an {@link Iterable} of resources of * {@link JsonApiResourceRepository#value()} type. * * @see io.katharsis.legacy.repository.ResourceRepository#findAll(Iterable, * QueryParams) * @deprecated Make use of ResourceRepositoryV2 and related classes */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface JsonApiFindAllWithIds { }
{ "content_hash": "d5e123f53c9491e426f0fca32502bb79", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 33.09090909090909, "alnum_prop": 0.7710622710622711, "repo_name": "katharsis-project/katharsis-framework", "id": "f33b05830b87d012a30ebc0e40e1ef6bd8074554", "size": "1092", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "katharsis-core/src/main/java/io/katharsis/legacy/repository/annotations/JsonApiFindAllWithIds.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "191265" }, { "name": "HTML", "bytes": "8048" }, { "name": "Java", "bytes": "2346234" }, { "name": "JavaScript", "bytes": "2121" }, { "name": "Shell", "bytes": "614" }, { "name": "TypeScript", "bytes": "32723" } ], "symlink_target": "" }
import itsdangerous import mock from nose.tools import * # flake8: noqa import unittest from django.utils import timezone from tests.base import ApiTestCase from osf_tests.factories import ( AuthUserFactory ) from api.base.settings.defaults import API_BASE from framework.auth.oauth_scopes import public_scopes from framework.auth.cas import CasResponse from website import settings from osf.models import ApiOAuth2PersonalToken, Session class TestWelcomeToApi(ApiTestCase): def setUp(self): super(TestWelcomeToApi, self).setUp() self.user = AuthUserFactory() self.url = '/{}'.format(API_BASE) def tearDown(self): self.app.reset() super(TestWelcomeToApi, self).tearDown() def test_returns_200_for_logged_out_user(self): res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal(res.json['meta']['current_user'], None) def test_returns_current_user_info_when_logged_in(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['given_name'], self.user.given_name ) def test_current_user_accepted_tos(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], False ) self.user.accepted_terms_of_service = timezone.now() self.user.save() res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], True ) def test_returns_302_redirect_for_base_url(self): res = self.app.get('/') assert_equal(res.status_code, 302) assert_equal(res.location, '/v2/') def test_cookie_has_admin(self): session = Session(data={'auth_user_id': self.user._id}) session.save() cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(session._id) self.app.set_cookie(settings.COOKIE_NAME, str(cookie)) res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.json['meta']['admin'], True) def test_basic_auth_does_not_have_admin(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_not_in('admin', res.json['meta'].keys()) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') # TODO: Remove when available outside of DEV_MODE @unittest.skipIf( not settings.DEV_MODE, 'DEV_MODE disabled, osf.admin unavailable' ) def test_admin_scoped_token_has_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', scopes='osf.admin' ) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s for s in token.scopes.split(' ')] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_equal(res.json['meta']['admin'], True) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') def test_non_admin_scoped_token_does_not_have_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', scopes=' '.join([key for key in public_scopes if key != 'osf.admin']) ) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s for s in token.scopes.split(' ')] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_not_in('admin', res.json['meta'].keys())
{ "content_hash": "101831291a120101b8af7a3e1acb3be0", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 96, "avg_line_length": 34.95, "alnum_prop": 0.6012671162885755, "repo_name": "icereval/osf.io", "id": "758263b7ef0df56b2fbcb37330ecec8d548d8c54", "size": "4917", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "api_tests/base/test_root.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "108526" }, { "name": "HTML", "bytes": "261937" }, { "name": "JavaScript", "bytes": "1856123" }, { "name": "Mako", "bytes": "691640" }, { "name": "Python", "bytes": "8331919" }, { "name": "VCL", "bytes": "13885" } ], "symlink_target": "" }
package com.opengamma.sesame.irfutureoption; import java.util.Map; import com.opengamma.analytics.financial.interestrate.future.calculator.FuturesPriceNormalSTIRFuturesCalculator; import com.opengamma.analytics.financial.interestrate.future.derivative.FuturesTransaction; import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionSecurity; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PositionDeltaNormalSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PositionGammaNormalSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PositionThetaNormalSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PositionVegaNormalSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PresentValueCurveSensitivityNormalSTIRFuturesCalculator; import com.opengamma.analytics.financial.provider.calculator.normalstirfutures.PresentValueNormalSTIRFuturesCalculator; import com.opengamma.analytics.financial.provider.description.interestrate.NormalSTIRFuturesExpSimpleMoneynessProviderDiscount; import com.opengamma.analytics.financial.provider.description.interestrate.NormalSTIRFuturesProviderInterface; import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity; import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity; import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator; import com.opengamma.financial.analytics.model.fixedincome.BucketedCurveSensitivities; import com.opengamma.sesame.CurveMatrixLabeller; import com.opengamma.sesame.ZeroIRDeltaBucketingUtils; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.MultipleCurrencyAmount; import com.opengamma.util.result.Result; /** * Interest rate future option Normal calculator. */ public class IRFutureOptionNormalCalculator implements IRFutureOptionCalculator { private static final FuturesPriceNormalSTIRFuturesCalculator PRICE_CALC = FuturesPriceNormalSTIRFuturesCalculator.getInstance(); private static final PresentValueNormalSTIRFuturesCalculator PV_CALC = PresentValueNormalSTIRFuturesCalculator.getInstance(); private static final PresentValueCurveSensitivityNormalSTIRFuturesCalculator PV01_CALC = PresentValueCurveSensitivityNormalSTIRFuturesCalculator.getInstance(); private static final ParameterSensitivityParameterCalculator<NormalSTIRFuturesProviderInterface> PSSFC = new ParameterSensitivityParameterCalculator<>(PV01_CALC); private static final PositionDeltaNormalSTIRFutureOptionCalculator DELTA_CALC = PositionDeltaNormalSTIRFutureOptionCalculator.getInstance(); private static final PositionGammaNormalSTIRFutureOptionCalculator GAMMA_CALC = PositionGammaNormalSTIRFutureOptionCalculator.getInstance(); private static final PositionThetaNormalSTIRFutureOptionCalculator THETA_CALC = PositionThetaNormalSTIRFutureOptionCalculator.getInstance(); private static final PositionVegaNormalSTIRFutureOptionCalculator VEGA_CALC = PositionVegaNormalSTIRFutureOptionCalculator.getInstance(); private final FuturesTransaction<InterestRateFutureOptionSecurity> _derivative; private final Map<String, CurveMatrixLabeller> _curveLabellers; private final NormalSTIRFuturesExpSimpleMoneynessProviderDiscount _normalSurface; /** * Constructs a interest rate future options Normal calculator. * @param derivative FuturesTransaction for InterestRateFutureOptionSecurity * @param normalSurface the normal surface provider * @param curveLabellers curve labellers for the multicurve */ public IRFutureOptionNormalCalculator(FuturesTransaction<InterestRateFutureOptionSecurity> derivative, NormalSTIRFuturesExpSimpleMoneynessProviderDiscount normalSurface, Map<String, CurveMatrixLabeller> curveLabellers) { _normalSurface = ArgumentChecker.notNull(normalSurface, "normalSurface"); _curveLabellers = ArgumentChecker.notNull(curveLabellers, "curveLabellers"); _derivative = ArgumentChecker.notNull(derivative, "derivative"); } @Override public Result<MultipleCurrencyAmount> calculatePV() { return Result.success(_derivative.accept(PV_CALC, _normalSurface)); } @Override public Result<MultipleCurrencyMulticurveSensitivity> calculatePV01() { return Result.success(_derivative.accept(PV01_CALC, _normalSurface)); } @Override public Result<Double> calculateModelPrice() { return Result.success(_derivative.accept(PRICE_CALC, _normalSurface)); } @Override public Result<Double> calculateDelta() { return Result.success(_derivative.accept(DELTA_CALC, _normalSurface)); } @Override public Result<Double> calculateGamma() { return Result.success(_derivative.accept(GAMMA_CALC, _normalSurface)); } @Override public Result<Double> calculateVega() { return Result.success(_derivative.accept(VEGA_CALC, _normalSurface)); } @Override public Result<Double> calculateTheta() { return Result.success(_derivative.accept(THETA_CALC, _normalSurface)); } @Override public Result<BucketedCurveSensitivities> calculateBucketedZeroIRDelta() { MultipleCurrencyParameterSensitivity sensitivities = PSSFC.calculateSensitivity(_derivative, _normalSurface); BucketedCurveSensitivities bucketedCurveSensitivities = ZeroIRDeltaBucketingUtils.getBucketedCurveSensitivities(sensitivities, _curveLabellers); return Result.success(bucketedCurveSensitivities); } }
{ "content_hash": "ba4f89d49412a83dcbec381272afdc91", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 135, "avg_line_length": 53.11818181818182, "alnum_prop": 0.8315933595755605, "repo_name": "nssales/OG-Platform", "id": "14169ea32e42f6aaf6b82035ed164625ee0263b1", "size": "5980", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sesame/sesame-function/src/main/java/com/opengamma/sesame/irfutureoption/IRFutureOptionNormalCalculator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4064" }, { "name": "CSS", "bytes": "212432" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "284313" }, { "name": "Java", "bytes": "80833346" }, { "name": "JavaScript", "bytes": "1672518" }, { "name": "PLSQL", "bytes": "105" }, { "name": "PLpgSQL", "bytes": "13175" }, { "name": "Protocol Buffer", "bytes": "53119" }, { "name": "SQLPL", "bytes": "1004" }, { "name": "Shell", "bytes": "10958" } ], "symlink_target": "" }
'use babel'; import observe from '../../src/index'; import {awaitObservation} from '../setup/test-helpers'; describe('ArrayObservation', () => { it('invokes listeners when the array changes', (done) => { let observedArray = ['a', 'b', 'c', 'd', 'e']; awaitObservation(observe(observedArray), (changes) => { expect(changes).to.eql([ {index: 1, removedCount: 1, added: ['f', 'g']}, {index: 4, removedCount: 1, added: ['h', 'i']} ]); done(); }); observedArray.splice(1, 1, 'f', 'g'); observedArray.splice(4, 1, 'h', 'i'); }); describe('.prototype.map(fn)', () => { it('applies a transform function over the values of the array', (done) => { let observedArray = ['a', 'b', 'c', 'd', 'e']; let observation = observe(observedArray).map(value => value.toUpperCase()); expect(observation.getValues()).to.eql(['A', 'B', 'C', 'D', 'E']); awaitObservation(observation, (changes) => { expect(changes).to.eql([ {index: 1, removedCount: 1, added: ['F', 'G']}, {index: 4, removedCount: 1, added: ['H', 'I']} ]); done(); }); observedArray.splice(1, 1, 'f', 'g'); observedArray.splice(4, 1, 'h', 'i'); }); }); });
{ "content_hash": "9ea1dbac2e5be2a83dd51a01c6f31b6e", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 81, "avg_line_length": 30.75609756097561, "alnum_prop": 0.5305313243457573, "repo_name": "nathansobo/data-observer", "id": "c6baedb7eb15efe16211937d027e4dc51da50ac8", "size": "1261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/array-observation-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "27047" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; namespace AzureTokenMaker.App.Model { public sealed class ProfileCollection : IEnumerable<Profile> { private HashSet<Profile> _profiles = new HashSet<Profile>(); public void Add ( Profile target ) { _profiles = new HashSet<Profile>( _profiles ) { target }; } public IEnumerator<Profile> GetEnumerator () { return _profiles.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator(); } } }
{ "content_hash": "164ef98b998a7d55a6e3f59e01a88f7e", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 69, "avg_line_length": 27.761904761904763, "alnum_prop": 0.6243567753001715, "repo_name": "sfgadjo/AzureTokenMaker", "id": "481d32b2ed7ed3a1ac236a6084caf0082d530852", "size": "585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/App/Model/ProfileCollection.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "38087" } ], "symlink_target": "" }
Retrieve a specific organization record. {@inheritdoc} ### get_list Retrieve a collection of organization records. {@inheritdoc} ### create Create a new organization record. The created record is returned in the response. {@inheritdoc} {@request:json_api} Example: ```JSON { "data":{ "type":"organizations", "attributes":{ "is_global":null, "name":"Acme, South", "description":"Example of organization description", "enabled":true }, "relationships":{ "businessUnits":{ "data":[ { "type":"businessunits", "id":"1" }, { "type":"businessunits", "id":"2" } ] }, "users":{ "data":[ { "type":"users", "id":"1" }, { "type":"users", "id":"2" } ] } } } } ``` {@/request} ### update Edit a specific organization record. {@inheritdoc} {@request:json_api} Example: ```JSON { "data":{ "type":"organizations", "id":"2", "attributes":{ "is_global":null, "name":"Acme, South", "description":"Example of organization description", "enabled":true }, "relationships":{ "businessUnits":{ "data":[ { "type":"businessunits", "id":"1" }, { "type":"businessunits", "id":"2" } ] }, "users":{ "data":[ { "type":"users", "id":"1" }, { "type":"users", "id":"2" } ] } } } } ``` {@/request} ## FIELDS ### id #### update {@inheritdoc} **The required field.** ### name #### create {@inheritdoc} **The required field.** #### update {@inheritdoc} **Please note:** *This field is **required** and must remain defined.* ## SUBRESOURCES ### businessUnits #### get_subresource Retrieve the business unit records that belong to a specific organization record. #### get_relationship Retrieve the IDs of the business units that belong to a specific organization record. #### add_relationship Set the business unit records to a specific organization record. {@request:json_api} Example: ```JSON { "data": [ { "type": "businessunits", "id": "1" }, { "type": "businessunits", "id": "2" }, { "type": "businessunits", "id": "3" } ] } ``` {@/request} #### update_relationship Replace the business units that belong to a specific organization record. {@request:json_api} Example: ```JSON { "data": [ { "type": "businessunits", "id": "1" }, { "type": "businessunits", "id": "2" }, { "type": "businessunits", "id": "3" } ] } ``` {@/request} #### delete_relationship Remove the business units that belong to a specific organization record. ### users #### get_subresource Retrieve records of the users who have access to a specific organization. #### get_relationship Retrieve the IDs of the users who have access to a specific organization record. #### add_relationship Set users who have access to a specific organization. {@request:json_api} Example: ```JSON { "data":[ { "type":"users", "id":"1" }, { "type":"users", "id":"2" } ] } ``` {@/request} #### update_relationship Replace users who have access to a specific organization. {@request:json_api} Example: ```JSON { "data":[ { "type":"users", "id":"1" }, { "type":"users", "id":"2" } ] } ``` {@/request} #### delete_relationship Delete users who have access to a specific organization.
{ "content_hash": "b1a8a12489e70284f7690c07e56be0f5", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 85, "avg_line_length": 15.757462686567164, "alnum_prop": 0.4619938432394033, "repo_name": "orocrm/platform", "id": "6266e34aaa3df89ce9d870ec3c0cdad0de8137c4", "size": "4299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Oro/Bundle/OrganizationBundle/Resources/doc/api/organization.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
package org.apereo.cas.support.events.service; import org.apereo.cas.support.events.AbstractCasEvent; /** * This is {@link BaseCasRegisteredServiceEvent}. * * @author Misagh Moayyed * @since 5.2.0 */ public abstract class BaseCasRegisteredServiceEvent extends AbstractCasEvent { private static final long serialVersionUID = 7828374109804253319L; protected BaseCasRegisteredServiceEvent(final Object source) { super(source); } }
{ "content_hash": "9d702b2a20322362298758e1248a3db3", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 78, "avg_line_length": 25.38888888888889, "alnum_prop": 0.7592997811816192, "repo_name": "fogbeam/cas_mirror", "id": "406360c6c81e98607bccc3bed3f1c3dc7da170df", "size": "457", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "api/cas-server-core-api-events/src/main/java/org/apereo/cas/support/events/service/BaseCasRegisteredServiceEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13992" }, { "name": "Dockerfile", "bytes": "75" }, { "name": "Groovy", "bytes": "31399" }, { "name": "HTML", "bytes": "195237" }, { "name": "Java", "bytes": "12509257" }, { "name": "JavaScript", "bytes": "85879" }, { "name": "Python", "bytes": "26699" }, { "name": "Ruby", "bytes": "1323" }, { "name": "Shell", "bytes": "177491" } ], "symlink_target": "" }
#include <sys/un.h> #include "h2o.h" #include "h2o/socketpool.h" struct rp_handler_t { h2o_handler_t super; h2o_url_t upstream; /* host should be NULL-terminated */ h2o_socketpool_t *sockpool; /* non-NULL if config.use_keepalive == 1 */ h2o_proxy_config_vars_t config; }; static int on_req(h2o_handler_t *_self, h2o_req_t *req) { struct rp_handler_t *self = (void *)_self; h2o_req_overrides_t *overrides = h2o_mem_alloc_pool(&req->pool, sizeof(*overrides)); const h2o_url_scheme_t *scheme; h2o_iovec_t *authority; /* setup overrides */ *overrides = (h2o_req_overrides_t){}; if (self->sockpool != NULL) { overrides->socketpool = self->sockpool; } else if (self->config.preserve_host) { overrides->hostport.host = self->upstream.host; overrides->hostport.port = h2o_url_get_port(&self->upstream); } overrides->location_rewrite.match = &self->upstream; overrides->location_rewrite.path_prefix = req->pathconf->path; overrides->client_ctx = h2o_context_get_handler_context(req->conn->ctx, &self->super); /* determine the scheme and authority */ if (self->config.preserve_host) { scheme = req->scheme; authority = &req->authority; } else { scheme = self->upstream.scheme; authority = &self->upstream.authority; } /* request reprocess */ h2o_reprocess_request(req, req->method, scheme, *authority, h2o_build_destination(req, self->upstream.path.base, self->upstream.path.len), overrides, 0); return 0; } static void on_context_init(h2o_handler_t *_self, h2o_context_t *ctx) { struct rp_handler_t *self = (void *)_self; /* use the loop of first context for handling socketpool timeouts */ if (self->sockpool != NULL && self->sockpool->timeout == UINT64_MAX) h2o_socketpool_set_timeout(self->sockpool, ctx->loop, self->config.keepalive_timeout); /* setup a specific client context only if we need to */ if (ctx->globalconf->proxy.io_timeout == self->config.io_timeout && !self->config.websocket.enabled && self->config.ssl_ctx == ctx->globalconf->proxy.ssl_ctx) return; h2o_http1client_ctx_t *client_ctx = h2o_mem_alloc(sizeof(*ctx)); client_ctx->loop = ctx->loop; client_ctx->getaddr_receiver = &ctx->receivers.hostinfo_getaddr; if (ctx->globalconf->proxy.io_timeout == self->config.io_timeout) { client_ctx->io_timeout = &ctx->proxy.io_timeout; } else { client_ctx->io_timeout = h2o_mem_alloc(sizeof(*client_ctx->io_timeout)); h2o_timeout_init(client_ctx->loop, client_ctx->io_timeout, self->config.io_timeout); } if (self->config.websocket.enabled) { /* FIXME avoid creating h2o_timeout_t for every path-level context in case the timeout values are the same */ client_ctx->websocket_timeout = h2o_mem_alloc(sizeof(*client_ctx->websocket_timeout)); h2o_timeout_init(client_ctx->loop, client_ctx->websocket_timeout, self->config.websocket.timeout); } else { client_ctx->websocket_timeout = NULL; } client_ctx->ssl_ctx = self->config.ssl_ctx; h2o_context_set_handler_context(ctx, &self->super, client_ctx); } static void on_context_dispose(h2o_handler_t *_self, h2o_context_t *ctx) { struct rp_handler_t *self = (void *)_self; h2o_http1client_ctx_t *client_ctx = h2o_context_get_handler_context(ctx, &self->super); if (client_ctx == NULL) return; if (client_ctx->io_timeout != &ctx->proxy.io_timeout) { h2o_timeout_dispose(client_ctx->loop, client_ctx->io_timeout); free(client_ctx->io_timeout); } if (client_ctx->websocket_timeout != NULL) { h2o_timeout_dispose(client_ctx->loop, client_ctx->websocket_timeout); free(client_ctx->websocket_timeout); } free(client_ctx); } static void on_handler_dispose(h2o_handler_t *_self) { struct rp_handler_t *self = (void *)_self; if (self->config.ssl_ctx != NULL) SSL_CTX_free(self->config.ssl_ctx); free(self->upstream.host.base); free(self->upstream.path.base); if (self->sockpool != NULL) { h2o_socketpool_dispose(self->sockpool); free(self->sockpool); } } void h2o_proxy_register_reverse_proxy(h2o_pathconf_t *pathconf, h2o_url_t *upstream, h2o_proxy_config_vars_t *config) { struct rp_handler_t *self = (void *)h2o_create_handler(pathconf, sizeof(*self)); self->super.on_context_init = on_context_init; self->super.on_context_dispose = on_context_dispose; self->super.dispose = on_handler_dispose; self->super.on_req = on_req; if (config->keepalive_timeout != 0) { self->sockpool = h2o_mem_alloc(sizeof(*self->sockpool)); struct sockaddr_un sa; const char *to_sa_err; int is_ssl = upstream->scheme == &H2O_URL_SCHEME_HTTPS; if ((to_sa_err = h2o_url_host_to_sun(upstream->host, &sa)) == h2o_url_host_to_sun_err_is_not_unix_socket) { h2o_socketpool_init_by_hostport(self->sockpool, upstream->host, h2o_url_get_port(upstream), is_ssl, SIZE_MAX /* FIXME */); } else { assert(to_sa_err == NULL); h2o_socketpool_init_by_address(self->sockpool, (void *)&sa, sizeof(sa), is_ssl, SIZE_MAX /* FIXME */); } } h2o_url_copy(NULL, &self->upstream, upstream); h2o_strtolower(self->upstream.host.base, self->upstream.host.len); self->config = *config; if (self->config.ssl_ctx != NULL) CRYPTO_add(&self->config.ssl_ctx->references, 1, CRYPTO_LOCK_SSL_CTX); }
{ "content_hash": "77898f6c1ce32b32867ce473cfa808ce", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 119, "avg_line_length": 40.22857142857143, "alnum_prop": 0.6361860795454546, "repo_name": "nkmideb/h2o-server", "id": "7afe8c4eaedb5a8c695d9cdee618acad6e918111", "size": "6772", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/handler/proxy.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1342358" }, { "name": "C++", "bytes": "135227" }, { "name": "CMake", "bytes": "19985" }, { "name": "HTML", "bytes": "6006" }, { "name": "JavaScript", "bytes": "16" }, { "name": "Makefile", "bytes": "1473" }, { "name": "Mathematica", "bytes": "108200" }, { "name": "Objective-C", "bytes": "4662" }, { "name": "PHP", "bytes": "10130" }, { "name": "Perl", "bytes": "272173" }, { "name": "Ruby", "bytes": "4637" }, { "name": "Shell", "bytes": "54059" } ], "symlink_target": "" }
<?php namespace ServerGrove\Bundle\TranslationEditorBundle; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerAware; class MongoStorageManager extends ContainerAware { protected $mongo; public function __construct(ContainerInterface $container) { $this->setContainer($container); } function getMongo() { if (!$this->mongo) { $this->mongo = new \Mongo($this->container->getParameter('translation_editor.mongodb')); } if (!$this->mongo) { throw new \Exception("failed to connect to mongo"); } return $this->mongo; } public function getDB() { return $this->getMongo()->translations; } public function getCollection() { return $this->getDB()->selectCollection($this->container->getParameter('translation_editor.collection')); } }
{ "content_hash": "792398ff098ddcc878b364ae4ddf120f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 115, "avg_line_length": 25.205128205128204, "alnum_prop": 0.6215666327568667, "repo_name": "servergrove/TranslationEditorBundle", "id": "76d5d5b5d72fdf0bc499f2182801f341b966257a", "size": "983", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "MongoStorageManager.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "15414" } ], "symlink_target": "" }
package org.apache.ambari.server.controller.logging; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class LogLevelQueryResponse { private String startIndex; private String pageSize; private String totalCount; private String resultSize; private String queryTimeMS; private List<NameValuePair> nameValueList; @JsonProperty("startIndex") public String getStartIndex() { return startIndex; } @JsonProperty("startIndex") public void setStartIndex(String startIndex) { this.startIndex = startIndex; } @JsonProperty("pageSize") public String getPageSize() { return pageSize; } @JsonProperty("pageSize") public void setPageSize(String pageSize) { this.pageSize = pageSize; } @JsonProperty("totalCount") public String getTotalCount() { return totalCount; } @JsonProperty("totalCount") public void setTotalCount(String totalCount) { this.totalCount = totalCount; } @JsonProperty("resultSize") public String getResultSize() { return resultSize; } @JsonProperty("resultSize") public void setResultSize(String resultSize) { this.resultSize = resultSize; } @JsonProperty("queryTimeMS") public String getQueryTimeMS() { return queryTimeMS; } @JsonProperty("queryTimeMS") public void setQueryTimeMS(String queryTimeMS) { this.queryTimeMS = queryTimeMS; } @JsonProperty("vNameValues") public List<NameValuePair> getNameValueList() { return nameValueList; } @JsonProperty("vNameValues") public void setNameValueList(List<NameValuePair> nameValueList) { this.nameValueList = nameValueList; } }
{ "content_hash": "b5ade694e586bdab5d5f32394d78bf82", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 67, "avg_line_length": 20.8, "alnum_prop": 0.7358597285067874, "repo_name": "alexryndin/ambari", "id": "27e4c9c08132e60e1183853bc74ac9736f11cf99", "size": "2574", "binary": false, "copies": "2", "ref": "refs/heads/branch-adh-1.5", "path": "ambari-server/src/main/java/org/apache/ambari/server/controller/logging/LogLevelQueryResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44884" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "215907" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "786184" }, { "name": "CoffeeScript", "bytes": "8465" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Groovy", "bytes": "89958" }, { "name": "HTML", "bytes": "2514774" }, { "name": "Java", "bytes": "29565801" }, { "name": "JavaScript", "bytes": "19033151" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "316489" }, { "name": "PowerShell", "bytes": "2090340" }, { "name": "Python", "bytes": "17215686" }, { "name": "R", "bytes": "3943" }, { "name": "Roff", "bytes": "13935" }, { "name": "Ruby", "bytes": "33764" }, { "name": "SQLPL", "bytes": "4277" }, { "name": "Shell", "bytes": "886011" }, { "name": "Vim script", "bytes": "5813" }, { "name": "sed", "bytes": "2303" } ], "symlink_target": "" }
package com.sean.im.friend.service; import com.sean.im.commom.entity.UserInfo; public interface UserService { public UserInfo getUserInfoById(long userId); }
{ "content_hash": "ff38bd4044c85987779c0928fb01284c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 46, "avg_line_length": 20.125, "alnum_prop": 0.8012422360248447, "repo_name": "seanzwx/workspace", "id": "7d6751e627296cf942bf6f9b1ee339de18cf6fdc", "size": "161", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "seatalk/im/im-friend/im-friend-api/src/main/java/com/sean/im/friend/service/UserService.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "461" }, { "name": "CSS", "bytes": "47056" }, { "name": "Java", "bytes": "5593911" }, { "name": "JavaScript", "bytes": "1671808" }, { "name": "Shell", "bytes": "2079" } ], "symlink_target": "" }
The instrumented libraries are a collection of Chromium's dependencies built with *SAN enabled. The MSAN libraries are required for an MSAN build to run. The others are optional, and are currently unused. ## Building the instrumented libraries ### Setting up a chroot Building the libraries requires `apt-get source`, so the build must be done from an Ubuntu 16.04 environment. The preferred way is using a chroot. To get started, install `debootstrap` and `schroot`. If you're running a Debian-based distro, run: ```shell sudo apt install debootstrap schroot ``` Create a configuration for a Xenial chroot: ```shell sudo $EDITOR /etc/schroot/chroot.d/xenial_amd64.conf ``` Add the following to the new file, replacing the instances of `thomasanderson` with your own username. ``` [xenial_amd64] description=Ubuntu 16.04 Xenial for amd64 directory=/srv/chroot/xenial_amd64 personality=linux root-users=thomasanderson type=directory users=thomasanderson ``` Bootstrap the chroot: ```shell sudo mkdir -p /srv/chroot/xenial_amd64 sudo debootstrap --variant=buildd --arch=amd64 xenial /srv/chroot/xenial_amd64 http://archive.ubuntu.com/ubuntu/ ``` If your `$HOME` directory is not `/home` (as is the case on gLinux), then route `/home` to the real thing. `schroot` automatically mounts `/home`, which is where I'm assuming you keep your source tree and `depot_tools`. ```shell sudo mount --bind "$HOME" /home ``` Add `sources.list`: ```shell sudo $EDITOR /srv/chroot/xenial_amd64/etc/apt/sources.list ``` Add the following contents to the file: ``` deb http://archive.ubuntu.com/ubuntu/ xenial main restricted universe deb-src http://archive.ubuntu.com/ubuntu/ xenial main restricted universe deb http://archive.ubuntu.com/ubuntu/ xenial-security main restricted universe deb-src http://archive.ubuntu.com/ubuntu/ xenial-security main restricted universe deb http://archive.ubuntu.com/ubuntu/ xenial-updates main restricted universe deb-src http://archive.ubuntu.com/ubuntu/ xenial-updates main restricted universe ``` Enter the chroot and install the necessary packages: ```shell schroot -c xenial_amd64 -u root --directory /home/dev/chromium/src apt update apt install lsb-release sudo python pkg-config libgtk2.0-bin libdrm-dev nih-dbus-tool help2man ``` Install library packages: ```shell third_party/instrumented_libraries/scripts/install-build-deps.sh ``` Change to a non-root user: ```shell exit schroot -c xenial_amd64 -u `whoami` --directory /home/dev/chromium/src ``` Add `depot_tools` to your `PATH`. For example, I have it in `~/dev/depot_tools`, so I use: ```shell export PATH=/home/dev/depot_tools/:$PATH ``` Now we're ready to build the libraries. A clean build takes a little over 8 minutes on a 72-thread machine. ```shell third_party/instrumented_libraries/scripts/build_and_package.py --parallel -j $(nproc) all xenial ``` ## Uploading the libraries This requires write permission on the `chromium-instrumented-libraries` GCS bucket. `dpranke@` can grant access. ```shell # Exit the chroot. exit # Move files into place. mv *.tgz third_party/instrumented_libraries/binaries # Upload. upload_to_google_storage.py -b chromium-instrumented-libraries third_party/instrumented_libraries/binaries/msan*.tgz ``` ## Testing and uploading a CL After uploading, run `gclient sync` and test out a build with `is_msan = true` in your `args.gn`. Try running eg. `chrome` and `unit_tests` to make sure it's working. The binaries should work natively on gLinux. When uploading a CL, make sure to add the following in the description so that the MSAN bot will run on the CQ: ``` CQ_INCLUDE_TRYBOTS=luci.chromium.try:linux_chromium_msan_rel_ng ```
{ "content_hash": "1027171a506573925343ce0fd260eaef", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 116, "avg_line_length": 28.553846153846155, "alnum_prop": 0.7537715517241379, "repo_name": "ric2b/Vivaldi-browser", "id": "695c2e569f72d0aaf39e362aa4204cca18c91edd", "size": "3744", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "chromium/docs/linux/instrumented_libraries.md", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@interface BTFakeHTTP : BTHTTP @property (nonatomic, assign) NSUInteger GETRequestCount; @property (nonatomic, assign) NSUInteger POSTRequestCount; @property (nonatomic, copy, nullable) NSString *lastRequestEndpoint; @property (nonatomic, copy, nullable) NSString *lastRequestMethod; @property (nonatomic, strong, nullable) NSDictionary *lastRequestParameters; @property (nonatomic, copy, nullable) NSString *stubMethod; @property (nonatomic, copy, nullable) NSString *stubEndpoint; @property (nonatomic, strong, nullable) BTJSON *cannedResponse; @property (nonatomic, strong, nullable) BTJSON *cannedConfiguration; @property (nonatomic, assign) NSUInteger cannedStatusCode; @property (nonatomic, strong, nullable) NSError *cannedError; - (nullable instancetype)init; + (nullable instancetype)fakeHTTP; - (void)stubRequest:(nonnull NSString *)httpMethod toEndpoint:(nonnull NSString *)endpoint respondWith:(nonnull id)value statusCode:(NSUInteger)statusCode; - (void)stubRequest:(nonnull NSString *)httpMethod toEndpoint:(nonnull NSString *)endpoint respondWithError:(nonnull NSError *)error; @end
{ "content_hash": "134041cb6ed4275d5e52f31514b9235f", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 155, "avg_line_length": 48, "alnum_prop": 0.8043478260869565, "repo_name": "apascual/braintree_ios", "id": "e8c1c107ea1d5a907557962b1e058daa30977789", "size": "1158", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "UnitTests/Helpers/BTFakeHTTP.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "127908" }, { "name": "Objective-C", "bytes": "1857220" }, { "name": "Ruby", "bytes": "24954" }, { "name": "Shell", "bytes": "1904" }, { "name": "Swift", "bytes": "333014" } ], "symlink_target": "" }
title: DIB training R Markdown half day workshop text: What is robust and reproducible research? How can you make your research more robust and reproducible? You can use RMarkdown! Wait, what’s RMarkdown? RMarkdown is a variant of Markdown that has embedded R code chunks to be used with knitr to make it easy to create reproducible web-based reports. Registration required. location: Simon Fraser University, Burnaby Campus, SSB 8114 link: https://github.com/sciprog-sfu/sciprog-sfu.github.io/issues/70 date: 2016-05-11 startTime: '9:15' endTime: '12:15' ---
{ "content_hash": "b2675703abe0a8c20f291dd0fccb54a1", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 325, "avg_line_length": 69.875, "alnum_prop": 0.7906976744186046, "repo_name": "ttimbers/studyGroup", "id": "47a365a72589c99332cd18867e5c7bbaebe8bbec", "size": "565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_posts/2016/2016-05-11-DIB_training_RMarkdown.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "19460" }, { "name": "HTML", "bytes": "25681" }, { "name": "JavaScript", "bytes": "42758" }, { "name": "PHP", "bytes": "1092" }, { "name": "Python", "bytes": "6446" }, { "name": "R", "bytes": "1797" }, { "name": "Ruby", "bytes": "715" } ], "symlink_target": "" }
package org.apereo.cas.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.notifications.sms.SmsSender; import org.apereo.cas.support.sms.ClickatellSmsSender; import lombok.val; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * This is {@link ClickatellSmsConfiguration}. * * @author Misagh Moayyed * @since 5.1.0 */ @Configuration(value = "clickatellSmsConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public class ClickatellSmsConfiguration { @Autowired private CasConfigurationProperties casProperties; @Bean public SmsSender smsSender() { val clickatell = casProperties.getSmsProvider().getClickatell(); return new ClickatellSmsSender(clickatell.getToken(), clickatell.getServerUrl()); } }
{ "content_hash": "da8acfc3cdeda7bb2892947e6b327de5", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 89, "avg_line_length": 34, "alnum_prop": 0.8007590132827325, "repo_name": "pdrados/cas", "id": "d5f75aa1cb08be14c6f3b55c6e2b23f1cae8449e", "size": "1054", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "support/cas-server-support-sms-clickatell/src/main/java/org/apereo/cas/config/ClickatellSmsConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13992" }, { "name": "Dockerfile", "bytes": "75" }, { "name": "Groovy", "bytes": "31399" }, { "name": "HTML", "bytes": "195237" }, { "name": "Java", "bytes": "12509257" }, { "name": "JavaScript", "bytes": "85879" }, { "name": "Python", "bytes": "26699" }, { "name": "Ruby", "bytes": "1323" }, { "name": "Shell", "bytes": "177491" } ], "symlink_target": "" }
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\PostOrder\Types; /** * * @property \DTS\eBaySDK\PostOrder\Types\RuleDetailInputType $ruleDetail */ class CreateDispositionRuleRequest extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = [ 'ruleDetail' => [ 'type' => 'DTS\eBaySDK\PostOrder\Types\RuleDetailInputType', 'repeatable' => false, 'attribute' => false, 'elementName' => 'ruleDetail' ] ]; /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = []) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } $this->setValues(__CLASS__, $childValues); } }
{ "content_hash": "da86d5f40d6fa9b50f4579e77c8079b7", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 116, "avg_line_length": 28.347826086956523, "alnum_prop": 0.620398773006135, "repo_name": "davidtsadler/ebay-sdk-php", "id": "3185a82a4a729f7ba20a4678a8f0c0fd04369ea1", "size": "1304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PostOrder/Types/CreateDispositionRuleRequest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "10944" }, { "name": "PHP", "bytes": "9958599" } ], "symlink_target": "" }
package org.apache.carbondata.scan.expression.conditional; import java.util.ArrayList; import java.util.List; import org.apache.carbondata.scan.expression.Expression; import org.apache.carbondata.scan.expression.ExpressionResult; import org.apache.carbondata.scan.expression.exception.FilterIllegalMemberException; import org.apache.carbondata.scan.expression.exception.FilterUnsupportedException; import org.apache.carbondata.scan.filter.intf.ExpressionType; import org.apache.carbondata.scan.filter.intf.RowIntf; public class ListExpression extends Expression { private static final long serialVersionUID = 1L; public ListExpression(List<Expression> children) { this.children = children; } @Override public ExpressionResult evaluate(RowIntf value) throws FilterUnsupportedException { List<ExpressionResult> listOfExprRes = new ArrayList<ExpressionResult>(10); for (Expression expr : children) { try { listOfExprRes.add(expr.evaluate(value)); } catch (FilterIllegalMemberException e) { continue; } } return new ExpressionResult(listOfExprRes); } @Override public ExpressionType getFilterExpressionType() { // TODO Auto-generated method stub return ExpressionType.LIST; } @Override public String getString() { // TODO Auto-generated method stub return null; } }
{ "content_hash": "e124496b137015969c3cd55f05892caa", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 95, "avg_line_length": 30.244444444444444, "alnum_prop": 0.766348273328435, "repo_name": "ashokblend/incubator-carbondata", "id": "e57d48a5fcecb79248e34bd50e71203d1e166699", "size": "2169", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/carbondata/scan/expression/conditional/ListExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4159095" }, { "name": "Python", "bytes": "19945" }, { "name": "Scala", "bytes": "2135326" }, { "name": "Shell", "bytes": "6699" }, { "name": "Smalltalk", "bytes": "86" }, { "name": "Thrift", "bytes": "19298" } ], "symlink_target": "" }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDatabase extends Migration { /** * Run the migrations. * * @return void */ public function up() { //CREATES SCHOOLS TABLE Schema::create('schools', function ($table) { // TODO: Add additional school fields? (URL, ...) $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name', 255); $table->string('opening', 5); $table->string('city'); $table->string('lang', 5)->default('nl'); $table->timestamps(); $table->softDeletes(); }); //CREATES USERS TABLE Schema::create('users', function ($table) { // TODO: Make permissions an intermediate column, or remove it alltogether and base permissions solely off groups. // TODO: Permissions are at the moment null for all, are they even needed here? $table->engine = 'InnoDB'; $table->increments('id'); $table->string('email'); $table->string('password'); $table->string('lang', 5)->nullable(); $table->text('permissions')->nullable(); $table->boolean('activated')->default(0); $table->string('activation_code')->nullable(); $table->timestamp('activated_at')->nullable(); $table->timestamp('last_login')->nullable(); $table->string('persist_code')->nullable(); $table->string('reset_password_code')->nullable(); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->timestamps(); //Defines the school a user belongs to $table->integer('school_id')->unsigned()->nullable(); $table->foreign('school_id')->references('id')->on('schools')->onDelete('cascade'); // We'll need to ensure that MySQL uses the InnoDB engine to // support the indexes, other engines aren't affected. $table->engine = 'InnoDB'; $table->unique('email'); $table->index('activation_code'); $table->index('reset_password_code'); }); //CREATES GROUPS TABLE Schema::create('groups', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name'); $table->text('permissions')->nullable(); $table->timestamps(); //Defines the school a user belongs to $table->integer('school_id')->unsigned()->nullable(); $table->foreign('school_id')->references('id')->on('schools')->onDelete('cascade'); // We'll need to ensure that MySQL uses the InnoDB engine to // support the indexes, other engines aren't affected. $table->engine = 'InnoDB'; //$table->unique('name'); }); //CREATE USER GROUPS PIVOT TABLE Schema::create('users_groups', function ($table) { $table->engine = 'InnoDB'; $table->integer('user_id')->unsigned(); $table->integer('group_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); // We'll need to ensure that MySQL uses the InnoDB engine to // support the indexes, other engines aren't affected. $table->primary(['user_id', 'group_id']); }); //CREATE THROTTLE TABLE Schema::create('throttle', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('user_id')->unsigned()->nullable(); $table->string('ip_address')->nullable(); $table->integer('attempts')->default(0); $table->boolean('suspended')->default(0); $table->boolean('banned')->default(0); $table->timestamp('last_attempt_at')->nullable(); $table->timestamp('suspended_at')->nullable(); $table->timestamp('banned_at')->nullable(); // We'll need to ensure that MySQL uses the InnoDB engine to // support the indexes, other engines aren't affected. $table->index('user_id'); }); //CREATES APPOINTMENTS TABLE Schema::create('parent_appointments', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title'); $table->text('description'); $table->string('location'); $table->boolean('allday'); $table->dateTime('start_date'); $table->dateTime('end_date')->nullable(); $table->timestamps(); //Defines the school a user belongs to $table->integer('group_id')->unsigned(); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); }); //CREATES APPOINTMENTS TABLE Schema::create('appointments', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title'); $table->text('description'); $table->string('location'); $table->boolean('allday'); $table->dateTime('start_date'); $table->dateTime('end_date')->nullable(); /* // Repeat_type = day=>'d', week=>'w', month=>'M', year=>'y' $table->string('repeat_type')->nullbale(); // Repeat_freq = every x days, weeks,... $table->integer('repeat_freq')->nullable(); // Nr_repeat = number of times this event will be repeated $table->integer('nr_repeat')->nullable(); */ $table->timestamps(); //Defines the group an appointment belongs to $table->integer('group_id')->unsigned(); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); //Defines the parent event $table->integer('parent_id')->unsigned()->nullable(); $table->foreign('parent_id')->references('id')->on('parent_appointments')->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('appointments'); Schema::dropIfExists('parent_appointments'); Schema::dropIfExists('users_groups'); Schema::dropIfExists('users'); Schema::dropIfExists('groups'); Schema::dropIfExists('schools'); Schema::dropIfExists('throttle'); } }
{ "content_hash": "e2b9a0a7c55999ef68b389afa64e02e9", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 126, "avg_line_length": 39.54597701149425, "alnum_prop": 0.5343700043598314, "repo_name": "oSoc15/educal", "id": "ee36552a2fef50cde8a90fbc57ba21f28eea2ea9", "size": "6881", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/database/migrations/2014_07_01_070425_create_database.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "95539" }, { "name": "JavaScript", "bytes": "28939" }, { "name": "PHP", "bytes": "287365" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2009-2019 the original author or authors. 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. --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.apache.ibatis.submitted.ognlstatic.Mapper"> <select id="getUserStatic" resultType="org.apache.ibatis.submitted.ognlstatic.User"> SELECT * FROM users <trim prefix="WHERE" prefixOverrides="AND |OR "> AND <foreach collection="{ (@org.apache.ibatis.submitted.ognlstatic.StaticClass@value) } " item="enum" open="name IN (" close=") " separator=", ">#{enum}</foreach> AND id = #{id} </trim> </select> <select id="getUserIfNode" resultType="org.apache.ibatis.submitted.ognlstatic.User"> select * from users <if test="value not in {null, ''}"> where name = #{value} </if> </select> </mapper>
{ "content_hash": "d0035e6f38d3536664c3adf9a04b94b0", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 114, "avg_line_length": 36.92857142857143, "alnum_prop": 0.6415215989684074, "repo_name": "langlan/mybatis-3", "id": "fca3f9a079b5e5bb0e8e571ad3c103fdf4a5fe2a", "size": "1551", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/test/java/org/apache/ibatis/submitted/ognlstatic/Mapper.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8370" }, { "name": "Java", "bytes": "3261506" }, { "name": "PLpgSQL", "bytes": "5675" }, { "name": "TSQL", "bytes": "5683" } ], "symlink_target": "" }
package org.jclouds.json.internal; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.in; import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Iterables.tryFind; import static org.jclouds.reflect.Reflection2.constructors; import java.beans.ConstructorProperties; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Map; import javax.inject.Named; import org.jclouds.json.SerializedNames; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.FluentIterable; import com.google.common.collect.Maps; import com.google.common.reflect.Invokable; import com.google.common.reflect.TypeToken; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.SerializedName; /** * NamingStrategies used for JSON deserialization using GSON */ public class NamingStrategies { /** * Specifies how to extract the name from an annotation for use in determining the serialized name. * * @see com.google.gson.annotations.SerializedName * @see ExtractSerializedName */ public abstract static class NameExtractor<A extends Annotation> implements Function<Annotation, String>, Supplier<Predicate<Annotation>> { protected final Class<A> annotationType; protected final Predicate<Annotation> predicate; protected NameExtractor(final Class<A> annotationType) { this.annotationType = checkNotNull(annotationType, "annotationType"); this.predicate = new Predicate<Annotation>() { public boolean apply(Annotation input) { return input.getClass().equals(annotationType); } }; } @SuppressWarnings("unchecked") public Class<Annotation> annotationType() { return (Class<Annotation>) annotationType; } @Override public String apply(Annotation in) { return extractName(annotationType.cast(in)); } protected abstract String extractName(A cast); @Override public Predicate<Annotation> get() { return predicate; } @Override public String toString() { return "nameExtractor(" + annotationType.getSimpleName() + ")"; } @Override public int hashCode() { return annotationType.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; return annotationType.equals(NameExtractor.class.cast(obj).annotationType); } } public static class ExtractSerializedName extends NameExtractor<SerializedName> { public ExtractSerializedName() { super(SerializedName.class); } public String extractName(SerializedName in) { return checkNotNull(in, "input annotation").value(); } } public static class ExtractNamed extends NameExtractor<Named> { public ExtractNamed() { super(Named.class); } @Override public String extractName(Named in) { return checkNotNull(in, "input annotation").value(); } } public abstract static class AnnotationBasedNamingStrategy { protected final Map<Class<? extends Annotation>, ? extends NameExtractor<?>> annotationToNameExtractor; protected final String forToString; public AnnotationBasedNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) { checkNotNull(extractors, "means to extract names by annotations"); this.annotationToNameExtractor = Maps.uniqueIndex(extractors, new Function<NameExtractor<?>, Class<? extends Annotation>>() { @Override public Class<? extends Annotation> apply(NameExtractor<?> input) { return input.annotationType(); } }); this.forToString = Joiner.on(",").join(transform(extractors, new Function<NameExtractor<?>, String>() { @Override public String apply(NameExtractor<?> input) { return input.annotationType().getName(); } })); } @Override public String toString() { return "AnnotationBasedNamingStrategy requiring one of " + forToString; } } /** * Definition of field naming policy for annotation-based field */ public static class AnnotationFieldNamingStrategy extends AnnotationBasedNamingStrategy implements FieldNamingStrategy { public AnnotationFieldNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) { super(extractors); checkArgument(extractors.iterator().hasNext(), "you must supply at least one name extractor, for example: " + ExtractSerializedName.class.getSimpleName()); } @Override public String translateName(Field f) { // Determining if AutoValue is tough, since annotations are SOURCE retention. if (Modifier.isAbstract(f.getDeclaringClass().getSuperclass().getModifiers())) { // AutoValue means abstract. for (Invokable<?, ?> target : constructors(TypeToken.of(f.getDeclaringClass().getSuperclass()))) { SerializedNames names = target.getAnnotation(SerializedNames.class); if (names != null && target.isStatic()) { // == factory method // Fields and constructor params are written by AutoValue in same order as methods are declared. // By contract, SerializedNames factory methods must declare its names in the same order, Field[] fields = f.getDeclaringClass().getDeclaredFields(); checkState(fields.length == names.value().length, "Incorrect number of names on " + names); for (int i = 0; i < fields.length; i++) { if (fields[i].equals(f)) { return names.value()[i]; } } // The input field was not a declared field. Accidentally placed on something not AutoValue? throw new IllegalStateException("Inconsistent state. Ensure type is AutoValue on " + target); } } } for (Annotation annotation : f.getAnnotations()) { if (annotationToNameExtractor.containsKey(annotation.annotationType())) { return annotationToNameExtractor.get(annotation.annotationType()).apply(annotation); } } return null; } } public static class AnnotationOrNameFieldNamingStrategy extends AnnotationFieldNamingStrategy implements FieldNamingStrategy { public AnnotationOrNameFieldNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) { super(extractors); } @Override public String translateName(Field f) { String result = super.translateName(f); return result == null ? f.getName() : result; } } /** * Determines field naming from constructor annotations */ public static final class AnnotationConstructorNamingStrategy extends AnnotationBasedNamingStrategy { private final Predicate<Invokable<?, ?>> hasMarker; private final Collection<? extends Class<? extends Annotation>> markers; public AnnotationConstructorNamingStrategy(Collection<? extends Class<? extends Annotation>> markers, Iterable<? extends NameExtractor<?>> extractors) { super(extractors); this.markers = checkNotNull(markers, "you must supply at least one annotation to mark deserialization constructors"); this.hasMarker = hasAnnotationIn(markers); } private static Predicate<Invokable<?, ?>> hasAnnotationIn( final Collection<? extends Class<? extends Annotation>> markers) { return new Predicate<Invokable<?, ?>>() { public boolean apply(Invokable<?, ?> input) { return FluentIterable.from(Arrays.asList(input.getAnnotations())) .transform(new Function<Annotation, Class<? extends Annotation>>() { public Class<? extends Annotation> apply(Annotation input) { return input.annotationType(); } }).anyMatch(in(markers)); } }; } @VisibleForTesting <T> Invokable<T, T> getDeserializer(TypeToken<T> token) { return tryFind(constructors(token), hasMarker).orNull(); } @VisibleForTesting <T> String translateName(Invokable<T, T> c, int index) { String name = null; if ((markers.contains(ConstructorProperties.class) && c.getAnnotation(ConstructorProperties.class) != null) || (markers.contains(SerializedNames.class) && c.getAnnotation(SerializedNames.class) != null)) { String[] names = c.getAnnotation(SerializedNames.class) != null ? c.getAnnotation(SerializedNames.class).value() : c.getAnnotation(ConstructorProperties.class).value(); checkArgument(names.length == c.getParameters().size(), "Incorrect count of names on annotation of %s", c); if (names != null && names.length > index) { name = names[index]; } } else { for (Annotation annotation : c.getParameters().get(index).getAnnotations()) { if (annotationToNameExtractor.containsKey(annotation.annotationType())) { name = annotationToNameExtractor.get(annotation.annotationType()).apply(annotation); break; } } } return name; } } }
{ "content_hash": "3ceeb72653225ad178e5eeefc291a9b9", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 119, "avg_line_length": 39.041666666666664, "alnum_prop": 0.6457747162122829, "repo_name": "yanzhijun/jclouds-aliyun", "id": "cf3c5aceeab997b425781b08d763bda26d6dcf90", "size": "11108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/jclouds/json/internal/NamingStrategies.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12999" }, { "name": "CSS", "bytes": "10692" }, { "name": "Clojure", "bytes": "99051" }, { "name": "Emacs Lisp", "bytes": "852" }, { "name": "HTML", "bytes": "381689" }, { "name": "Java", "bytes": "19478047" }, { "name": "JavaScript", "bytes": "7110" }, { "name": "Shell", "bytes": "121121" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <serializer> <!-- This file has been generated by the EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends ) @author <yourname> <youremail> --> <class name="Application\Sonata\UserBundle\Document\User" exclusion-policy="all" xml-root-name="_user"> <property xml-attribute-map="true" name="id" type="integer" expose="true" since-version="1.0" groups="sonata_api_read,sonata_api_write,sonata_search" /> </class> </serializer>
{ "content_hash": "c60d5055ae35bed841024e117dc17a14", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 160, "avg_line_length": 38.285714285714285, "alnum_prop": 0.6529850746268657, "repo_name": "leva2020/cineco-admin", "id": "72528ab98126139987e452808c8286be080f81a1", "size": "536", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Application/Sonata/UserBundle/Resources/config/serializer/Document.User.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "15982" }, { "name": "ApacheConf", "bytes": "3297" }, { "name": "CSS", "bytes": "2340773" }, { "name": "CoffeeScript", "bytes": "11578" }, { "name": "Go", "bytes": "7075" }, { "name": "HTML", "bytes": "5281118" }, { "name": "JavaScript", "bytes": "6764732" }, { "name": "LiveScript", "bytes": "6103" }, { "name": "Makefile", "bytes": "343" }, { "name": "PHP", "bytes": "667907" }, { "name": "Python", "bytes": "22125" }, { "name": "Shell", "bytes": "10826" } ], "symlink_target": "" }
#if DEBUG using System; using System.Runtime.CompilerServices; using JetBrains.Annotations; namespace CodeJam.IO { /// <summary> /// The <see cref="IO"/> namespace contains I/O related functionality. /// </summary> [UsedImplicitly] [CompilerGenerated] internal class NamespaceDoc { } } #endif
{ "content_hash": "d47dca88e21e2040ddf1acb13cf04480", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 71, "avg_line_length": 18.8125, "alnum_prop": 0.7342192691029901, "repo_name": "NN---/CodeJam", "id": "a889a5e03d6b26000dc381a8568c9af1395680ce", "size": "303", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CodeJam.Main/IO/NamespaceDoc.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1402" }, { "name": "C#", "bytes": "3895637" }, { "name": "PowerShell", "bytes": "6413" } ], "symlink_target": "" }
package com.google.appengine.tck.datastore; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import org.jboss.arquillian.junit.Arquillian; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import static com.google.appengine.api.datastore.Query.CompositeFilterOperator.and; import static com.google.appengine.api.datastore.Query.FilterOperator.EQUAL; import static com.google.appengine.api.datastore.Query.FilterOperator.GREATER_THAN; import static com.google.appengine.api.datastore.Query.FilterOperator.GREATER_THAN_OR_EQUAL; import static com.google.appengine.api.datastore.Query.FilterOperator.IN; import static com.google.appengine.api.datastore.Query.FilterOperator.NOT_EQUAL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Datastore querying basic tests. * * @author <a href="mailto:marko.luksa@gmail.com">Marko Luksa</a> */ @RunWith(Arquillian.class) public class QueryBasicsTest extends QueryTestBase { private static final String QUERY_BASICS_ENTITY = "QueryBasicsTestEntity"; private Key createQueryBasicsTestParent(String methodName) { Entity parent = createTestEntityWithUniqueMethodNameKey(QUERY_BASICS_ENTITY, methodName); return parent.getKey(); } @Test public void testQueryWithoutAnyConstraints() throws Exception { Key parentKey = createQueryBasicsTestParent("testQueryWithoutAnyConstraints"); Entity person = new Entity("Person", parentKey); service.put(person); Entity address = new Entity("Address", parentKey); service.put(address); PreparedQuery preparedQuery = service.prepare(new Query().setAncestor(parentKey)); assertTrue(preparedQuery.countEntities(withDefaults()) >= 2); List<Entity> results = preparedQuery.asList(withDefaults()); assertTrue(results.containsAll(Arrays.asList(person, address))); } @Test public void queryingByKindOnlyReturnsEntitiesOfRequestedKind() throws Exception { Key parentKey = createQueryBasicsTestParent("queryingByKindOnlyReturnsEntitiesOfRequestedKind"); Entity person = new Entity(KeyFactory.createKey(parentKey, "Person", 1)); service.put(person); Entity address = new Entity(KeyFactory.createKey(parentKey, "Address", 1)); service.put(address); assertSingleResult(person, new Query("Person").setAncestor(parentKey)); } @Test public void singleEntityThrowsTooManyResultsExceptionWhenMoreThanOneResult() throws Exception { String methodName = "singleEntityThrowsTooManyResultsExceptionWhenMoreThanOneResult"; Key parentKey = createQueryBasicsTestParent(methodName); createEntity("Person", parentKey).store(); createEntity("Person", parentKey).store(); PreparedQuery preparedQuery = service.prepare(new Query("Person")); try { preparedQuery.asSingleEntity(); fail("Expected PreparedQuery.TooManyResultsException"); } catch (PreparedQuery.TooManyResultsException e) { // pass } } @Test public void testMultipleFilters() throws Exception { Key parentKey = createQueryBasicsTestParent("testMultipleFilters"); Entity johnDoe = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Doe") .store(); Entity johnBooks = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Books") .store(); Entity janeDoe = createEntity("Person", parentKey) .withProperty("name", "Jane") .withProperty("lastName", "Doe") .store(); Query query = new Query("Person") .setAncestor(parentKey) .setFilter(and( new Query.FilterPredicate("name", EQUAL, "John"), new Query.FilterPredicate("lastName", EQUAL, "Doe"))); assertSingleResult(johnDoe, query); } @Test public void testNullPropertyValue() throws Exception { Key parentKey = createQueryBasicsTestParent("testNullPropertyValue"); createEntity("Entry", parentKey) .withProperty("user", null) .store(); Entity entity = service.prepare(new Query("Entry") .setAncestor(parentKey)).asSingleEntity(); assertNull(entity.getProperty("user")); } @Test public void testFilteringWithNotEqualReturnsOnlyEntitiesContainingTheProperty() throws Exception { String methodName = "testFilteringWithNotEqualReturnsOnlyEntitiesContainingTheProperty"; Key parentKey = createQueryBasicsTestParent(methodName); Entity e1 = createEntity("Entry", parentKey) .withProperty("foo", "aaa") .store(); createEntity("Entry", parentKey) .withProperty("bar", "aaa") .store(); Query query = new Query("Entry") .setAncestor(parentKey) .setFilter(new Query.FilterPredicate("foo", NOT_EQUAL, "bbb")); assertEquals(Collections.singletonList(e1), service.prepare(query).asList(withDefaults())); } @Test public void testFilterEqualNull() throws Exception { Key parentKey = createQueryBasicsTestParent("testFilterEqualNull"); createEntity("Entry", parentKey) .withProperty("user", null) .store(); Query query = new Query("Entry") .setAncestor(parentKey) .setFilter(new Query.FilterPredicate("user", EQUAL, null)); assertNotNull(service.prepare(query).asSingleEntity()); } @Test public void testFilterNotEqualNull() throws Exception { Key parentKey = createQueryBasicsTestParent("testFilterNotEqualNull"); createEntity("Entry", parentKey) .withProperty("user", "joe") .store(); Query query = new Query("Entry") .setAncestor(parentKey) .setFilter(new Query.FilterPredicate("user", NOT_EQUAL, null)); assertNotNull(service.prepare(query).asSingleEntity()); } @Test public void testFilterInNull() throws Exception { Key parentKey = createQueryBasicsTestParent("testFilterInNull"); createEntity("Entry", parentKey) .withProperty("user", null) .store(); Query query = new Query("Entry") .setAncestor(parentKey) .setFilter(new Query.FilterPredicate("user", IN, Arrays.asList(null, "foo"))); assertNotNull(service.prepare(query).asSingleEntity()); } @Test public void testFilterOnMultiValuedProperty() throws Exception { Key parentKey = createQueryBasicsTestParent("testFilterOnMultiValuedProperty"); createEntity("Entry", parentKey) .withProperty("letters", Arrays.asList("a", "b", "c")) .store(); Query query = new Query("Entry") .setAncestor(parentKey) .setFilter(new Query.FilterPredicate("letters", EQUAL, "a")); assertNotNull(service.prepare(query).asSingleEntity()); } @Test public void testFilteringByKind() throws Exception { Key parentKey = createQueryBasicsTestParent("testFilteringByKind"); Entity foo = createEntity("foo", parentKey).store(); Entity bar = createEntity("bar", parentKey).store(); PreparedQuery preparedQuery = service.prepare(new Query("foo").setAncestor(parentKey)); List<Entity> results = preparedQuery.asList(withDefaults()); assertEquals(1, results.size()); assertEquals(foo, results.get(0)); } @Test public void testFilteringByAncestor() throws Exception { Key rootKey = KeyFactory.createKey("foo", "root"); Entity root = createEntity(rootKey).store(); Key barKey = KeyFactory.createKey(rootKey, "bar", 10); Entity bar = createEntity(barKey).store(); Key fooKey = KeyFactory.createKey(barKey, "foo", 20); Entity foo = createEntity(fooKey).store(); List<Entity> list = service.prepare(new Query("foo", rootKey)).asList(withDefaults()); assertEquals(asSet(Arrays.asList(root, foo)), asSet(list)); list = service.prepare(new Query(rootKey)).asList(withDefaults()); assertEquals(asSet(Arrays.asList(root, foo, bar)), asSet(list)); list = service.prepare(new Query("foo", barKey)).asList(withDefaults()); assertEquals(asSet(Arrays.asList(foo)), asSet(list)); } @Test public void testQueryWithInequalityFiltersOnMultiplePropertiesThrowsIllegalArgumentException() throws Exception { Query query = createQuery() .setFilter(and( new Query.FilterPredicate("weight", GREATER_THAN, 3), new Query.FilterPredicate("size", GREATER_THAN, 5))); assertIAEWhenAccessingResult(service.prepare(query)); } @Test public void testQueryWithInequalityFilterAndFirstSortOnDifferentPropertyThrowsIllegalArgumentException() throws Exception { Query query = createQuery() .setFilter(new Query.FilterPredicate("foo", GREATER_THAN, 3)) .addSort("bar"); assertIAEWhenAccessingResult(service.prepare(query)); } @Test public void testQueryWithInequalityFilterAndFirstSortOnSamePropertyIsAllowed() throws Exception { Query query = createQuery() .setFilter(new Query.FilterPredicate("foo", GREATER_THAN, 3)) .addSort("foo") .addSort("bar"); service.prepare(query).asList(withDefaults()); } @Ignore("According to the docs, ordering of query results is undefined when no sort order is specified. They are " + "currently ordered according to the index, but this may change in the future and so it shouldn't be tested by the TCK.") @Test public void testDefaultSortOrderIsDefinedByIndexDefinition() throws Exception { Key parentKey = createQueryBasicsTestParent("testDefaultSortOrderIsDefinedByIndexDefinition"); Entity aaa = createEntity("Product", parentKey) .withProperty("name", "aaa") .withProperty("price", 10) .store(); Entity ccc = createEntity("Product", parentKey) .withProperty("name", "ccc") .withProperty("price", 10) .store(); Entity bbb = createEntity("Product", parentKey) .withProperty("name", "bbb") .withProperty("price", 10) .store(); Query query = new Query("Product") .setAncestor(parentKey) .setFilter(and( new Query.FilterPredicate("name", GREATER_THAN_OR_EQUAL, "aaa"), new Query.FilterPredicate("price", EQUAL, 10) )); assertEquals(Arrays.asList(aaa, bbb, ccc), service.prepare(query).asList(withDefaults())); } @SuppressWarnings("deprecation") @Test public void testDeprecatedFiltersAreSupported() throws Exception { Key parentKey = createQueryBasicsTestParent("testDeprecatedFiltersAreSupported"); Entity johnDoe = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Doe") .store(); Entity johnBooks = createEntity("Person", parentKey) .withProperty("name", "John") .withProperty("lastName", "Books") .store(); Entity janeDoe = createEntity("Person", parentKey) .withProperty("name", "Jane") .withProperty("lastName", "Doe") .store(); Query query = new Query("Person") .setAncestor(parentKey) .addFilter("name", EQUAL, "John") .addFilter("lastName", EQUAL, "Doe"); assertSingleResult(johnDoe, query); } private Set<Entity> asSet(List<Entity> collection) { return new HashSet<>(collection); } }
{ "content_hash": "ff216fc3c09515d187cf6967f2338e39", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 128, "avg_line_length": 38.6625386996904, "alnum_prop": 0.6616752081998719, "repo_name": "GoogleCloudPlatform/appengine-tck", "id": "b2ef7bfc125427248e0af1bed70a6539e4a33f1e", "size": "13098", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/appengine-tck-datastore/src/test/java/com/google/appengine/tck/datastore/QueryBasicsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "217" }, { "name": "HTML", "bytes": "14652" }, { "name": "Java", "bytes": "1410720" }, { "name": "JavaScript", "bytes": "14674" }, { "name": "Shell", "bytes": "5123" } ], "symlink_target": "" }
namespace Dapper.FastCrud.EntityDescriptors { using System; using System.Runtime.CompilerServices; using System.Threading; using Dapper.FastCrud.Mappings; using Dapper.FastCrud.SqlBuilders; using Dapper.FastCrud.SqlStatements; /// <summary> /// Typed entity descriptor, capable of producing statement builders associated with default entity mappings. /// </summary> internal class EntityDescriptor<TEntity>:EntityDescriptor { // entity mappings should have a very long timespan if used correctly, however we can't make that assumption // hence we'll have to keep them for the duration of their lifespan and attach precomputed sql statements private readonly ConditionalWeakTable<EntityMapping, ISqlStatements> _registeredEntityMappings; private readonly Lazy<ISqlStatements> _defaultEntityMappingSqlStatements; /// <summary> /// Default constructor /// </summary> public EntityDescriptor() :base(typeof(TEntity)) { this.DefaultEntityMapping = new AutoGeneratedEntityMapping<TEntity>(); _defaultEntityMappingSqlStatements = new Lazy<ISqlStatements>(()=>this.ConstructSqlStatements(this.DefaultEntityMapping), LazyThreadSafetyMode.PublicationOnly); _registeredEntityMappings = new ConditionalWeakTable<EntityMapping, ISqlStatements>(); } /// <summary> /// Returns the sql statements for an entity mapping, or the default one if the argument is null. /// </summary> public ISqlStatements GetSqlStatements(EntityMapping entityMapping = null) { ISqlStatements sqlStatements; // default entity mappings are the ones that are mostly used, treat them differently if (entityMapping == null) { sqlStatements = _defaultEntityMappingSqlStatements.Value; } else { sqlStatements = _registeredEntityMappings.GetValue(entityMapping, mapping => this.ConstructSqlStatements(mapping)); } return sqlStatements; } private ISqlStatements ConstructSqlStatements(EntityMapping entityMapping) { entityMapping.FreezeMapping(); ISqlStatements sqlStatements; GenericStatementSqlBuilder statementSqlBuilder; switch (entityMapping.Dialect) { case SqlDialect.MsSql: statementSqlBuilder = new MsSqlBuilder(this, entityMapping); break; case SqlDialect.MySql: statementSqlBuilder = new MySqlBuilder(this, entityMapping); break; case SqlDialect.PostgreSql: statementSqlBuilder = new PostgreSqlBuilder(this, entityMapping); break; case SqlDialect.SqLite: statementSqlBuilder = new SqLiteBuilder(this, entityMapping); break; default: throw new NotSupportedException($"Dialect {entityMapping.Dialect} is not supported"); } sqlStatements = new GenericSqlStatements<TEntity>(statementSqlBuilder); return sqlStatements; } } }
{ "content_hash": "b296ff03ad62afe05bda6582c6c5e89a", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 172, "avg_line_length": 42.25316455696203, "alnum_prop": 0.6360095865787897, "repo_name": "tenbaset/Dapper.FastCRUD", "id": "f152c90f726a02acad4e9c777c9e76d396eea6c1", "size": "3340", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Dapper.FastCrud/EntityDescriptors/TypedEntityDescriptor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "403754" }, { "name": "Gherkin", "bytes": "40063" }, { "name": "PowerShell", "bytes": "1183" } ], "symlink_target": "" }
<?php /** * Object wrapper for interacting with stdin * * @package Cake.Console */ class ConsoleInput { /** * Input value. * * @var resource */ protected $_input; /** * Constructor * * @param string $handle The location of the stream to use as input. */ public function __construct($handle = 'php://stdin') { $this->_input = fopen($handle, 'r'); } /** * Read a value from the stream * * @return mixed The value of the stream */ public function read() { return fgets($this->_input); } }
{ "content_hash": "48346c25fee5575a51069e4e17d71757", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 68, "avg_line_length": 15.727272727272727, "alnum_prop": 0.6165703275529865, "repo_name": "calmsu/arcs", "id": "f6d52a9b0173008bf340a6dd80354b2b7732950a", "size": "1125", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "lib/Cake/Console/ConsoleInput.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CoffeeScript", "bytes": "111677" }, { "name": "JavaScript", "bytes": "14109" }, { "name": "PHP", "bytes": "7278759" }, { "name": "Ruby", "bytes": "461" }, { "name": "Shell", "bytes": "5691" } ], "symlink_target": "" }
#ifndef LIBXMP_MIXER_H #define LIBXMP_MIXER_H #define SMIX_C4NOTE 6864 #define SMIX_NUMVOC 128 /* default number of softmixer voices */ #define SMIX_SHIFT 16 #define SMIX_MASK 0xffff #define FILTER_SHIFT 16 /* Anticlick ramps */ #define SLOW_ATTACK_SHIFT 4 #define SLOW_ATTACK (1 << SLOW_ATTACK_SHIFT) #define SLOW_RELEASE 16 struct mixer_voice { int chn; /* channel number */ int root; /* */ unsigned int age; /* */ int note; /* */ int pan; /* */ int vol; /* */ int period; /* current period */ int pos; /* position in sample */ int pos0; /* position in sample before mixing */ int frac; /* interpolation */ int fidx; /* function index */ int ins; /* instrument number */ int smp; /* sample number */ int end; /* loop end */ int act; /* nna info & status of voice */ int sleft; /* last left sample output, in 32bit */ int sright; /* last right sample output, in 32bit */ void *sptr; /* sample pointer */ struct { int r1; /* filter variables */ int r2; int l1; int l2; int a0; int b0; int b1; int cutoff; int resonance; } filter; int attack; /* ramp up anticlick */ int sample_loop; /* set if sample has looped */ }; int mixer_on (struct context_data *, int, int, int); void mixer_off (struct context_data *); void mixer_setvol (struct context_data *, int, int); void mixer_seteffect (struct context_data *, int, int, int); void mixer_setpan (struct context_data *, int, int); int mixer_numvoices (struct context_data *, int); void mixer_softmixer (struct context_data *); void mixer_reset (struct context_data *); void mixer_setpatch (struct context_data *, int, int); void mixer_voicepos (struct context_data *, int, int, int); int mixer_getvoicepos (struct context_data *, int); void mixer_setnote (struct context_data *, int, int); void mixer_setbend (struct context_data *, int, int); #endif /* LIBXMP_MIXER_H */
{ "content_hash": "b28828dd80246be92fc0cb8941b08fc9", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 64, "avg_line_length": 28.058823529411764, "alnum_prop": 0.659853249475891, "repo_name": "PopCap/GameIdea", "id": "20dc991823ad77d97a03baf504ff943222cc808a", "size": "1908", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engine/Source/ThirdParty/coremod/coremod-4.2.6/src/mixer.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "238055" }, { "name": "Assembly", "bytes": "184134" }, { "name": "Batchfile", "bytes": "116983" }, { "name": "C", "bytes": "84264210" }, { "name": "C#", "bytes": "9612596" }, { "name": "C++", "bytes": "242290999" }, { "name": "CMake", "bytes": "548754" }, { "name": "CSS", "bytes": "134910" }, { "name": "GLSL", "bytes": "96780" }, { "name": "HLSL", "bytes": "124014" }, { "name": "HTML", "bytes": "4097051" }, { "name": "Java", "bytes": "757767" }, { "name": "JavaScript", "bytes": "2742822" }, { "name": "Makefile", "bytes": "1976144" }, { "name": "Objective-C", "bytes": "75778979" }, { "name": "Objective-C++", "bytes": "312592" }, { "name": "PAWN", "bytes": "2029" }, { "name": "PHP", "bytes": "10309" }, { "name": "PLSQL", "bytes": "130426" }, { "name": "Pascal", "bytes": "23662" }, { "name": "Perl", "bytes": "218656" }, { "name": "Python", "bytes": "21593012" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "2889614" }, { "name": "Tcl", "bytes": "1452" } ], "symlink_target": "" }
Controllers =========== After creating the resource classes and specifying how resource data should be formatted, the next thing to do is to create controller actions to expose the resources to end users through RESTful APIs. Yii provides two base controller classes to simplify your work of creating RESTful actions: [[yii\rest\Controller]] and [[yii\rest\ActiveController]]. The difference between these two controllers is that the latter provides a default set of actions that are specifically designed to deal with resources represented as [Active Record](db-active-record.md). So if you are using [Active Record](db-active-record.md) and are comfortable with the provided built-in actions, you may consider extending your controller classes from [[yii\rest\ActiveController]], which will allow you to create powerful RESTful APIs with minimal code. Both [[yii\rest\Controller]] and [[yii\rest\ActiveController]] provide the following features, some of which will be described in detail in the next few sections: * HTTP method validation; * [Content negotiation and Data formatting](rest-response-formatting.md); * [Authentication](rest-authentication.md); * [Rate limiting](rest-rate-limiting.md). [[yii\rest\ActiveController]] in addition provides the following features: * A set of commonly needed actions: `index`, `view`, `create`, `update`, `delete`, `options`; * User authorization in regarding to the requested action and resource. ## Creating Controller Classes <a name="creating-controller"></a> When creating a new controller class, a convention in naming the controller class is to use the type name of the resource and use singular form. For example, to serve user information, the controller may be named as `UserController`. Creating a new action is similar to creating an action for a Web application. The only difference is that instead of rendering the result using a view by calling the `render()` method, for RESTful actions you directly return the data. The [[yii\rest\Controller::serializer|serializer]] and the [[yii\web\Response|response object]] will handle the conversion from the original data to the requested format. For example, ```php public function actionView($id) { return User::findOne($id); } ``` ## Filters <a name="filters"></a> Most RESTful API features provided by [[yii\rest\Controller]] are implemented in terms of [filters](structure-filters.md). In particular, the following filters will be executed in the order they are listed: * [[yii\filters\ContentNegotiator|contentNegotiator]]: supports content negotiation, to be explained in the [Response Formatting](rest-response-formatting.md) section; * [[yii\filters\VerbFilter|verbFilter]]: supports HTTP method validation; * [[yii\filters\AuthMethod|authenticator]]: supports user authentication, to be explained in the [Authentication](rest-authentication.md) section; * [[yii\filters\RateLimiter|rateLimiter]]: supports rate limiting, to be explained in the [Rate Limiting](rest-rate-limiting.md) section. These named filters are declared in the [[yii\rest\Controller::behaviors()|behaviors()]] method. You may override this method to configure individual filters, disable some of them, or add your own filters. For example, if you only want to use HTTP basic authentication, you may write the following code: ```php use yii\filters\auth\HttpBasicAuth; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => HttpBasicAuth::className(), ]; return $behaviors; } ``` ## Extending `ActiveController` <a name="extending-active-controller"></a> If your controller class extends from [[yii\rest\ActiveController]], you should set its [[yii\rest\ActiveController::modelClass||modelClass]] property to be the name of the resource class that you plan to serve through this controller. The class must extend from [[yii\db\ActiveRecord]]. ### Customizing Actions <a name="customizing-actions"></a> By default, [[yii\rest\ActiveController]] provides the following actions: * [[yii\rest\IndexAction|index]]: list resources page by page; * [[yii\rest\ViewAction|view]]: return the details of a specified resource; * [[yii\rest\CreateAction|create]]: create a new resource; * [[yii\rest\UpdateAction|update]]: update an existing resource; * [[yii\rest\DeleteAction|delete]]: delete the specified resource; * [[yii\rest\OptionsAction|options]]: return the supported HTTP methods. All these actions are declared through the [[yii\rest\ActiveController::actions()|actions()]] method. You may configure these actions or disable some of them by overriding the `actions()` method, like shown the following, ```php public function actions() { $actions = parent::actions(); // disable the "delete" and "create" actions unset($actions['delete'], $actions['create']); // customize the data provider preparation with the "prepareDataProvider()" method $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider']; return $actions; } public function prepareDataProvider() { // prepare and return a data provider for the "index" action } ``` Please refer to the class references for individual action classes to learn what configuration options are available. ### Performing Access Check <a name="performing-access-check"></a> When exposing resources through RESTful APIs, you often need to check if the current user has the permission to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done by overriding the [[yii\rest\ActiveController::checkAccess()|checkAccess()]] method like the following, ```php /** * Checks the privilege of the current user. * * This method should be overridden to check whether the current user has the privilege * to run the specified action against the specified data model. * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. * * @param string $action the ID of the action to be executed * @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed. * @param array $params additional parameters * @throws ForbiddenHttpException if the user does not have access */ public function checkAccess($action, $model = null, $params = []) { // check if the user can access $action and $model // throw ForbiddenHttpException if access should be denied } ``` The `checkAccess()` method will be called by the default actions of [[yii\rest\ActiveController]]. If you create new actions and also want to perform access check, you should call this method explicitly in the new actions. > Tip: You may implement `checkAccess()` by using the [Role-Based Access Control (RBAC) component](security-authorization.md).
{ "content_hash": "743d463df1353df45a4d0295f50aa38a", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 126, "avg_line_length": 44.828947368421055, "alnum_prop": 0.7596125623715879, "repo_name": "peterkokot/yii2", "id": "ce0289a6feeebc00abc501502e69d054c763c3d6", "size": "6814", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "docs/guide/rest-controllers.md", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/** * @module routes.activities.engagement */ /** * @property entryPoint * @type String * @default api * @static * @final */ var entryPoint = 'api'; /** * @class Engagement * @constructor */ exports.Engagement = function(api) { this.api = api; this.api.epoint = entryPoint; } /** * List activities for specific engagement * * @method getSpecific * @param engagementRef {Integer} Engagement reference * @param callback {String} Callback function * @async */ exports.Engagement.prototype.getSpecific = function(engagementRef, callback) { debug('running request'); this.api.client.get('tasks/v2/tasks/contracts/' + engagementRef, {}, callback); } /** * Assign engagements to the list of activities * * @method assign * @param company {String} Company ID * @param team {String} Team ID * @param engagementRef {Integer} Engagement reference * @param params {Hash} Parameters * @param callback {String} Callback function * @async */ exports.Engagement.prototype.assign = function(company, team, engagementRef, params, callback) { debug('running request'); this.api.client.put('otask/v1/tasks/companies/' + company + '/teams/' + team + '/engagements/' + engagementRef + '/tasks', params, callback); } /** * Assign to specific engagement the list of activities * * @method assign * @param engagementRef {Integer} Engagement reference * @param params {Hash} Parameters * @param callback {String} Callback function * @async */ exports.Engagement.prototype.assignToEngagement = function(engagementRef, params, callback) { debug('running request'); this.api.client.put('tasks/v2/tasks/contracts/' + engagementRef, params, callback); }
{ "content_hash": "ec1f738bb0d718c5b1092e09cff38b34", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 143, "avg_line_length": 25.484848484848484, "alnum_prop": 0.7080856123662307, "repo_name": "upwork/node-upwork", "id": "e5731bc3b233e85b2c207b4d5b2e313882b17442", "size": "2000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/routers/activities/engagement.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "72310" } ], "symlink_target": "" }
using UnityEngine; using System; using System.Collections; public class VHSpeechRecognizer : MonoBehaviour { public GUIText m_SpeechRecognition; public GUIText m_TTS; public DebugConsole m_Console; //public override void VHStart() void Start() { return; #if false // TEST 2 AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); // jni.FindClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = jc.GetStatic<AndroidJavaObject>("currentActivity"); //currentActivity.Call("Launch"); // jni.GetStaticFieldID(classID, "Ljava/lang/Object;"); // jni.GetStaticObjectField(classID, fieldID); // jni.FindClass("java.lang.Object"); //Debug.Log(currentActivity.Call<AndroidJavaObject>("getCacheDir").Call<string>("getCanonicalPath")); // jni.GetMethodID(classID, "getCacheDir", "()Ljava/io/File;"); // or any baseclass thereof! // jni.CallObjectMethod(objectID, methodID); // jni.FindClass("java.io.File"); // jni.GetMethodID(classID, "getCanonicalPath", "()Ljava/lang/String;"); // jni.CallObjectMethod(objectID, methodID); // jni.GetStringUTFChars(javaString); AndroidJavaClass recognizerFactory = new AndroidJavaClass("android.speech.SpeechRecognizer"); if (recognizerFactory == null) { Debug.LogError("recognizerFactory is null"); } AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", "android.speech.action.RECOGNIZE_SPEECH"); if (intent == null) { Debug.LogError("intent is null"); } else { //string ACTION_RECOGNIZE_SPEECH = intent.GetStatic<string>("ACTION_RECOGNIZE_SPEECH"); //intent = new AndroidJavaObject("android.content.Intent", ACTION_RECOGNIZE_SPEECH); //string ACTION_RECOGNIZE_SPEECH = intent.Get<string>("ACTION_RECOGNIZE_SPEECH"); //string ACTION_RECOGNIZE_SPEECH = intent.Get<string>("ACTION_RECOGNIZE_SPEECH"); intent.Call<AndroidJavaObject>("putExtra", "android.speech.extra.LANGUAGE_MODEL", "free_form"); intent.Call<AndroidJavaObject>("putExtra", "android.speech.extra.PROMPT", "Please speak slowly and enunciate clearly."); //startActivityForResult(intent, VOICE_RECOGNITION_REQUEST); } currentActivity.Call("startActivityForResult", intent, 65793); return; AndroidJavaObject listener = new AndroidJavaObject("android.speech.RecognitionListener"); if (listener == null) { Debug.LogError("listener is null "); } AndroidJavaObject recognizer = recognizerFactory.CallStatic<AndroidJavaObject>("createSpeechRecognizer", currentActivity.Call<AndroidJavaObject>("getApplicationContext")); if (recognizer == null) { Debug.LogError("Factory created recognizer is null "); } else { recognizer.Call("setRecognitionListener", listener); recognizer.Call("startListening", intent); } Debug.Log("Finished function"); #endif } //public override void VHOnGUI() void OnGUI() { #if false if (GUI.Button(new Rect(100, 100, 130, 40), "Speech Recognition")) { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); jo.Call("LaunchSpeechRecognition"); } else if (GUI.Button(new Rect(100, 175, 130, 40), "Text To Speech") && !string.IsNullOrEmpty(m_Console.CommandString)) { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); jo.Call("UseTTS", m_Console.CommandString); OnTTS(m_Console.CommandString); } #endif } public void OnSpeechRecognition(string message) { m_SpeechRecognition.text = message; } public void OnTTS(string message) { m_TTS.text = message; } /*public void speakToMe(View view) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please speak slowly and enunciate clearly."); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST && resultCode == RESULT_OK) { ArrayList matches = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); TextView textView = (TextView) findViewById(R.id.speech_io_text); String firstMatch = matches.get(0); textView.setText(firstMatch); } }*/ // TEST 1 //The comments is what you would need to do if you use raw JNI //AndroidJavaObject jo = new AndroidJavaObject("java.lang.String", "some_string"); // jni.FindClass("java.lang.String"); // jni.GetMethodID(classID, "<init>", "(Ljava/lang/String;)V"); // jni.NewStringUTF("some_string"); // jni.NewObject(classID, methodID, javaString); //int hash = jo.Call<int>("hashCode"); //Debug.Log("String hash: " + hash); // jni.GetMethodID(classID, "hashCode", "()I"); // jni.CallIntMethod(objectID, methodID); }
{ "content_hash": "5e01cafd387a60955a718d6f53b18502", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 132, "avg_line_length": 39.95238095238095, "alnum_prop": 0.6255746637153073, "repo_name": "USC-ICT/gift-integration-demo", "id": "9a55a92ec580397097d00665b3c7e20d8f22d2fd", "size": "5873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GiftDemo/Assets/vhAssets/vhutils/VHSpeechRecognizer.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "4330" }, { "name": "C#", "bytes": "2656559" }, { "name": "GLSL", "bytes": "33373" }, { "name": "HLSL", "bytes": "10511" }, { "name": "HTML", "bytes": "1910" }, { "name": "Java", "bytes": "7146" }, { "name": "Makefile", "bytes": "530" }, { "name": "Python", "bytes": "133786" }, { "name": "ShaderLab", "bytes": "423535" }, { "name": "Shell", "bytes": "21847" }, { "name": "XSLT", "bytes": "989722" } ], "symlink_target": "" }
from baremetal_network_provisioning.common import constants as hp_const from baremetal_network_provisioning.ml2 import (hp_network_provisioning_driver as np_drv) from baremetal_network_provisioning.ml2 import mechanism_hp as hp_mech import contextlib import mock from oslo_config import cfg from neutron.extensions import portbindings from neutron.tests import base CONF = cfg.CONF class TestHPMechDriver(base.BaseTestCase): """Test class for mech driver.""" def setUp(self): super(TestHPMechDriver, self).setUp() self.driver = hp_mech.HPMechanismDriver() self.driver.initialize() self.driver._load_drivers() def _get_port_context(self, tenant_id, net_id, vm_id, network): """Get port context.""" port = {'device_id': vm_id, 'device_owner': 'compute', 'binding:host_id': 'ironic', 'name': 'test-port', 'tenant_id': tenant_id, 'id': 123456, 'network_id': net_id, 'binding:profile': {'local_link_information': [{'switch_id': '11:22:33:44:55:66', 'port_id': 'Tengig0/1'}]}, 'binding:vnic_type': 'baremetal', 'admin_state_up': True, } return FakePortContext(port, port, network) def _get_network_context(self, tenant_id, net_id, seg_id, shared): """Get network context.""" network = {'id': net_id, 'tenant_id': tenant_id, 'name': 'test-net', 'shared': shared} network_segments = [{'segmentation_id': seg_id}] return FakeNetworkContext(network, network_segments, network) def _get_port_dict(self): """Get port dict.""" port_dict = {'port': {'segmentation_id': 1001, 'host_id': 'ironic', 'access_type': hp_const.ACCESS, 'switchports': [{'port_id': 'Tengig0/1', 'switch_id': '11:22:33:44:55:66'}], 'id': 123456, 'network_id': "net1-id", 'is_lag': False}} return port_dict def test_create_port_precommit(self): """Test create_port_precommit method.""" fake_port_dict = mock.Mock() fake_context = mock.Mock() with contextlib.nested( mock.patch.object(hp_mech.HPMechanismDriver, '_is_port_of_interest', return_value=True), mock.patch.object(hp_mech.HPMechanismDriver, '_construct_port', return_value=fake_port_dict), mock.patch.object(np_drv.HPNetworkProvisioningDriver, 'create_port', return_value=None) ) as (is_port, cons_port, c_port): self.driver.create_port_precommit(fake_context) is_port.assert_called_with(fake_context) cons_port.assert_called_with(fake_context) c_port.assert_called_with(fake_port_dict) def test_delete_port_precommit(self): """Test delete_port_precommit method.""" tenant_id = 'ten-1' network_id = 'net1-id' segmentation_id = 1001 vm_id = 'vm1' network_context = self._get_network_context(tenant_id, network_id, segmentation_id, False) port_context = self._get_port_context(tenant_id, network_id, vm_id, network_context) port_id = port_context.current['id'] with contextlib.nested( mock.patch.object(hp_mech.HPMechanismDriver, '_get_vnic_type', return_value=portbindings.VNIC_BAREMETAL), mock.patch.object(np_drv.HPNetworkProvisioningDriver, 'delete_port', return_value=None) ) as (vnic_type, d_port): self.driver.delete_port_precommit(port_context) vnic_type.assert_called_with(port_context) d_port.assert_called_with(port_id) def test__construct_port(self): """Test _construct_port method.""" tenant_id = 'ten-1' network_id = 'net1-id' segmentation_id = 1001 vm_id = 'vm1' fake_port_dict = self._get_port_dict() network_context = self._get_network_context(tenant_id, network_id, segmentation_id, False) port_context = self._get_port_context(tenant_id, network_id, vm_id, network_context) port_dict = self.driver._construct_port(port_context, segmentation_id) self.assertEqual(port_dict, fake_port_dict) def test__get_binding_profile(self): """Test _get_binding_profile method.""" tenant_id = 'ten-1' network_id = 'net1-id' segmentation_id = 1001 vm_id = 'vm1' network_context = self._get_network_context(tenant_id, network_id, segmentation_id, False) port_context = self._get_port_context(tenant_id, network_id, vm_id, network_context) fake_profile = {'local_link_information': [{'switch_id': '11:22:33:44:55:66', 'port_id': 'Tengig0/1'}]} profile = self.driver._get_binding_profile(port_context) self.assertEqual(profile, fake_profile) def test__get_vnic_type(self): """Test _get_binding_profile method.""" tenant_id = 'ten-1' network_id = 'net1-id' segmentation_id = 1001 vm_id = 'vm1' network_context = self._get_network_context(tenant_id, network_id, segmentation_id, False) port_context = self._get_port_context(tenant_id, network_id, vm_id, network_context) vnic_type = self.driver._get_vnic_type(port_context) self.assertEqual(vnic_type, 'baremetal') class FakeNetworkContext(object): """To generate network context for testing purposes only.""" def __init__(self, network, segments=None, original_network=None): self._network = network self._original_network = original_network self._segments = segments @property def current(self): return self._network @property def original(self): return self._original_network @property def network_segments(self): return self._segments class FakePortContext(object): """To generate port context for testing purposes only.""" def __init__(self, port, original_port, network): self._port = port self._original_port = original_port self._network_context = network @property def current(self): return self._port @property def original(self): return self._original_port @property def network(self): return self._network_context
{ "content_hash": "b754f627701df5edafd3d6a839dd98d1", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 78, "avg_line_length": 38.76777251184834, "alnum_prop": 0.4799511002444988, "repo_name": "selvakumars2/baremetal-network-provisioning", "id": "878122269cc46f38922396b182390f652046dc78", "size": "8794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "baremetal_network_provisioning/tests/unit/ml2/test_mechanism_hp.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "205720" }, { "name": "Shell", "bytes": "1887" } ], "symlink_target": "" }
package ch.hsr.servicestoolkit.editor.security; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Returns a 401 error code (Unauthorized) to the client, when Ajax authentication fails. */ @Component public class AjaxAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed"); } }
{ "content_hash": "777c41b9dfa01fd14386bb417f1aeccc", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 113, "avg_line_length": 39.541666666666664, "alnum_prop": 0.8018967334035827, "repo_name": "ServiceCutter/ServiceCutter", "id": "2fe2687008789a4435bfcb4e7bbd808016023241", "size": "949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Editor/src/main/java/ch/hsr/servicestoolkit/editor/security/AjaxAuthenticationFailureHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "Dockerfile", "bytes": "1401" }, { "name": "HTML", "bytes": "107796" }, { "name": "Java", "bytes": "387480" }, { "name": "JavaScript", "bytes": "136560" }, { "name": "SCSS", "bytes": "2999" } ], "symlink_target": "" }
package de.zahlii.youtube.download.step; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; import javax.swing.SwingUtilities; import org.apache.commons.io.FilenameUtils; import org.jaudiotagger.tag.FieldKey; import radams.gracenote.webapi.GracenoteMetadata; import de.zahlii.youtube.download.QueueEntry; import de.zahlii.youtube.download.basic.SearchManager; import de.zahlii.youtube.download.ui.InfoFrame; import de.zahlii.youtube.download.ui.SearchFrame; public class StepMetaSearch extends Step { private String artist = "", title = "", album = ""; private GracenoteMetadata d; public StepMetaSearch(final QueueEntry entry) { super(entry, new StepDescriptor("GracenoteSearch", "Searches the Gracenote music DB for further information and cover art")); } @Override public void doStep() { final String baseName = FilenameUtils.getBaseName(entry.getDownloadTempFile().getAbsolutePath()); final String[] parts = baseName.split("-"); switch (parts.length) { case 1: title = parts[0].trim(); break; case 2: artist = parts[0].trim(); title = parts[1].trim(); break; case 3: artist = parts[0].trim(); title = parts[1].trim(); album = parts[2].trim(); break; default: final int n = parts.length - 3; artist = parts[n].trim(); title = parts[n + 1].trim(); album = parts[n + 2].trim(); } handleMetaSearch(); } @Override public String getStepResults() { return d == null ? "No Gracenote match found." : "Found possible match with songtitle " + d.getTitle() + "."; } private void handleMetaResult() { if (SwingUtilities.isEventDispatchThread()) { final InfoFrame i = new InfoFrame(entry, d); if (d == null) { i.fillInfo(artist, title, album); } i.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { if (arg0 == null) { StepMetaSearch.this.handleMetaSearch(); } else { StepMetaSearch.this.saveMetaData(i); } } }); i.setVisible(true); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { StepMetaSearch.this.handleMetaResult(); } }); } } private void handleMetaSearch() { if (SwingUtilities.isEventDispatchThread()) { final SearchFrame sf = new SearchFrame(artist, title, album); sf.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { if (arg0 == null) { StepMetaSearch.this.handleMetaResult(); } else { d = SearchManager.getInstance().searchForSong(sf.getArtist(), sf.getAlbum(), sf.getSongTitle()); StepMetaSearch.this.handleMetaResult(); } } }); sf.setVisible(true); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { StepMetaSearch.this.handleMetaSearch(); } }); } } private void saveMetaData(final InfoFrame fr) { final Map<FieldKey, String> data = new HashMap<FieldKey, String>(); data.put(FieldKey.ARTIST, fr.getArtist()); data.put(FieldKey.ALBUM_ARTIST, fr.getAlbumArtist()); data.put(FieldKey.CONDUCTOR, fr.getArtist()); data.put(FieldKey.ALBUM, fr.getAlbum()); data.put(FieldKey.TITLE, fr.getSongtitle()); data.put(FieldKey.TRACK, fr.getTrack()); data.put(FieldKey.TRACK_TOTAL, fr.getTrackCount()); data.put(FieldKey.YEAR, fr.getYear()); data.put(FieldKey.MOOD, fr.getMood()); data.put(FieldKey.GENRE, fr.getGenre()); data.put(FieldKey.TEMPO, fr.getTempo()); data.put(FieldKey.COMMENT, entry.getDownloadTempFile().getAbsolutePath()); entry.getStepInfo().put("meta.data", data); fr.getTagEditor().writeAllFields(data); fr.getTagEditor().writeArtwork(fr.getArtworkImage()); fr.getTagEditor().commit(); nextStep(); } }
{ "content_hash": "278e156c9d6e8495f3593be17e6afa43", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 127, "avg_line_length": 27.27027027027027, "alnum_prop": 0.6598116947472745, "repo_name": "Zahlii/Advanced-Youtube-Downloader", "id": "2a34e915ad1448f6d95174e3a077bb35db76c553", "size": "4036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Advanced-Youtube-Download/src/de/zahlii/youtube/download/step/StepMetaSearch.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "170638" } ], "symlink_target": "" }
package org.apache.gobblin.util; import java.util.Properties; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; public class PropertiesUtilsTest { @Test public void testExtractPropertiesWithPrefix() { Properties properties = new Properties(); properties.setProperty("k1.kk1", "v1"); properties.setProperty("k1.kk2", "v2"); properties.setProperty("k2.kk", "v3"); // First prefix Properties extractedPropertiesK1 = PropertiesUtils.extractPropertiesWithPrefix(properties, Optional.of("k1")); Assert.assertEquals(extractedPropertiesK1.getProperty("k1.kk1"), "v1"); Assert.assertEquals(extractedPropertiesK1.getProperty("k1.kk2"), "v2"); Assert.assertTrue(!extractedPropertiesK1.containsKey("k2.kk")); // Second prefix Properties extractedPropertiesK2 = PropertiesUtils.extractPropertiesWithPrefix(properties, Optional.of("k2")); Assert.assertTrue(!extractedPropertiesK2.containsKey("k1.kk1")); Assert.assertTrue(!extractedPropertiesK2.containsKey("k1.kk2")); Assert.assertEquals(extractedPropertiesK2.getProperty("k2.kk"), "v3"); // Missing prefix Properties extractedPropertiesK3 = PropertiesUtils.extractPropertiesWithPrefix(properties, Optional.of("k3")); Assert.assertTrue(!extractedPropertiesK3.containsKey("k1.kk1")); Assert.assertTrue(!extractedPropertiesK3.containsKey("k1.kk1")); Assert.assertTrue(!extractedPropertiesK3.containsKey("k2.kk")); } @Test public void testGetStringList() { Properties properties = new Properties(); properties.put("key", "1,2, 3"); // values as comma separated strings Assert.assertEquals(PropertiesUtils.getPropAsList(properties, "key"), ImmutableList.of("1", "2", "3")); Assert.assertEquals(PropertiesUtils.getPropAsList(properties, "key2", "default"), ImmutableList.of("default")); } @Test public void testGetValuesAsList() { Properties properties = new Properties(); properties.put("k1", "v1"); properties.put("k2", "v2"); properties.put("k3", "v2"); properties.put("K3", "v4"); Assert.assertEqualsNoOrder(PropertiesUtils.getValuesAsList(properties, Optional.of("k")).toArray(), new String[]{"v1", "v2", "v2"}); } }
{ "content_hash": "a48d4bf4737c9aa3679fae84e98e4486", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 136, "avg_line_length": 37.20967741935484, "alnum_prop": 0.729952319029042, "repo_name": "abti/gobblin", "id": "ae2ae80a3e05a196e4f9519a2a1deaa0956fbe23", "size": "3107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gobblin-utility/src/test/java/org/apache/gobblin/util/PropertiesUtilsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "40" }, { "name": "CSS", "bytes": "14588" }, { "name": "Dockerfile", "bytes": "7802" }, { "name": "Groovy", "bytes": "2273" }, { "name": "HTML", "bytes": "13792" }, { "name": "Java", "bytes": "13266164" }, { "name": "JavaScript", "bytes": "42618" }, { "name": "PLSQL", "bytes": "749" }, { "name": "Python", "bytes": "52481" }, { "name": "Roff", "bytes": "202" }, { "name": "Shell", "bytes": "78719" }, { "name": "XSLT", "bytes": "10197" } ], "symlink_target": "" }
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>Sample Post &#8211; Clean+Simple Theme</title> <meta name="description" content="Something..."> <meta name="keywords" content="sample post"> <!-- MathJax --> <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script> <!-- Open Graph --> <meta property="og:locale" content="en_US"> <meta property="og:type" content="article"> <meta property="og:title" content="Sample Post"> <meta property="og:description" content="Something..."> <meta property="og:url" content="http://localhost:4000/posts/2016-11-20/sample-post.html"> <meta property="og:site_name" content="Clean+Simple Theme"> <link rel="canonical" href="http://localhost:4000/posts/2016-11-20/sample-post.html"> <link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Clean+Simple Theme Feed"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- For all browsers --> <link rel="stylesheet" href="http://localhost:4000/assets/css/main.css"> <!-- Webfonts --> <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css"> <meta http-equiv="cleartype" content="on"> <!-- Load Modernizr --> <script src="http://localhost:4000/assets/js/vendor/modernizr-2.6.2.custom.min.js"></script> <!-- HEADER IMAGE --> <center> <span class="main-header-image"> <a href="/"><img src="/images/header/clean-and-simple-header.jpg"></a> </span> </center> <!-- NAVIGATION --> <br><br> <center> <span class="navigation-bar"> <a href="/">HOME</a> <a href="/archives/">ARCHIVE</a> <a href="/tags/">TAGS</a> <a href="/about/">ABOUT</a> <a href="/feed.xml">RSS</a> </span> </center> </head> <!-- BODY --> <body id="post-index"> <!--[if lt IE 9]><div class="upgrade"><strong><a href="http://whatbrowser.org/">Your browser is quite old!</strong> Why not upgrade to a different browser to better enjoy this site?</a></div><![endif]--> <div id="main" role="main"> <article class="hentry"> <!-- MAIN --> <h1 class="entry-title"> <a>Sample Post</a> </h1> <!-- POST CONTENT --> <div class="entry-content"> <p>Below is just about everything you’ll need to style in the theme. Check the source code to see the many embedded elements within paragraphs.</p> <h1 id="heading-1">Heading 1</h1> <h2 id="heading-2">Heading 2</h2> <h3 id="heading-3">Heading 3</h3> <h4 id="heading-4">Heading 4</h4> <h5 id="heading-5">Heading 5</h5> <h6 id="heading-6">Heading 6</h6> <h3 id="body-text">Body text</h3> <p>Lorem ipsum dolor sit amet, test link adipiscing elit. <strong>This is strong</strong>. Nullam dignissim convallis est. Quisque aliquam.</p> <p class="image-right"><img src="http://localhost:4000/images/3953273590_704e3899d5_m.jpg" alt="Smithsonian Image" /></p> <p><em>This is emphasized</em>. Donec faucibus. Nunc iaculis suscipit dui. 53 = 125. Water is H<sub>2</sub>O. Nam sit amet sem. Aliquam libero nisi, imperdiet at, tincidunt nec, gravida vehicula, nisl. The New York Times <cite>(That’s a citation)</cite>. <u>Underline</u>. Maecenas ornare tortor. Donec sed tellus eget sapien fringilla nonummy. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus.</p> <p>HTML and <abbr title="cascading stylesheets">CSS<abbr> are our tools. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus. Praesent mattis, massa quis luctus fermentum, turpis mi volutpat justo, eu volutpat enim diam eget metus.</abbr></abbr></p> <h3 id="blockquotes">Blockquotes</h3> <blockquote> <p>Lorem ipsum dolor sit amet, test link adipiscing elit. Nullam dignissim convallis est. Quisque aliquam.</p> </blockquote> <h2 id="list-types">List Types</h2> <h3 id="ordered-lists">Ordered Lists</h3> <ol> <li>Item one <ol> <li>sub item one</li> <li>sub item two</li> <li>sub item three</li> </ol> </li> <li>Item two</li> </ol> <h3 id="unordered-lists">Unordered Lists</h3> <ul> <li>Item one</li> <li>Item two</li> <li>Item three</li> </ul> <h2 id="tables">Tables</h2> <table rules="groups"> <thead> <tr> <th style="text-align: left">Header1</th> <th style="text-align: center">Header2</th> <th style="text-align: right">Header3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">cell1</td> <td style="text-align: center">cell2</td> <td style="text-align: right">cell3</td> </tr> <tr> <td style="text-align: left">cell4</td> <td style="text-align: center">cell5</td> <td style="text-align: right">cell6</td> </tr> </tbody> <tbody> <tr> <td style="text-align: left">cell1</td> <td style="text-align: center">cell2</td> <td style="text-align: right">cell3</td> </tr> <tr> <td style="text-align: left">cell4</td> <td style="text-align: center">cell5</td> <td style="text-align: right">cell6</td> </tr> </tbody> <tfoot> <tr> <td style="text-align: left">Foot1</td> <td style="text-align: center">Foot2</td> <td style="text-align: right">Foot3</td> </tr> </tfoot> </table> <h2 id="code-snippets">Code Snippets</h2> <p>Syntax highlighting via Rouge</p> <div class="language-css highlighter-rouge"><pre class="highlight"><code><span class="nf">#container</span> <span class="p">{</span> <span class="nl">float</span><span class="p">:</span> <span class="nb">left</span><span class="p">;</span> <span class="nl">margin</span><span class="p">:</span> <span class="m">0</span> <span class="m">-240px</span> <span class="m">0</span> <span class="m">0</span><span class="p">;</span> <span class="nl">width</span><span class="p">:</span> <span class="m">100%</span><span class="p">;</span> <span class="p">}</span> </code></pre> </div> <p>Non Pygments code example</p> <div class="highlighter-rouge"><pre class="highlight"><code>&lt;div id="awesome"&gt; &lt;p&gt;This is great isn't it?&lt;/p&gt; &lt;/div&gt; </code></pre> </div> <h2 id="buttons">Buttons</h2> <p>Make any link standout more when applying the <code class="highlighter-rouge">.btn</code> class.</p> <div class="language-html highlighter-rouge"><pre class="highlight"><code><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"#"</span> <span class="na">class=</span><span class="s">"btn btn-success"</span><span class="nt">&gt;</span>Success Button<span class="nt">&lt;/a&gt;</span> </code></pre> </div> <div><a href="#" class="btn">Primary Button</a></div> <div><a href="#" class="btn btn-success">Success Button</a></div> <div><a href="#" class="btn btn-warning">Warning Button</a></div> <div><a href="#" class="btn btn-danger">Danger Button</a></div> <div><a href="#" class="btn btn-info">Info Button</a></div> </div> <!--- DIVIDING LINE --> <hr> <!-- POST TAGS --> <div class="inline-tags"> <span> <a href="/tags/#sample post">#sample post&nbsp;&nbsp;&nbsp;</a> </span> </div> <br> <!-- POST DATE --> <div class="post-date"> NOVEMBER 20, 2016 </div> </article> </div> </body> <!-- FOOTER --> <footer> <div class="footer-wrapper"> <footer role="contentinfo"> <span> &copy; 2017 YOUR NAME HERE.<br>Powered by <a target="_blank" href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a target="_blank" href="https://github.com/nathanrooy/Clean-and-Simple-Jekyll-Theme">Clean+Simple</a> theme. </span> </footer> </div> </footer> </html>
{ "content_hash": "57bbb2b8e54505c16f3b2b487a005b25", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 467, "avg_line_length": 34.03557312252964, "alnum_prop": 0.6048078039716641, "repo_name": "nathanrooy/Clean-and-Simple-Jekyll-Theme", "id": "9af31e7a6d61f47a7ae7f9f25110d6914d833cf0", "size": "8615", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_site/posts/2016-11-20/sample-post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14946" }, { "name": "HTML", "bytes": "113082" }, { "name": "JavaScript", "bytes": "34676" } ], "symlink_target": "" }
<chart> <!-- This file defines the bar chart that shows order capture metrics by country. --> <!-- Define the chart type --> <chart-type>BarChart</chart-type> <!-- Specify the title of the chart --> <title>Unique Visits by Region</title> <!-- Specify the location of the title --> <title-position>TOP</title-position> <!-- Specify the font of the title --> <title-font> <font-family>Ariel</font-family> <size>20</size> <is-bold>false</is-bold> <is-italic>false</is-italic> </title-font> <width>400</width> <height>300</height> <chart-background type="color">#FFFFFF</chart-background> <plot-background type="color">#EEEEEE</plot-background> <!-- Specify the orientation of the bars --> <orientation>vertical</orientation> <!-- Specify the 3D-ness of the bars --> <is-3D>false</is-3D> <!-- Specify if the bars are stacked --> <is-stacked>false</is-stacked> <!-- Specify if the chart has a border and the border color --> <border-visible>false</border-visible> <border-paint>#000000</border-paint> <!-- Specify is the chart legend should be shown --> <include-legend>true</include-legend> <!-- Specify the color palette for the chart --> <color-palette> <!-- <color>#febe7d</color> --> <color>#336699</color> <!-- <color>#ccccfe</color> --> <color>#99CCFF</color> <!-- <color>#d8ebb3</color> --> <color>#999933</color> <!-- <color>#ffffcc</color> --> <color>#666699</color> <color>#CC9933</color> <color>#006666</color> <color>#3399FF</color> <color>#993300</color> <color>#CCCC99</color> <color>#666666</color> <color>#FFCC66</color> <color>#6699CC</color> <color>#663366</color> </color-palette> <!-- Specify where the data for the chart comes from --> <data> <!-- Specify the path to the action sequence that provides the data --> <data-solution>breadboard</data-solution> <data-path>customer_360/web_analytics_open_source/dashboard/components</data-path> <data-action>web_visit_region_week_g.xaction</data-action> <!-- Specify the output of the action sequence that contains the data --> <data-output>rule-result</data-output> <!-- Specify whether to get the chart series from the rows or columns --> <data-orientation>rows</data-orientation> </data> </chart>
{ "content_hash": "92d41fa76324aac95fce3bd63d7e509b", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 86, "avg_line_length": 28.375, "alnum_prop": 0.6709251101321586, "repo_name": "cjlavigne/breadboard", "id": "b61782f5b61905c2427c26ee1913c53d47236937", "size": "2270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bi_server/original/solution/customer_360/web_analytics_open_source/deprecated/dashboard/web_visit_region_week_vert_bar_g.widget.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13705" }, { "name": "HTML", "bytes": "6074" }, { "name": "Java", "bytes": "1060799" }, { "name": "JavaScript", "bytes": "30415" }, { "name": "Shell", "bytes": "2132" }, { "name": "TXL", "bytes": "11390246" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lte IE 8 ]> <html class="ie" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> <!--<![endif]--> <head> <meta charset="utf-8"> <!-- Page Title, (write properly for SEO) --> <title>Careers | A Multi-purpose Theme</title> <!-- Meta viewport & behaviour --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Meta data --> <meta name="author" content="Add Author"> <meta name="description" content="Add Description"> <meta name="keywords" content="add, site, and, page, keywords" /> <!-- Favicon, (keep icon in root folder) --> <link rel="Shortcut Icon" href="/favicon.ico" type="image/ico"> <!-- Open graph meta data, (Facebook) --> <meta property="og:description" content="Add a description here"> <meta property="og:image" content="http://addsiteurlhere.com/preview_image.png"> <meta property="og:site_name" content="Add Site Name"> <meta property="og:title" content="Add Page Title"> <meta property="og:type" content="website"> <meta property="og:url" content="http://addspecificpageurlhere.com/"> <!-- Meta card data, (Twitter) --> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@addtwitterhandlehere"> <meta name="twitter:creator" content="@addtwitterhandlehere"> <meta name="twitter:title" content="Add Site Title Here"> <meta name="twitter:description" content="Add site description here"> <meta name="twitter:image" content="http://addsiteurlhere.com/preview_image.png"> <!-- Apple touch icons, (keep icons in root folder) --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-icon-144x144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="57x57" href="apple-touch-icon-57x57-precomposed.png"> <!-- Theme Styles, (load in this order) --> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> <!-- Bootstrap framework --> <link href="css/animsition.min.css" rel="stylesheet" type="text/css"> <!-- Page transitions --> <link href="css/animate.css" rel="stylesheet" type="text/css"> <!-- Element animations --> <link href="css/slidebars.min.css" rel="stylesheet" type="text/css" /> <!-- Off-canvas navigation --> <link href="css/iconfont.css" rel="stylesheet" type="text/css"> <!-- Icon fonts --> <link href="css/style.css" rel="stylesheet" type="text/css"> <!-- Core theme styles --> <link href="css/custom.css" rel="stylesheet" type="text/css"> <!-- Custom stylesheet, (add custom styles here, always load last) --> <!-- Load our stylesheet for IE8 --> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="css/ie8.css" /> <![endif]--> <!-- Google Webfonts (Monserrat 400/700, Open Sans 400/600) --> <link href='//fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Open+Sans:400,600' rel='stylesheet' type='text/css'> <!-- Load our fonts individually if IE8+, to avoid faux bold & italic rendering --> <!--[if IE]> <link href='http://fonts.googleapis.com/css?family=Montserrat:400' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Montserrat:700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:600' rel='stylesheet' type='text/css'> <![endif]--> <!-- jQuery | Load our jQuery, with an alternative source fallback to a local version if request is unavailable --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/jquery-1.11.1.min.js"><\/script>')</script> <!-- Load these in the <head> for quicker IE8+ load times --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="js/html5shiv.min.js"></script> <script src="js/respond.min.js"></script> <![endif]--> </head> <body id="careers" class="lightnav animsition"> <!-- ============================ Off-canvas navigation ============================ --> <div class="sb-slidebar sb-right sb-style-overlay sb-momentum-scrolling"> <div class="sb-close" aria-label="Close Menu" aria-hidden="true"> <img src="img/global/close.png" alt="Close"/> </div> <!-- Lists in Slidebars --> <ul class="sb-menu"> <li><a href="index.html" class="animsition-link" title="Image Hero">Start</a></li> <li><a href="index-video.html" class="animsition-link" title="Video Hero">Video Alt</a></li> <li><a href="company.html" class="animsition-link" title="Company">Company</a></li> <li><a href="values.html" class="animsition-link" title="Values">Values</a></li> <li><a href="team.html" class="animsition-link" title="Team">Team</a></li> <li><a href="careers.html" class="animsition-link" title="Careers">Careers</a></li> <!-- Dropdown Menu --> <li> <a class="sb-toggle-submenu">Portfolio<span class="sb-caret"></span></a> <ul class="sb-submenu"> <li><a href="portfolio.html" class="animsition-link" title="Filter Portfolio">Filter Portfolio</a></li> <li><a href="portfolio-item.html" class="animsition-link" title="Portfolio Item">Portfolio Item</a></li> </ul> </li> <li><a href="faq.html" class="animsition-link" title="FAQ&#39;s">FAQ&#39;s</a></li> <li><a href="proposal.html" class="animsition-link" title="Start a Project">Start a Project</a></li> <li><a href="contact.html" class="animsition-link" title="Contact Us">Contact Us</a></li> </ul> <!-- Lists in Slidebars --> <ul class="sb-menu secondary"> <li><a href="blog.html" class="animsition-link" title="T&amp;C&#39;s">Read the Blog</a></li> <li><a href="style-guide.html" class="animsition-link" title="Style Guide">Theme Style Guide</a></li> </ul> <ul class="sb-menu secondary"> <li><a href="terms-conditions.html" class="animsition-link" title="T&amp;C&#39;s">Terms &amp; Conditions</a></li> <li><a href="privacy-policy.html" class="animsition-link" title="Privacy Policy">Privacy Statement</a></li> <li><a href="press-kit.html" class="animsition-link" title="Press Kit">Press Kit</a></li> </ul> </div> <!-- ============================ END Off-canvas navigation ============================ --> <!-- ============================ #sb-site Main Page Wrapper =========================== --> <div id="sb-site"> <!-- #sb-site - All page content should be contained within this id, except the off-canvas navigation itself --> <!-- ============================ Header & Logo bar =========================== --> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <!-- Nav logo --> <div class="logo"> <a href="index.html" title="Logo" class="animsition-link"><img src="img/global/logo.png" alt="Logo"></a> </div> <!-- // Nav logo --> <!-- Info-bar --> <nav> <ul class="nav"> <li><a href="index.html" class="animsition-link">Start</a></li> <li class="nolink">We are a <span>media</span> company that <span>surpasses</span> expectations</li> <li><a href="http://www.twitter.com/" title="Twitter" target="_blank"><i class="social-icon-twitter"></i></a></li> <li><a href="http://www.facebook.com/" title="Facebook" target="_blank"><i class="social-icon-facebook"></i></a></li> <li><a href="http://www.instagram.com/" title="Instagram" target="_blank"><i class="social-icon-instagram"></i></a></li> <li class="nolink"><span>Careers</span></li> </ul> </nav> <!--// Info-bar --> </div> <!-- // .container --> <div class="learnmore sb-toggle-right">Learn More</div> <button type="button" class="navbar-toggle menu-icon sb-toggle-right" title="learn More"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar before"></span> <span class="icon-bar main"></span> <span class="icon-bar after"></span> </button> </div> <!-- // .navbar-inner --> </div> <!-- ============================ END Header & Logo bar =========================== --> <!-- ============================ Page Header =========================== --> <section id="page-header" class="element-img scrollme" style="background-image: url('img/careers/page-header.jpg')"> <div class="container"> <div class="row boost"> <div class="col-xs-12 col-sm-12 col-md-8 col-md-offset-2 vertical-align text-center"> <div class="animateme center-me" data-when="exit" data-from="0" data-to="0.6" data-opacity="0" data-translatey="120"> <h2>Looking for a <span>career change?</span></h2> </div> </div> </div> </div> <div class="headerfade beige-dk"></div> </section> <!-- ============================ END Page Header =========================== --> <!-- ============================ Page tabs =========================== --> <section id="pagetabs" class="boost"> <div class="container"> <!-- ============================ Page tabs =========================== --> <div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <ul class="row page-nav"> <li class="col-xs-6 col-sm-3 col-md-3 col-lg-3"><a href="company.html" class="animsition-link" title="Company"><i class="icon-basic-book-pencil"></i>Company</a></li> <li class="col-xs-6 col-sm-3 col-md-3 col-lg-3"><a href="values.html" class="animsition-link" title="Values"><i class="icon-basic-heart"></i>Values</a></li> <li class="col-xs-6 col-sm-3 col-md-3 col-lg-3"><a href="team.html" class="animsition-link" title="Team"><i class="icon-basic-life-buoy"></i>Team</a></li> <li class="col-xs-6 col-sm-3 col-md-3 col-lg-3 active"><a href="careers.html" class="animsition-link" title="Careers"><i class="icon-basic-globe"></i>Careers <span class="badge jobs">4</span></a></li> </ul> </div> </div> <!-- ============================ END Page tabs =========================== --> <!-- ============================ Careers =========================== --> <div class="row"> <div class="col-md-6 col-md-offset-3 titleblock text-center"> <h2>Careers &amp; Openings</h2> <p>Looking to work for the best company in town, that offers all the best perks? Apply today if you think you&#39;ve got what it takes.</p> </div> </div> <!-- Job 1 --> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 wow fadeInLeft" data-wow-delay="0.3s"> <h4>Front-end Web Developer</h4> </div> <div class="col-xs-12 col-sm-9 col-md-9 col-lg-9 wow fadeInRight" data-wow-delay="0.3s"> <p>Signs without. There land. Earth earth creepeth, image. Said make moved bearing man god let i. She&#39;d third you&#39;ll grass one were above third gathered don&#39;t every life fly be bring may.</p> <!-- PANEL START --> <div class="panel"> <div class="panel-heading"> <a class="panel-title" data-toggle="collapse" data-parent="#job-1" href="#job-1-dropdown"> Read more about this position <span><i class="glyphicon glyphicon-chevron-down"></i></span> </a> </div> <div id="job-1-dropdown" class="panel-collapse collapse"> <div class="panel-body"> <p>Fish seas lights air creature rule won't unto abundantly. He male tree days every won't. Seed fowl set for there them earth, meat thing, above. Two great signs under, behold lights likeness replenish god he sixth set male fish. Him.</p> <ul> <li>Salary 27-35k per annum</li> <li>25 days holiday</li> <li>Free lunches</li> <li>Macbook Pro Retina</li> <li>Awesome office perks</li> </ul> </div> <!-- // .panel-body --> </div> <!-- // .panel-collapse --> </div> <!-- // .panel --> </div> <!-- // .col-xs-12 .col-sm-9 .col-md-9 .col-lg-9 --> <div class="clearfix"></div> <hr> </div> <!-- // .row --> <!-- Job 2 --> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 wow fadeInLeft" data-wow-delay="0.6s"> <h4>Staff Ambassador</h4> </div> <div class="col-xs-12 col-sm-9 col-md-9 col-lg-9 wow fadeInRight" data-wow-delay="0.6s"> <p>Signs without. There land. Earth earth creepeth, image. Said make moved bearing man god let i. She&#39;d third you&#39;ll grass one were above third gathered don&#39;t every life fly be bring may.</p> <!-- PANEL START --> <div class="panel"> <div class="panel-heading"> <a class="panel-title" data-toggle="collapse" data-parent="#job-2" href="#job-2-dropdown"> Read more about this position <span><i class="glyphicon glyphicon-chevron-down"></i></span> </a> </div> <div id="job-2-dropdown" class="panel-collapse collapse"> <div class="panel-body"> <p>AFish seas lights air creature rule won't unto abundantly. He male tree days every won't. Seed fowl set for there them earth, meat thing, above. Two great signs under, behold lights likeness replenish god he sixth set male fish. Him.</p> <ul> <li>Salary 27-35k per annum</li> <li>25 days holiday</li> <li>Free lunches</li> <li>Macbook Pro Retina</li> <li>Awesome office perks</li> </ul> </div> <!-- // .panel-body --> </div> <!-- // .panel-collapse --> </div> <!-- // .panel --> </div> <!-- // .col-xs-12 .col-sm-9 .col-md-9 .col-lg-9 --> <div class="clearfix"></div> <hr> </div> <!-- // .row --> <!-- Job 3 --> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 wow fadeInLeft" data-wow-delay="0.9s"> <h4>Int&#39;l Account Manager</h4> </div> <div class="col-xs-12 col-sm-9 col-md-9 col-lg-9 wow fadeInRight" data-wow-delay="0.9s"> <p>Signs without. There land. Earth earth creepeth, image. Said make moved bearing man god let i. She&#39;d third you&#39;ll grass one were above third gathered don&#39;t every life fly be bring may.</p> <!-- PANEL START --> <div class="panel"> <div class="panel-heading"> <a class="panel-title" data-toggle="collapse" data-parent="#job-3" href="#job-3-dropdown"> Read more about this position <span><i class="glyphicon glyphicon-chevron-down"></i></span> </a> </div> <div id="job-3-dropdown" class="panel-collapse collapse"> <div class="panel-body"> <p>Fish seas lights air creature rule won't unto abundantly. He male tree days every won't. Seed fowl set for there them earth, meat thing, above. Two great signs under, behold lights likeness replenish god he sixth set male fish. Him.</p> <ul> <li>Salary 27-35k per annum</li> <li>25 days holiday</li> <li>Free lunches</li> <li>Macbook Pro Retina</li> <li>Awesome office perks</li> </ul> </div> <!-- // .panel-body --> </div> <!-- // .panel-collapse --> </div> <!-- // .panel --> </div> <!-- // .col-xs-12 .col-sm-9 .col-md-9 .col-lg-9 --> <div class="clearfix"></div> <hr> </div> <!-- // .row --> <!-- Job 4 --> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3 wow fadeInLeft" data-wow-delay="1.2s"> <h4>Server Analyst</h4> </div> <div class="col-xs-12 col-sm-9 col-md-9 col-lg-9 wow fadeInRight" data-wow-delay="1.2s"> <p>Signs without. There land. Earth earth creepeth, image. Said make moved bearing man god let i. She&#39;d third you&#39;ll grass one were above third gathered don&#39;t every life fly be bring may.</p> <!-- PANEL START --> <div class="panel"> <div class="panel-heading"> <a class="panel-title" data-toggle="collapse" data-parent="#job-4" href="#job-4-dropdown"> Read more about this position <span><i class="glyphicon glyphicon-chevron-down"></i></span> </a> </div> <div id="job-4-dropdown" class="panel-collapse collapse"> <div class="panel-body"> <p>Fish seas lights air creature rule won't unto abundantly. He male tree days every won't. Seed fowl set for there them earth, meat thing, above. Two great signs under, behold lights likeness replenish god he sixth set male fish. Him.</p> <ul> <li>Salary 27-35k per annum</li> <li>25 days holiday</li> <li>Free lunches</li> <li>Macbook Pro Retina</li> <li>Awesome office perks</li> </ul> </div> <!-- // .panel-body --> </div> <!-- // .panel-collapse --> </div> <!-- // .panel --> </div> <!-- // .col-xs-12 .col-sm-9 .col-md-9 .col-lg-9 --> <div class="clearfix"></div> <hr> </div> <!-- // .row --> </div> <!-- // .col-md-8 .col-md-offset-2 --> </div> <!-- // .row --> <div class="row"> <div class="col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2"> <div class="row"> <div class="col-sm-6 col-md-6 col-lg-6 wow fadeInLeft" data-wow-delay="0.4s"> <img src="img/careers/box.jpg" class="img-responsive" alt="Image"> </div> <div class="col-sm-6 col-md-6 col-lg-6 wow fadeInRight" data-wow-delay="0.4s"> <div class="apply"> <h4>Think you&#39;ve got what it takes?</h4> <h5><a href="contact.html" class="animsition-link" title="Apply Today">apply today</a></h5> </div> </div> </div> <div class="col-md-12 apply-meta"> <p>That's great! Head on over to our <a href="contact.html" class="animsition-link" title="Contact" style="color:#fff;text-decoration:underline">contact</a> page and send us an email to introduce yourself.</p> <p>Need to send a CV? No problem. Please send your work history across to <span style="color:#fff;text-decoration:underline">email@address.com</span>, making sure you include a covering letter, for the attention of Mr. Smith.</p> </div> </div> </div> </div> </section> <!-- ============================ END Page tabs =========================== --> <!-- ============================ Hire Us =========================== --> <section id="hire-us" class="beige-dk"> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-lg-offset-2"> <div class="row"> <div class="col-md-8"> <h4 class="headspc">Ready to begin your project?</h4> <p class="copyspc">Find your professional and begin working within 48 hours.</p> </div> <!-- Go to proposal.html link --> <div class="col-md-4"> <a href="proposal.html" class="custom-button animsition-link" title="Proposal">Start Your Project</a> </div> </div> </div> </div> </div> </section> <!-- ============================ END Hire Us =========================== --> <!-- ============================ Footer =========================== --> <footer> <div class="container"> <div class="row footer-top"> <div class="col-xs-12 col-sm-12 col-md-3 footer_grid"> <ul class="f_grid1"> <li> <div class="extra-wrap"> <h5>Address</h5> </div> <div class="clearfix"> </div> </li> </ul> <p class="m_14">aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis.</p> <div class="address"> <p><i class="icon-basic-geolocalize-01"></i> 500 Lorem Ipsum Dolor Sit,</p> <p><i class="icon-basic-life-buoy"></i> Phone:(00) 222 666 444</p> <p><i class="icon-basic-mail-multiple"></i> Email: <span>help[at]email.com</span></p> </div> </div> <div class="col-xs-12 col-sm-12 col-md-3 footer_grid"> <ul class="f_grid1"> <li> <div class="extra-wrap"> <h5>Snapshot</h5> </div> <div class="clearfix"> </div> </li> </ul> <p class="m_14">aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commod consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat</p> </div> <div class="col-xs-12 col-sm-12 col-md-3 footer_grid"> <ul class="f_grid1"> <li> <div class="extra-wrap"> <h5>Quick Links</h5> </div> <div class="clearfix"> </div> </li> </ul> <div class="footer_lists"> <ul class="list"> <li><a href="#">Home</a></li> <li><a href="#">Features</a></li> <li><a href="#">Screenshots</a></li> <li><a href="#">About</a></li> </ul> <ul class="list1"> <li><a href="#">Pricing</a></li> <li><a href="#">News</a></li> <li><a href="#">figures</a></li> <li><a href="#">Contact</a></li> </ul> <div class="clearfix"> </div> </div> </div> <div class="col-xs-12 col-sm-12 col-md-3 footer_grid"> <ul class="f_grid1"> <li> <div class="extra-wrap"> <h5>Just Another Area</h5> </div> <div class="clearfix"> </div> </li> </ul> <p class="m_14">Another area to add some of your most vital content or links. You can use this area to show any content globally across the site.</p> </div> </div> <div class="footer_bottom"> <div class="copy"> <p> &copy; 2010<script>new Date().getFullYear()>2010&&document.write("-"+new Date().getFullYear());</script>, Company. All Rights Reserved. </p> </div> <div class="social"> <ul> <li><a href="http://twitter.com/" target="_blank"><i class="social-icon-twitter"></i></a></li> <li><a href="http://facebook.com/" target="_blank"><i class="social-icon-facebook"></i></a></li> <li><a href="http://instagram.com/" target="_blank"><i class="social-icon-instagram"></i></a></li> <li><a href="http://linkedin.com/" target="_blank"><i class="social-icon-linkedin"></i></a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </footer> <!-- ============================ END Footer =========================== --> <!-- //////////////////////////////////////////////////////////// --> <!-- Load our scripts --> <script src="js/plugins.min.js"></script><!-- Bootstrap core and concatenated plugins always load first --> <script src="js/scripts.js"></script><!-- Theme scripts --> </div> <!-- ============================ END #sb-site Main Page Wrapper =========================== --> </body> </html>
{ "content_hash": "31ef67dc270ea172bb421d9e65652d28", "timestamp": "", "source": "github", "line_count": 524, "max_line_length": 284, "avg_line_length": 60.06106870229008, "alnum_prop": 0.42710981189628877, "repo_name": "jahde/chefly", "id": "d8248cde6082705dff49e7e9f73e947b49cb4339", "size": "31472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/assets/alaska-v1.0.2/theme/careers.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "3433" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "91109" }, { "name": "JavaScript", "bytes": "1010629" }, { "name": "Ruby", "bytes": "51960" } ], "symlink_target": "" }
package com.oliver.easy.webview; /** * Created by wangdong on 16-1-5. */ public class WebViewTest { }
{ "content_hash": "25fa6da48bdb36c26065d8ff33932ed2", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 33, "avg_line_length": 15, "alnum_prop": 0.6857142857142857, "repo_name": "mazouri/EasyAndroidDev", "id": "9632096ee0041771830c85a7e99deebb2f48166f", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/oliver/easy/webview/WebViewTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "332875" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="Styles/branding.css"/> <title>Feature Stapling</title> <meta name="Description" content="Adds a FeatureSitetemplateAssocation to the selected feature" /> <style type="text/css"> .OH_TocResize { top: 126px; } </style> </head> <body class="primary-mtps-offline-document" style="max-width: 1220px;" > <table class="noSpace" style="width: 100%;"> <tr> <td colspan="2" style="background-color: #6685A2;">&nbsp;</td> </tr> <tr> <td> <img src="./_img/header_left.jpg" height="66" style="margin-top: 10px; margin-bottom: 20px" /> </td> <td align="right" valign="top" rowspan="2"> <img src="./_img/header_right.jpg" style="margin-top: 2px" height="72"/> </td> </tr> </table> <div class="OH_topic"> <div id="mainHeader"> <table> <tbody> <tr> <td> <h1>Feature Stapling</h1> </td> </tr> </tbody> </table> </div> </div> <div id="mainSection"> <div id="mainBody"> <div class="introduction"><p>Adds a FeatureSitetemplateAssocation to the selected feature</p></div> <DIV class="OH_CollapsibleAreaRegion"> <DIV class="OH_regiontitle">Recipe Description</DIV> <DIV class="OH_RegionToggle"></DIV> </DIV> <DIV class="OH_clear"></DIV> <p> Stapling SharePoint features with site definitions, which relies on the FeatureSiteTemplateAssociation element, allows developers to attach features to both standard and custom site definitions without directly modifying them. <br /> Every new site that is based on a site definition with a stapled feature is created with that feature activated. <br /> Feature stapling is particularly useful when you want to add functionality to standard site definitions because editing standard site definition files is not a recommended practice. (Source: MSDN) </p> <DIV class="OH_CollapsibleAreaRegion"> <DIV class="OH_regiontitle">Arguments</DIV> <DIV class="OH_RegionToggle"></DIV> </DIV> <DIV class="OH_clear"></DIV> <p> <div class="tableSection"> <table id="argumentTable" width="100%"> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td class="name" colspan="2">Feature Associations</td> </tr> <tr> <td>Feature</td> <td>Required Feature. Feature to which the previously selected feature should be stapled to.</td> </tr> <tr> <td>Site Template</td> <td>Optional Site Definition. Site Definition to which the previously selected feature should be stapled to.</td> </tr> </table> </div> </p> <DIV class="OH_CollapsibleAreaRegion"> <DIV class="OH_regiontitle">References</DIV> <DIV class="OH_RegionToggle"></DIV> </DIV> <DIV class="OH_clear"></DIV> <p> <ul> <li> <a href="http://msdn.microsoft.com/en-us/library/dd206907.aspx" target="_new">MSDN: Stapling Features to Site Definitions</a> </li> <li> <a href="http://www.sharepointnutsandbolts.com/2007/05/feature-stapling.html" target="_new">Chris O'Brien: Feature Stapling </a> </li> <li> <a href="http://blogs.msdn.com/cjohnson/archive/2006/11/01/feature-stapling-in-wss-v3.aspx" target="_new">Chris Johnson: Feature Stapling in WSS V3</a> </li> <li> <a href="http://blogs.msdn.com/sharepoint/archive/2007/03/22/customizing-moss-2007-my-sites-within-the-enterprise.aspx" target="_new">MS SharePoint Team Blog: Customizing MOSS 2007 My Sites within the enterprise</a> </li> <li> <a href="http://msdn.microsoft.com/en-us/library/bb861862.aspx" target="_new">Definition Schema</a> </li> </ul></p> <DIV class="OH_CollapsibleAreaRegion"> <DIV class="OH_regiontitle">Authors</DIV> <DIV class="OH_RegionToggle"></DIV> </DIV> <DIV class="OH_clear"></DIV> <p> <ul> <li>Torsten Mandelkow</li><li>Matthias Einig</li> </ul> </p> <DIV class="OH_CollapsibleAreaRegion"> <DIV class="OH_regiontitle">Version history</DIV> <DIV class="OH_RegionToggle"></DIV> </DIV> <DIV class="OH_clear"></DIV> <p> <ul> <li>1.1 Updated Documentation</li><li>1.0 Initial Recipe</li> </ul> </p> </div> </div> </div> </div> <br /> <table width="100%"> <tr> <td> <div class="OH_feedbacklink"> <b>Disclaimer:</b> The views and opinions expressed in this documentation and in SPSF are those of the <a href="SPSF_OVERVIEW_110_AUTHORS.html">authors</a> and do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. All trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.<br /> SharePoint Software Factory, Version 4.1.2.2904, <a href="SPSF_OVERVIEW_800_LICENSE.html">GPLv2</a>, see <a href="http://spsf.codeplex.com">http://spsf.codeplex.com</a> for more information </div> <br /> </td> </tr> </table> <br /> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-6735734-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
{ "content_hash": "1971ad77eda07cf4f883a22525e9e26f", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 592, "avg_line_length": 38.993788819875775, "alnum_prop": 0.5833067856005097, "repo_name": "rencoreab/SharePoint-Software-Factory", "id": "dd77204986ef7d06dd631a61e05ca47fdca5b2b4", "size": "6278", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "SPALM.SPSF/Help/OutputHTMLOnline/SPSF_RECIPE_FEATURESTAPLING.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1259824" }, { "name": "C#", "bytes": "1810937" }, { "name": "C++", "bytes": "11910081" }, { "name": "CSS", "bytes": "60598" }, { "name": "JavaScript", "bytes": "65766" }, { "name": "Objective-C", "bytes": "168782" }, { "name": "PowerShell", "bytes": "229454" }, { "name": "Shell", "bytes": "16959" }, { "name": "XSLT", "bytes": "2095" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { /// <summary> /// Provides a representation of an element's shadow root. /// </summary> public class ShadowRoot : ISearchContext, IWrapsDriver, IWebDriverObjectReference { /// <summary> /// The property name that represents an element shadow root in the wire protocol. /// </summary> public const string ShadowRootReferencePropertyName = "shadow-6066-11e4-a52e-4f735466cecf"; private WebDriver driver; private string shadowRootId; /// <summary> /// Initializes a new instance of the <see cref="ShadowRoot"/> class. /// </summary> /// <param name="parentDriver">The <see cref="WebDriver"/> instance that is driving this shadow root.</param> /// <param name="id">The ID value provided to identify the shadow root.</param> public ShadowRoot(WebDriver parentDriver, string id) { this.driver = parentDriver; this.shadowRootId = id; } /// <summary> /// Gets the <see cref="IWebDriver"/> driving this shadow root. /// </summary> public IWebDriver WrappedDriver { get { return this.driver; } } /// <summary> /// Gets the internal ID for this ShadowRoot. /// </summary> string IWebDriverObjectReference.ObjectReferenceId { get { return this.shadowRootId; } } internal static bool ContainsShadowRootReference(Dictionary<string, object> shadowRootDictionary) { if (shadowRootDictionary == null) { throw new ArgumentNullException(nameof(shadowRootDictionary), "The dictionary containing the shadow root reference cannot be null"); } return shadowRootDictionary.ContainsKey(ShadowRootReferencePropertyName); } internal static ShadowRoot FromDictionary(WebDriver driver, Dictionary<string, object> shadowRootDictionary) { return new ShadowRoot(driver, shadowRootDictionary[ShadowRoot.ShadowRootReferencePropertyName].ToString()); } /// <summary> /// Finds the first <see cref="IWebElement"/> using the given method. /// </summary> /// <param name="by">The locating mechanism to use.</param> /// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns> /// <exception cref="NoSuchElementException">If no element matches the criteria.</exception> public IWebElement FindElement(By by) { if (by == null) { throw new ArgumentNullException(nameof(@by), "by cannot be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.shadowRootId); parameters.Add("using", by.Mechanism); parameters.Add("value", by.Criteria); Response commandResponse = this.driver.InternalExecute(DriverCommand.FindShadowChildElement, parameters); return this.driver.GetElementFromResponse(commandResponse); } /// <summary> /// Finds all <see cref="IWebElement">IWebElements</see> within the current context /// using the given mechanism. /// </summary> /// <param name="by">The locating mechanism to use.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see> /// matching the current criteria, or an empty list if nothing matches.</returns> public ReadOnlyCollection<IWebElement> FindElements(By by) { if (by == null) { throw new ArgumentNullException(nameof(@by), "by cannot be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.shadowRootId); parameters.Add("using", by.Mechanism); parameters.Add("value", by.Criteria); Response commandResponse = this.driver.InternalExecute(DriverCommand.FindShadowChildElements, parameters); return this.driver.GetElementsFromResponse(commandResponse); } Dictionary<string, object> IWebDriverObjectReference.ToDictionary() { Dictionary<string, object> shadowRootDictionary = new Dictionary<string, object>(); shadowRootDictionary.Add(ShadowRootReferencePropertyName, this.shadowRootId); return shadowRootDictionary; } } }
{ "content_hash": "d8d79e596073155c60f0199e83298b20", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 148, "avg_line_length": 41.902654867256636, "alnum_prop": 0.6293558606124604, "repo_name": "HtmlUnit/selenium", "id": "c0850b1b033070d75fdf5eb3c8ed80ff22372e73", "size": "5617", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "dotnet/src/webdriver/ShadowRoot.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "825" }, { "name": "Batchfile", "bytes": "4443" }, { "name": "C", "bytes": "82917" }, { "name": "C#", "bytes": "2977660" }, { "name": "C++", "bytes": "2282643" }, { "name": "CSS", "bytes": "1049" }, { "name": "Dockerfile", "bytes": "1737" }, { "name": "HTML", "bytes": "1379423" }, { "name": "Java", "bytes": "6302205" }, { "name": "JavaScript", "bytes": "2533049" }, { "name": "Makefile", "bytes": "4655" }, { "name": "Python", "bytes": "974345" }, { "name": "Ragel", "bytes": "3086" }, { "name": "Ruby", "bytes": "1004097" }, { "name": "Shell", "bytes": "30004" }, { "name": "Starlark", "bytes": "395776" }, { "name": "TypeScript", "bytes": "110634" }, { "name": "XSLT", "bytes": "1047" } ], "symlink_target": "" }
package org.springframework.boot.actuate.web.exchanges.servlet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RecordableServletHttpRequest}. * * @author Madhura Bhave */ class RecordableServletHttpRequestTests { private MockHttpServletRequest request; @BeforeEach void setup() { this.request = new MockHttpServletRequest("GET", "/script"); } @Test void getUriWithoutQueryStringShouldReturnUri() { validate("http://localhost/script"); } @Test void getUriShouldReturnUriWithQueryString() { this.request.setQueryString("a=b"); validate("http://localhost/script?a=b"); } @Test void getUriWithSpecialCharactersInQueryStringShouldEncode() { this.request.setQueryString("a=${b}"); validate("http://localhost/script?a=$%7Bb%7D"); } @Test void getUriWithSpecialCharactersEncodedShouldNotDoubleEncode() { this.request.setQueryString("a=$%7Bb%7D"); validate("http://localhost/script?a=$%7Bb%7D"); } private void validate(String expectedUri) { RecordableServletHttpRequest sourceRequest = new RecordableServletHttpRequest(this.request); assertThat(sourceRequest.getUri().toString()).isEqualTo(expectedUri); } }
{ "content_hash": "638318d44e6f2f2cbf81edbd1d47e401", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 94, "avg_line_length": 24.555555555555557, "alnum_prop": 0.7631975867269984, "repo_name": "vpavic/spring-boot", "id": "4f76d5d3f89bdf3394e013c3120d348ab67bf085", "size": "1947", "binary": false, "copies": "7", "ref": "refs/heads/main", "path": "spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/servlet/RecordableServletHttpRequestTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2138" }, { "name": "CSS", "bytes": "117" }, { "name": "Dockerfile", "bytes": "2309" }, { "name": "Groovy", "bytes": "15015" }, { "name": "HTML", "bytes": "58426" }, { "name": "Java", "bytes": "21554950" }, { "name": "JavaScript", "bytes": "33592" }, { "name": "Kotlin", "bytes": "432332" }, { "name": "Mustache", "bytes": "449" }, { "name": "Ruby", "bytes": "7867" }, { "name": "Shell", "bytes": "45437" }, { "name": "Smarty", "bytes": "2882" }, { "name": "Vim Snippet", "bytes": "135" } ], "symlink_target": "" }
declare namespace Jymfony.Component.HttpServer.EventListener { import EventDispatcherInterface = Jymfony.Contracts.EventDispatcher.EventDispatcherInterface; import EventSubscriberInterface = Jymfony.Contracts.EventDispatcher.EventSubscriberInterface; import LoggerInterface = Jymfony.Component.Logger.LoggerInterface; import Request = Jymfony.Component.HttpFoundation.Request; import GetResponseForExceptionEvent = Jymfony.Component.HttpServer.Event.GetResponseForExceptionEvent; import EventSubscriptions = Jymfony.Contracts.EventDispatcher.EventSubscriptions; export class ExceptionListener extends implementationOf(EventSubscriberInterface) { private _controller: Invokable<any> | string; private _logger: LoggerInterface; private _debug: boolean; /** * Constructor. */ __construct(controller: Invokable<any> | string, logger?: LoggerInterface | undefined, debug?: boolean): void; constructor(controller: Invokable<any> | string, logger?: LoggerInterface | undefined, debug?: boolean); /** * Gets a response for a given exception. */ onException(event: GetResponseForExceptionEvent, eventName: string, eventDispatcher: EventDispatcherInterface): Promise<void>; /** * @inheritdoc */ static getSubscribedEvents(): EventSubscriptions; /** * Logs an exception. */ protected _logException(exception: Error, message: string): void; /** * Clones the request for the exception. * * @param exception The thrown exception * @param request The original request * * @returns The cloned request */ protected _duplicateRequest(exception: Error, request: Request): Request; } }
{ "content_hash": "5103d22cd3378ab29102599f4927f2df", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 134, "avg_line_length": 39.42553191489362, "alnum_prop": 0.6837560712358338, "repo_name": "massimilianobraglia/jymfony", "id": "6b0474f54541594f78e245007205d80e3bedf505", "size": "1853", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Component/HttpServer/types/EventListener/ExceptionListener.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2981759" } ], "symlink_target": "" }
package org.springframework.test.web.servlet.samples.client.standalone.resultmatches; import jakarta.validation.Valid; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Controller; import org.springframework.test.web.Person; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.client.MockMvcWebTestClient; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * {@link MockMvcWebTestClient} equivalent of the MockMvc * {@link org.springframework.test.web.servlet.samples.standalone.resultmatchers.ModelAssertionTests}. * * @author Rossen Stoyanchev */ public class ModelAssertionTests { private final WebTestClient client = MockMvcWebTestClient.bindToController(new SampleController("a string value", 3, new Person("a name"))) .controllerAdvice(new ModelAttributeAdvice()) .alwaysExpect(status().isOk()) .build(); @Test void attributeEqualTo() throws Exception { performRequest(HttpMethod.GET, "/") .andExpect(model().attribute("integer", 3)) .andExpect(model().attribute("string", "a string value")) .andExpect(model().attribute("integer", equalTo(3))) // Hamcrest... .andExpect(model().attribute("string", equalTo("a string value"))) .andExpect(model().attribute("globalAttrName", equalTo("Global Attribute Value"))); } @Test void attributeExists() throws Exception { performRequest(HttpMethod.GET, "/") .andExpect(model().attributeExists("integer", "string", "person")) .andExpect(model().attribute("integer", notNullValue())) // Hamcrest... .andExpect(model().attribute("INTEGER", nullValue())); } @Test void attributeHamcrestMatchers() throws Exception { performRequest(HttpMethod.GET, "/") .andExpect(model().attribute("integer", equalTo(3))) .andExpect(model().attribute("string", allOf(startsWith("a string"), endsWith("value")))) .andExpect(model().attribute("person", hasProperty("name", equalTo("a name")))); } @Test void hasErrors() throws Exception { performRequest(HttpMethod.POST, "/persons").andExpect(model().attributeHasErrors("person")); } @Test void hasNoErrors() throws Exception { performRequest(HttpMethod.GET, "/").andExpect(model().hasNoErrors()); } private ResultActions performRequest(HttpMethod method, String uri) { EntityExchangeResult<Void> result = client.method(method).uri(uri).exchange().expectBody().isEmpty(); return MockMvcWebTestClient.resultActionsFor(result); } @Controller private static class SampleController { private final Object[] values; SampleController(Object... values) { this.values = values; } @RequestMapping("/") String handle(Model model) { for (Object value : this.values) { model.addAttribute(value); } return "view"; } @PostMapping("/persons") String create(@Valid Person person, BindingResult result, Model model) { return "view"; } } @ControllerAdvice private static class ModelAttributeAdvice { @ModelAttribute("globalAttrName") String getAttribute() { return "Global Attribute Value"; } } }
{ "content_hash": "9b4ffa8a94944afc2ba34ccd302feafc", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 105, "avg_line_length": 33.916666666666664, "alnum_prop": 0.7626535626535627, "repo_name": "spring-projects/spring-framework", "id": "3794eb416719d9b5b90bcebc4e898bfb356e9c6f", "size": "4691", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/ModelAssertionTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "32003" }, { "name": "CSS", "bytes": "1019" }, { "name": "Dockerfile", "bytes": "257" }, { "name": "FreeMarker", "bytes": "30820" }, { "name": "Groovy", "bytes": "6902" }, { "name": "HTML", "bytes": "1203" }, { "name": "Java", "bytes": "43939386" }, { "name": "JavaScript", "bytes": "280" }, { "name": "Kotlin", "bytes": "571613" }, { "name": "PLpgSQL", "bytes": "305" }, { "name": "Python", "bytes": "254" }, { "name": "Ruby", "bytes": "1060" }, { "name": "Shell", "bytes": "5374" }, { "name": "Smarty", "bytes": "700" }, { "name": "XSLT", "bytes": "2945" } ], "symlink_target": "" }
<?php use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\HttpKernel\Kernel; class AppKernel extends Kernel { public function registerBundles() : array { $bundles = [ new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new JMS\SerializerBundle\JMSSerializerBundle(), new EM\DemoBundle\DemoBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'], true)) { $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(); $bundles[] = new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Nelmio\ApiDocBundle\NelmioApiDocBundle(); $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); } return $bundles; } public function getRootDir() : string { return __DIR__; } public function getCacheDir() : string { return "{$this->getRootDir()}/../var/cache/{$this->getEnvironment()}"; } public function getLogDir() : string { return "{$this->getRootDir()}/../var/logs"; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load("{$this->getRootDir()}/config/config_{$this->getEnvironment()}.yml"); } }
{ "content_hash": "f247822da891b6f46c9a0bac18b50883", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 91, "avg_line_length": 31.586206896551722, "alnum_prop": 0.6402838427947598, "repo_name": "eugene-matvejev/demo-symfony-v3-2", "id": "76c05bc47bb463aa103b16a166c388c086c8242c", "size": "1832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/AppKernel.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3319" }, { "name": "PHP", "bytes": "40516" } ], "symlink_target": "" }
<ul class="items"></ul>
{ "content_hash": "90bdbf1289211b959b7e6b7122650a8f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 23, "avg_line_length": 23, "alnum_prop": 0.6086956521739131, "repo_name": "manjunathkg/generator-bizzns", "id": "ee4656d10fc33599de160f98d7608e674b49d4af", "size": "23", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "templates/javascript/server/resources/admin/view/controls/list.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "698260" }, { "name": "CoffeeScript", "bytes": "10558" }, { "name": "JavaScript", "bytes": "1265127" }, { "name": "Shell", "bytes": "1485" } ], "symlink_target": "" }
using System; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Provider; using Dbg = System.Management.Automation; using Microsoft.PowerShell.Commands.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// Provider that provides access to Registry through cmdlets. This provider /// implements <see cref="System.Management.Automation.Provider.NavigationCmdletProvider"/>, /// <see cref="System.Management.Automation.Provider.IPropertyCmdletProvider"/>, /// <see cref="System.Management.Automation.Provider.IDynamicPropertyCmdletProvider"/>, /// <see cref="System.Management.Automation.Provider.ISecurityDescriptorCmdletProvider"/> /// interfaces. /// </summary> /// <!-- /// /// INSTALLATION: /// /// Type the following at an msh prompt: /// /// new-PSProvider -Path "REG.cmdletprovider" -description "My registry navigation provider" /// /// TO EXERCISE THE PROVIDER: /// /// Get-PSDrive /// set-location HKLM:\software /// get-childitem /// New-PSDrive -PSProvider REG -name HKCR -root HKEY_CLASSES_ROOT\CLSID /// set-location HKCR: /// get-childitem "{0000*" /// /// The CmdletProvider attribute defines the name and capabilities of the provider. /// The first parameter is the default friendly name for the provider. The second parameter /// is the provider name which, along with some assembly information like version, company, etc. /// is used as a fully-qualified provider name which can be used for disambiguation. /// The third parameter states the capabilities of the provider. /// /// --> #if CORECLR // System.Transaction namespace is not in CoreClr. [CmdletProvider(RegistryProvider.ProviderName, ProviderCapabilities.ShouldProcess)] #else [CmdletProvider(RegistryProvider.ProviderName, ProviderCapabilities.ShouldProcess | ProviderCapabilities.Transactions)] #endif [OutputType(typeof(string), ProviderCmdlet = ProviderCmdlet.MoveItemProperty)] [OutputType(typeof(RegistryKey), typeof(string), ProviderCmdlet = ProviderCmdlet.GetChildItem)] [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(System.Security.AccessControl.RegistrySecurity), ProviderCmdlet = ProviderCmdlet.GetAcl)] [OutputType(typeof(Microsoft.Win32.RegistryKey), ProviderCmdlet = ProviderCmdlet.GetChildItem)] [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(RegistryKey), typeof(string), typeof(Int32), typeof(Int64), ProviderCmdlet = ProviderCmdlet.GetItemProperty)] [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.NewItem)] [OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)] [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)] [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PopLocation)] public sealed partial class RegistryProvider : NavigationCmdletProvider, IPropertyCmdletProvider, IDynamicPropertyCmdletProvider, ISecurityDescriptorCmdletProvider { #region tracer /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "ProviderProvider" as the category. /// </summary> [Dbg.TraceSourceAttribute( "RegistryProvider", "The namespace navigation provider for the Windows Registry")] private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("RegistryProvider", "The namespace navigation provider for the Windows Registry"); #endregion tracer /// <summary> /// Gets the name of the provider. /// </summary> public const string ProviderName = "Registry"; #region CmdletProvider overrides /// <summary> /// Gets the alternate item separator character for this provider. /// </summary> public override char AltItemSeparator => ItemSeparator; #endregion #region DriveCmdletProvider overrides /// <summary> /// Verifies that the new drive has a valid root. /// </summary> /// <returns>A PSDriveInfo object.</returns> /// <!-- /// It also givesthe provider an opportunity to return a /// derived class of PSDriveInfo which can contain provider specific /// information about the drive.This may be done for performance /// or reliability reasons or toprovide extra data to all calls /// using the drive /// --> protected override PSDriveInfo NewDrive(PSDriveInfo drive) { if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } if (!ItemExists(drive.Root)) { Exception e = new ArgumentException(RegistryProviderStrings.NewDriveRootDoesNotExist); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, drive.Root)); } return drive; } /// <summary> /// Creates HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER registry drives during provider initialization. /// </summary> /// <remarks> /// After the Start method is called on a provider, the InitializeDefaultDrives /// method is called. This is an opportunity for the provider to /// mount drives that are important to it. For instance, the Active Directory /// provider might mount a drive for the defaultNamingContext if the /// machine is joined to a domain. The FileSystem mounts all drives then available. /// </remarks> protected override Collection<PSDriveInfo> InitializeDefaultDrives() { Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>(); drives.Add( new PSDriveInfo( "HKLM", ProviderInfo, "HKEY_LOCAL_MACHINE", RegistryProviderStrings.HKLMDriveDescription, null)); drives.Add( new PSDriveInfo( "HKCU", ProviderInfo, "HKEY_CURRENT_USER", RegistryProviderStrings.HKCUDriveDescription, null)); return drives; } #endregion DriveCmdletProvider overrides #region ItemCmdletProvider overrides /// <summary> /// Determines if the specified <paramref name="path"/> is syntactically and semantically valid. /// </summary> /// <param name="path"> /// The path to validate. /// </param> /// <returns> /// True if the path is valid, or False otherwise. /// </returns> protected override bool IsValidPath(string path) { bool result = true; do // false loop { // There really aren't any illegal characters or syntactical patterns // to validate, so just ensure that the path starts with one of the hive roots. string root = NormalizePath(path); root = root.TrimStart(StringLiterals.DefaultPathSeparator); root = root.TrimEnd(StringLiterals.DefaultPathSeparator); int pathSeparator = root.IndexOf(StringLiterals.DefaultPathSeparator); if (pathSeparator != -1) { root = root.Substring(0, pathSeparator); } if (string.IsNullOrEmpty(root)) { // An empty path means that we are at the root and should // enumerate the hives. So that is a valid path. result = true; break; } if (GetHiveRoot(root) == null) { result = false; } } while (false); return result; } /// <summary> /// Gets the RegistryKey item at the specified <paramref name="path"/> /// and writes it to the pipeline using the WriteObject method. /// Any non-terminating exceptions are written to the WriteError method. /// </summary> /// <param name="path"> /// The path to the key to retrieve. /// </param> protected override void GetItem(string path) { // Get the registry item IRegistryWrapper result = GetRegkeyForPathWriteIfError(path, false); if (result == null) { return; } // Write out the result WriteRegistryItemObject(result, path); } /// <summary> /// Sets registry values at <paramref name="path "/> to the <paramref name="value"/> specified. /// </summary> /// <param name="path"> /// The path to the item that is to be set. Only registry values can be set using /// this method. /// </param> /// <param name="value"> /// The new value for the registry value. /// </param> protected override void SetItem(string path, object value) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the set item with the user string action = RegistryProviderStrings.SetItemAction; string resourceTemplate = RegistryProviderStrings.SetItemResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, value); if (ShouldProcess(resource, action)) { // Get the registry item IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } // Check to see if the type was specified by the user bool valueSet = false; if (DynamicParameters != null) { RegistryProviderSetItemDynamicParameter dynParams = DynamicParameters as RegistryProviderSetItemDynamicParameter; if (dynParams != null) { try { // Convert the parameter to a RegistryValueKind RegistryValueKind kind = dynParams.Type; key.SetValue(null, value, kind); valueSet = true; } catch (ArgumentException argException) { WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, null)); key.Close(); return; } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } } } if (!valueSet) { try { // Set the value key.SetValue(null, value); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } } // Write out the result object result = value; // Since SetValue can munge the data to a specified // type (RegistryValueKind), retrieve the value again // to output it in the correct form to the user. result = ReadExistingKeyValue(key, null); key.Close(); WriteItemObject(result, path, false); } } /// <summary> /// Gets the dynamic parameters for the SetItem method. /// </summary> /// <param name="path"> /// Ignored. /// </param> /// <param name="value"> /// Ignored. /// </param> /// <returns> /// An instance of the <see cref="Microsoft.PowerShell.Commands.RegistryProviderSetItemDynamicParameter"/> class which /// contains a parameter for the Type. /// </returns> protected override object SetItemDynamicParameters(string path, object value) { return new RegistryProviderSetItemDynamicParameter(); } /// <summary> /// Clears the item at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item that is to be cleared. Only registry values can be cleared using /// this method. /// </param> /// <remarks> /// The registry provider implements this by removing all the values for the specified key. /// The item that is cleared is written to the WriteObject method. /// If the path is to a value, then an ArgumentException is written. /// </remarks> protected override void ClearItem(string path) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the clear item with the user string action = RegistryProviderStrings.ClearItemAction; string resourceTemplate = RegistryProviderStrings.ClearItemResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) { // Get the registry item IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } string[] valueNames; try { // Remove each value valueNames = key.GetValueNames(); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } for (int index = 0; index < valueNames.Length; ++index) { try { key.DeleteValue(valueNames[index]); } catch (System.IO.IOException ioException) { // An exception occurred while trying to delete the value. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to delete the value. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } // Write out the key WriteRegistryItemObject(key, path); } } #endregion ItemCmdletProvider overrides #region ContainerCmdletProvider overrides /// <summary> /// Gets all the child keys and values of the key at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the key to get the child keys of. /// </param>/ /// <param name="recurse"> /// Determines if the call should be recursive. If true, all subkeys of /// the key at the specified path will be written. If false, only the /// immediate children of the key at the specified path will be written. /// </param> /// <param name="depth"> /// Current depth of recursion; special case uint.MaxValue performs full recursion. /// </param> protected override void GetChildItems( string path, bool recurse, uint depth) { s_tracer.WriteLine("recurse = {0}, depth = {1}", recurse, depth); if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (IsHiveContainer(path)) { // If the path is empty or it is / or \, return all the hives foreach (string hiveName in s_hiveNames) { // Making sure to obey the StopProcessing. if (Stopping) { return; } GetItem(hiveName); } } else { // Get the key at the specified path IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); if (key == null) { return; } try { // Get all the subkeys of the specified path string[] keyNames = key.GetSubKeyNames(); key.Close(); if (keyNames != null) { foreach (string subkeyName in keyNames) { // Making sure to obey the StopProcessing. if (Stopping) { return; } if (!string.IsNullOrEmpty(subkeyName)) { string keypath = path; try { // Generate the path for each key name keypath = MakePath(path, subkeyName, childIsLeaf: true); if (!string.IsNullOrEmpty(keypath)) { // Call GetItem to retrieve the RegistryKey object // and write it to the WriteObject method. IRegistryWrapper resultKey = GetRegkeyForPath(keypath, false); if (resultKey != null) { WriteRegistryItemObject(resultKey, keypath); } // Now recurse if necessary if (recurse) { // Limiter for recursion if (depth > 0) // this includes special case 'depth == uint.MaxValue' for unlimited recursion { GetChildItems(keypath, recurse, depth - 1); } } } } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, keypath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); } } } } } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } } /// <summary> /// Gets all the child key and value names of the key at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the key to get the child names from. /// </param> /// <param name="returnContainers"> /// Ignored since the registry provider does not implement filtering. /// Normally, if this parameter is ReturnAllContainers then all subkeys should be /// returned. If it is false, then only those subkeys that match the /// filter should be returned. /// </param> protected override void GetChildNames( string path, ReturnContainers returnContainers) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (path.Length == 0) { // If the path is empty get the names of the hives foreach (string hiveName in s_hiveNames) { // Making sure to obey the StopProcessing. if (Stopping) { return; } WriteItemObject(hiveName, hiveName, true); } } else { // Get the key at the specified path IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); if (key == null) { return; } try { // Get the child key names string[] results = key.GetSubKeyNames(); key.Close(); // Write the child key names to the WriteItemObject method for (int index = 0; index < results.Length; ++index) { // Making sure to obey the StopProcessing. if (Stopping) { return; } string childName = EscapeChildName(results[index]); string childPath = MakePath(path, childName, childIsLeaf: true); WriteItemObject(childName, childPath, true); } } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } } private const string charactersThatNeedEscaping = ".*?[]:"; /// <summary> /// Escapes the characters in the registry key path that are used by globbing and /// path. /// </summary> /// <param name="path"> /// The path to escape. /// </param> /// <returns> /// The escaped path. /// </returns> /// <remarks> /// This method handles surrogate pairs. Please see msdn documentation /// </remarks> private static string EscapeSpecialChars(string path) { StringBuilder result = new StringBuilder(); // Get the text enumerator..this will iterate through each character // the character can be a surrogate pair System.Globalization.TextElementEnumerator textEnumerator = System.Globalization.StringInfo.GetTextElementEnumerator(path); Dbg.Diagnostics.Assert( textEnumerator != null, string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", path)); while (textEnumerator.MoveNext()) { // Iterate through each element and findout whether // any text needs escaping string textElement = textEnumerator.GetTextElement(); // NTRAID#Windows Out of Band Releases-939036-2006/07/12-LeeHolm // A single character can never contain a string of // charactersThatNeedEscaping, so this method does nothing. The fix // is to remove all calls to this escaping code, though, as this escaping // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { // This text element needs espacing result.Append('`'); } result.Append(textElement); } return result.ToString(); } /// <summary> /// Escapes the characters in the registry key name that are used by globbing and /// path. /// </summary> /// <param name="name"> /// The name to escape. /// </param> /// <returns> /// The escaped name. /// </returns> /// <remarks> /// This method handles surrogate pairs. Please see msdn documentation /// </remarks> private static string EscapeChildName(string name) { StringBuilder result = new StringBuilder(); // Get the text enumerator..this will iterate through each character // the character can be a surrogate pair System.Globalization.TextElementEnumerator textEnumerator = System.Globalization.StringInfo.GetTextElementEnumerator(name); Dbg.Diagnostics.Assert( textEnumerator != null, string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", name)); while (textEnumerator.MoveNext()) { // Iterate through each element and findout whether // any text needs escaping string textElement = textEnumerator.GetTextElement(); // NTRAID#Windows Out of Band Releases-939036-2006/07/12-LeeHolm // A single character can never contain a string of // charactersThatNeedEscaping, so this method does nothing. The fix // is to remove all calls to this escaping code, though, as this escaping // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { // This text element needs espacing result.Append('`'); } result.Append(textElement); } return result.ToString(); } /// <summary> /// Renames the key at the specified <paramref name="path"/> to <paramref name="newName"/>. /// </summary> /// <param name="path"> /// The path to the key to rename. /// </param> /// <param name="newName"> /// The new name of the key. /// </param> protected override void RenameItem( string path, string newName) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(newName)) { throw PSTraceSource.NewArgumentException(nameof(newName)); } s_tracer.WriteLine("newName = {0}", newName); string parentPath = GetParentPath(path, null); string newPath = MakePath(parentPath, newName); // Make sure we aren't going to overwrite an existing item bool exists = ItemExists(newPath); if (exists) { Exception e = new ArgumentException(RegistryProviderStrings.RenameItemAlreadyExists); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, newPath)); return; } // Confirm the rename item with the user string action = RegistryProviderStrings.RenameItemAction; string resourceTemplate = RegistryProviderStrings.RenameItemResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, newPath); if (ShouldProcess(resource, action)) { // Implement rename as a move operation MoveRegistryItem(path, newPath); } } /// <summary> /// Creates a new registry key or value at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the new key to create. /// </param> /// <param name="type"> /// The type is ignored because this provider only creates /// registry keys. /// </param> /// <param name="newItem"> /// The newItem is ignored because the provider creates the /// key based on the path. /// </param> protected override void NewItem( string path, string type, object newItem) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the new item with the user string action = RegistryProviderStrings.NewItemAction; string resourceTemplate = RegistryProviderStrings.NewItemResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) { // Check to see if the key already exists IRegistryWrapper resultKey = GetRegkeyForPath(path, false); if (resultKey != null) { if (!Force) { Exception e = new System.IO.IOException(RegistryProviderStrings.KeyAlreadyExists); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.ResourceExists, resultKey)); resultKey.Close(); return; } else { // Remove the existing key before creating the new one resultKey.Close(); RemoveItem(path, false); } } if (Force) { if (!CreateIntermediateKeys(path)) { // We are unable to create Intermediate keys. Just return. return; } } // Get the parent and child portions of the path string parentPath = GetParentPath(path, null); string childName = GetChildName(path); // Get the key at the specified path IRegistryWrapper key = GetRegkeyForPathWriteIfError(parentPath, true); if (key == null) { return; } try { // Create the new subkey IRegistryWrapper newKey = key.CreateSubKey(childName); key.Close(); try { // Set the default key value if the value and type were specified if (newItem != null) { RegistryValueKind kind; if (!ParseKind(type, out kind)) { return; } SetRegistryValue(newKey, string.Empty, newItem, kind, path, false); } } catch (Exception exception) { // The key has been created, but the default value failed to be set. // If possible, just write an error instead of failing the entire operation. if ((exception is ArgumentException) || (exception is InvalidCastException) || (exception is System.IO.IOException) || (exception is System.Security.SecurityException) || (exception is System.UnauthorizedAccessException) || (exception is NotSupportedException)) { ErrorRecord rec = new ErrorRecord( exception, exception.GetType().FullName, ErrorCategory.WriteError, newKey); rec.ErrorDetails = new ErrorDetails(StringUtil.Format(RegistryProviderStrings.KeyCreatedValueFailed, childName)); WriteError(rec); } else throw; } // Write the new key out. WriteRegistryItemObject(newKey, path); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (ArgumentException argException) { WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, path)); } catch (NotSupportedException notSupportedException) { WriteError(new ErrorRecord(notSupportedException, notSupportedException.GetType().FullName, ErrorCategory.InvalidOperation, path)); } } } /// <summary> /// Removes the specified registry key and all sub-keys. /// </summary> /// <param name="path"> /// The path to the key to remove. /// </param> /// <param name="recurse"> /// Ignored. All removes are recursive because the /// registry provider does not support filters. /// </param> protected override void RemoveItem( string path, bool recurse) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } s_tracer.WriteLine("recurse = {0}", recurse); // Get the parent and child portions of the path string parentPath = GetParentPath(path, null); string childName = GetChildName(path); // Get the parent key IRegistryWrapper key = GetRegkeyForPathWriteIfError(parentPath, true); if (key == null) { return; } // Confirm the remove item with the user string action = RegistryProviderStrings.RemoveKeyAction; string resourceTemplate = RegistryProviderStrings.RemoveKeyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) { try { key.DeleteSubKeyTree(childName); } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (NotSupportedException notSupportedException) { WriteError(new ErrorRecord(notSupportedException, notSupportedException.GetType().FullName, ErrorCategory.InvalidOperation, path)); } } key.Close(); } /// <summary> /// Determines if the key at the specified path exists. /// </summary> /// <param name="path"> /// The path to the key to determine if it exists. /// </param> /// <returns> /// True if the key at the specified path exists, false otherwise. /// </returns> protected override bool ItemExists(string path) { bool result = false; if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } try { if (IsHiveContainer(path)) { // an empty path, \ or / are valid because // we will enumerate all the hives result = true; } else { IRegistryWrapper key = GetRegkeyForPath(path, false); if (key != null) { result = true; key.Close(); } } } // Catch known non-terminating exceptions catch (System.IO.IOException) { } // In these cases, the item does exist catch (System.Security.SecurityException) { result = true; } catch (System.UnauthorizedAccessException) { result = true; } return result; } /// <summary> /// Determines if the specified key has subkeys. /// </summary> /// <param name="path"> /// The path to the key to determine if it has sub keys. /// </param> /// <returns> /// True if the specified key has subkeys, false otherwise. /// </returns> protected override bool HasChildItems(string path) { bool result = false; if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } try { if (IsHiveContainer(path)) { // An empty path will enumerate the hives result = s_hiveNames.Length > 0; } else { IRegistryWrapper key = GetRegkeyForPath(path, false); if (key != null) { result = key.SubKeyCount > 0; key.Close(); } } } catch (System.IO.IOException) { result = false; } catch (System.Security.SecurityException) { result = false; } catch (System.UnauthorizedAccessException) { result = false; } return result; } /// <summary> /// Copies the specified registry key to the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path of the registry key to copy. /// </param> /// <param name="destination"> /// The path to copy the key to. /// </param> /// <param name="recurse"> /// If true all subkeys should be copied. If false, only the /// specified key should be copied. /// </param> protected override void CopyItem( string path, string destination, bool recurse) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destination)) { throw PSTraceSource.NewArgumentException(nameof(destination)); } s_tracer.WriteLine("destination = {0}", destination); s_tracer.WriteLine("recurse = {0}", recurse); IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); if (key == null) { return; } try { CopyRegistryKey(key, path, destination, recurse, true, false); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } key.Close(); } private bool CopyRegistryKey( IRegistryWrapper key, string path, string destination, bool recurse, bool streamResult, bool streamFirstOnly) { bool result = true; // Make sure we are not trying to do a recursive copy of a key // to itself or a child of itself. if (recurse) { if (ErrorIfDestinationIsSourceOrChildOfSource(path, destination)) { return false; } } Dbg.Diagnostics.Assert( key != null, "The key should have been validated by the caller"); Dbg.Diagnostics.Assert( !string.IsNullOrEmpty(path), "The path should have been validated by the caller"); Dbg.Diagnostics.Assert( !string.IsNullOrEmpty(destination), "The destination should have been validated by the caller"); s_tracer.WriteLine("destination = {0}", destination); // Get the parent key of the destination // If the destination already exists and is a key, then it becomes // the container of the source. If the key doesn't already exist // the parent of the destination path becomes the container of source. IRegistryWrapper newParentKey = GetRegkeyForPath(destination, true); string destinationName = GetChildName(path); string destinationParent = destination; if (newParentKey == null) { destinationParent = GetParentPath(destination, null); destinationName = GetChildName(destination); newParentKey = GetRegkeyForPathWriteIfError(destinationParent, true); } if (newParentKey == null) { // The key was not found. // An error should have been written by GetRegkeyForPathWriteIfError return false; } string destinationPath = MakePath(destinationParent, destinationName); // Confirm the copy item with the user string action = RegistryProviderStrings.CopyKeyAction; string resourceTemplate = RegistryProviderStrings.CopyKeyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, destination); if (ShouldProcess(resource, action)) { // Create new key under the parent IRegistryWrapper newKey = null; try { newKey = newParentKey.CreateSubKey(destinationName); } catch (NotSupportedException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, destinationName)); } if (newKey != null) { // Now copy all the properties from the source to the destination string[] valueNames = key.GetValueNames(); for (int index = 0; index < valueNames.Length; ++index) { // Making sure to obey the StopProcessing. if (Stopping) { newParentKey.Close(); newKey.Close(); return false; } newKey.SetValue( valueNames[index], key.GetValue(valueNames[index], null, RegistryValueOptions.DoNotExpandEnvironmentNames), key.GetValueKind(valueNames[index])); } if (streamResult) { // Write out the key that was copied WriteRegistryItemObject(newKey, destinationPath); if (streamFirstOnly) { streamResult = false; } } } } newParentKey.Close(); if (recurse) { // Copy all the subkeys string[] subkeyNames = key.GetSubKeyNames(); for (int keyIndex = 0; keyIndex < subkeyNames.Length; ++keyIndex) { // Making sure to obey the StopProcessing. if (Stopping) { return false; } // Make the new path under the copy path. string subKeyPath = MakePath(path, subkeyNames[keyIndex]); string newSubKeyPath = MakePath(destinationPath, subkeyNames[keyIndex]); IRegistryWrapper childKey = GetRegkeyForPath(subKeyPath, false); bool subtreeResult = CopyRegistryKey(childKey, subKeyPath, newSubKeyPath, recurse, streamResult, streamFirstOnly); childKey.Close(); if (!subtreeResult) { result = subtreeResult; } } } return result; } private bool ErrorIfDestinationIsSourceOrChildOfSource( string sourcePath, string destinationPath) { s_tracer.WriteLine("destinationPath = {0}", destinationPath); // Note the paths have already been normalized so case-insensitive // comparisons should be sufficient bool result = false; while (true) { // See if the paths are equal if (string.Equals( sourcePath, destinationPath, StringComparison.OrdinalIgnoreCase)) { result = true; break; } string newDestinationPath = GetParentPath(destinationPath, null); if (string.IsNullOrEmpty(newDestinationPath)) { // We reached the root so the destination must not be a child // of the source break; } if (string.Equals( newDestinationPath, destinationPath, StringComparison.OrdinalIgnoreCase)) { // We reached the root so the destination must not be a child // of the source break; } destinationPath = newDestinationPath; } if (result) { Exception e = new ArgumentException( RegistryProviderStrings.DestinationChildOfSource); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, destinationPath)); } return result; } #endregion ContainerCmdletProvider overrides #region NavigationCmdletProvider overrides /// <summary> /// Determines if the key at the specified <paramref name="path"/> is a container. /// </summary> /// <param name="path"> /// The path to a key. /// </param> /// <returns> /// Since all registry keys are containers this method just checks /// to see if the key exists and returns true if it is does or /// false otherwise. /// </returns> protected override bool IsItemContainer(string path) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } bool result = false; if (IsHiveContainer(path)) { result = true; } else { try { IRegistryWrapper key = GetRegkeyForPath(path, false); if (key != null) { // All registry keys can be containers. Values are considered // properties key.Close(); result = true; } } // Catch known exceptions that are not terminating catch (System.IO.IOException ioException) { WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (UnauthorizedAccessException unauthorizedAccess) { WriteError(new ErrorRecord(unauthorizedAccess, unauthorizedAccess.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } return result; } /// <summary> /// Moves the specified key. /// </summary> /// <param name="path"> /// The path of the key to move. /// </param> /// <param name="destination"> /// The path to move the key to. /// </param> protected override void MoveItem( string path, string destination) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destination)) { throw PSTraceSource.NewArgumentException(nameof(destination)); } s_tracer.WriteLine("destination = {0}", destination); // Confirm the rename item with the user string action = RegistryProviderStrings.MoveItemAction; string resourceTemplate = RegistryProviderStrings.MoveItemResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, destination); if (ShouldProcess(resource, action)) { MoveRegistryItem(path, destination); } } private void MoveRegistryItem(string path, string destination) { // Implement move by copying the item and then removing it. // The copy will write the item to the pipeline IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); if (key == null) { return; } bool continueWithRemove = false; try { continueWithRemove = CopyRegistryKey(key, path, destination, true, true, true); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } key.Close(); string sourceParent = GetParentPath(path, null); // If the destination is the same container as the source container don't do remove // the source item because the source and destination are the same. if (string.Equals(sourceParent, destination, StringComparison.OrdinalIgnoreCase)) { continueWithRemove = false; } if (continueWithRemove) { try { RemoveItem(path, true); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } } } #endregion NavigationCmdletProvider overrides #region IPropertyCmdletProvider /// <summary> /// Gets the properties of the item specified by the <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item to retrieve properties from. /// </param> /// <param name="providerSpecificPickList"> /// A list of properties that should be retrieved. If this parameter is null /// or empty, all properties should be retrieved. /// </param> /// <returns> /// Nothing. An instance of PSObject representing the properties that were retrieved /// should be passed to the WriteObject() method. /// </returns> public void GetProperty( string path, Collection<string> providerSpecificPickList) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } // get a set of matching properties on the key itself IRegistryWrapper key; Collection<string> filteredPropertyCollection; GetFilteredRegistryKeyProperties(path, providerSpecificPickList, true, false, out key, out filteredPropertyCollection); if (key == null) { return; } bool valueAdded = false; PSObject propertyResults = new PSObject(); foreach (string valueName in filteredPropertyCollection) { string notePropertyName = valueName; if (string.IsNullOrEmpty(valueName)) { // If the value name is empty then using "(default)" // as the property name when adding the note, as // PSObject does not allow an empty propertyName notePropertyName = LocalizedDefaultToken; } propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); valueAdded = true; } key.Close(); if (valueAdded) { WritePropertyObject(propertyResults, path); } } /// <summary> /// Sets the specified properties of the item at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item to set the properties on. /// </param> /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// </param> /// <returns> /// Nothing. An instance of PSObject representing the properties that were set /// should be passed to the WriteObject() method. /// </returns> public void SetProperty( string path, PSObject propertyValue) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } if (propertyValue == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyValue)); } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } RegistryValueKind kind = RegistryValueKind.Unknown; // Get the kind of the value using the dynamic parameters if (DynamicParameters != null) { RegistryProviderSetItemDynamicParameter dynParams = DynamicParameters as RegistryProviderSetItemDynamicParameter; if (dynParams != null) { kind = dynParams.Type; } } string action = RegistryProviderStrings.SetPropertyAction; string resourceTemplate = RegistryProviderStrings.SetPropertyResourceTemplate; foreach (PSMemberInfo property in propertyValue.Properties) { object newPropertyValue = property.Value; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, property.Name); if (ShouldProcess(resource, action)) { try { SetRegistryValue(key, property.Name, newPropertyValue, kind, path); } catch (InvalidCastException invalidCast) { WriteError(new ErrorRecord(invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, property.Name)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } } } key.Close(); } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// get-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="propertyValue"> /// A PSObject which contains a collection of the name, type, value /// of the properties to be set. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object SetPropertyDynamicParameters( string path, PSObject propertyValue) { return new RegistryProviderSetItemDynamicParameter(); } /// <summary> /// Clears a property of the item at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item on which to clear the property. /// </param> /// <param name="propertyToClear"> /// The name of the property to clear. /// </param> public void ClearProperty( string path, Collection<string> propertyToClear) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } // get a set of matching properties on the key itself IRegistryWrapper key; Collection<string> filteredPropertyCollection; GetFilteredRegistryKeyProperties(path, propertyToClear, false, true, out key, out filteredPropertyCollection); if (key == null) { return; } string action = RegistryProviderStrings.ClearPropertyAction; string resourceTemplate = RegistryProviderStrings.ClearPropertyResourceTemplate; bool addedOnce = false; PSObject result = new PSObject(); foreach (string valueName in filteredPropertyCollection) { string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, valueName); if (ShouldProcess(resource, action)) { // reset the value of the property to its default value object defaultValue = ResetRegistryKeyValue(key, valueName); string propertyNameToAdd = valueName; if (string.IsNullOrEmpty(valueName)) { propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); addedOnce = true; } } key.Close(); if (addedOnce) { WritePropertyObject(result, path); } } #region Unimplemented methods /// <summary> /// Gives the provider a chance to attach additional parameters to the /// get-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="providerSpecificPickList"> /// A list of properties that should be retrieved. If this parameter is null /// or empty, all properties should be retrieved. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object GetPropertyDynamicParameters( string path, Collection<string> providerSpecificPickList) { return null; } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// clear-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="propertyToClear"> /// The name of the property to clear. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object ClearPropertyDynamicParameters( string path, Collection<string> propertyToClear) { return null; } #endregion Unimplemented methods #endregion IPropertyCmdletProvider #region IDynamicPropertyCmdletProvider /// <summary> /// Creates a new property on the specified item. /// </summary> /// <param name="path"> /// The path to the item on which the new property should be created. /// </param> /// <param name="propertyName"> /// The name of the property that should be created. /// </param> /// <param name="type"> /// The type of the property that should be created. /// </param> /// <param name="value"> /// The new value of the property that should be created. /// </param> /// <returns> /// Nothing. A PSObject representing the property that was created should /// be passed to the WriteObject() method. /// </returns> /// <!-- /// Implement this method when you are providing access to a data store /// that allows dynamic creation of properties. /// --> public void NewProperty( string path, string propertyName, string type, object value) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } // Confirm the set item with the user string action = RegistryProviderStrings.NewPropertyAction; string resourceTemplate = RegistryProviderStrings.NewPropertyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, propertyName); if (ShouldProcess(resource, action)) { // convert the type to a RegistryValueKind RegistryValueKind kind; if (!ParseKind(type, out kind)) { key.Close(); return; } try { // Check to see if the property already exists // or overwrite if frce is on if (Force || key.GetValue(propertyName) == null) { // Create the value SetRegistryValue(key, propertyName, value, kind, path); } else { // The property already exists System.IO.IOException e = new System.IO.IOException( RegistryProviderStrings.PropertyAlreadyExists); WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.ResourceExists, path)); key.Close(); return; } } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (InvalidCastException invalidCast) { WriteError(new ErrorRecord(invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } key.Close(); } /// <summary> /// Removes a property on the item specified by the path. /// </summary> /// <param name="path"> /// The path to the item on which the property should be removed. /// </param> /// <param name="propertyName"> /// The name of the property to be removed. /// </param> /// <remarks> /// Implement this method when you are providing access to a data store /// that allows dynamic removal of properties. /// </remarks> public void RemoveProperty( string path, string propertyName) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } WildcardPattern propertyNamePattern = WildcardPattern.Get(propertyName, WildcardOptions.IgnoreCase); bool hadAMatch = false; foreach (string valueName in key.GetValueNames()) { if ( ((!Context.SuppressWildcardExpansion) && (!propertyNamePattern.IsMatch(valueName))) || (Context.SuppressWildcardExpansion && (!string.Equals(valueName, propertyName, StringComparison.OrdinalIgnoreCase)))) { continue; } hadAMatch = true; // Confirm the set item with the user string action = RegistryProviderStrings.RemovePropertyAction; string resourceTemplate = RegistryProviderStrings.RemovePropertyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, valueName); if (ShouldProcess(resource, action)) { string propertyNameToRemove = GetPropertyName(valueName); try { // Remove the value key.DeleteValue(propertyNameToRemove); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, propertyNameToRemove)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); } } } key.Close(); WriteErrorIfPerfectMatchNotFound(hadAMatch, path, propertyName); } /// <summary> /// Renames a property of the item at the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item on which to rename the property. /// </param> /// <param name="sourceProperty"> /// The property to rename. /// </param> /// <param name="destinationProperty"> /// The new name of the property. /// </param> /// <returns> /// Nothing. A PSObject that represents the property that was renamed should be /// passed to the WriteObject() method. /// </returns> public void RenameProperty( string path, string sourceProperty, string destinationProperty) { if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } // Confirm the set item with the user string action = RegistryProviderStrings.RenamePropertyAction; string resourceTemplate = RegistryProviderStrings.RenamePropertyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, path, sourceProperty, destinationProperty); if (ShouldProcess(resource, action)) { try { MoveProperty(key, key, sourceProperty, destinationProperty); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } key.Close(); } /// <summary> /// Copies a property of the item at the specified <paramref name="path"/> to a new property on the /// destination <paramref name="path"/>. /// </summary> /// <param name="sourcePath"> /// The path to the item on which to copy the property. /// </param> /// <param name="sourceProperty"> /// The name of the property to copy. /// </param> /// <param name="destinationPath"> /// The path to the item on which to copy the property to. /// </param> /// <param name="destinationProperty"> /// The destination property to copy to. /// </param> /// <returns> /// Nothing. A PSObject that represents the property that was copied should be /// passed to the WriteObject() method. /// </returns> public void CopyProperty( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (!CheckOperationNotAllowedOnHiveContainer(sourcePath, destinationPath)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(sourcePath, false); if (key == null) { return; } IRegistryWrapper destinationKey = GetRegkeyForPathWriteIfError(destinationPath, true); if (destinationKey == null) { return; } // Confirm the set item with the user string action = RegistryProviderStrings.CopyPropertyAction; string resourceTemplate = RegistryProviderStrings.CopyPropertyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, sourcePath, sourceProperty, destinationPath, destinationProperty); if (ShouldProcess(resource, action)) { try { CopyProperty(key, destinationKey, sourceProperty, destinationProperty, true); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } } key.Close(); } /// <summary> /// Moves a property on an item specified by <paramref name="sourcePath"/>. /// </summary> /// <param name="sourcePath"> /// The path to the item on which to move the property. /// </param> /// <param name="sourceProperty"> /// The name of the property to move. /// </param> /// <param name="destinationPath"> /// The path to the item on which to move the property to. /// </param> /// <param name="destinationProperty"> /// The destination property to move to. /// </param> /// <returns> /// Nothing. A PSObject that represents the property that was moved should be /// passed to the WriteObject() method. /// </returns> public void MoveProperty( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (!CheckOperationNotAllowedOnHiveContainer(sourcePath, destinationPath)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(sourcePath, true); if (key == null) { return; } IRegistryWrapper destinationKey = GetRegkeyForPathWriteIfError(destinationPath, true); if (destinationKey == null) { return; } // Confirm the set item with the user string action = RegistryProviderStrings.MovePropertyAction; string resourceTemplate = RegistryProviderStrings.MovePropertyResourceTemplate; string resource = string.Format( Host.CurrentCulture, resourceTemplate, sourcePath, sourceProperty, destinationPath, destinationProperty); if (ShouldProcess(resource, action)) { try { MoveProperty(key, destinationKey, sourceProperty, destinationProperty); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } } key.Close(); destinationKey.Close(); } /// <summary> /// Gets the parent path of the given <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to get the parent of. /// </param> /// <param name="root"> /// The root of the drive. /// </param> /// <returns> /// The parent path of the given path. /// </returns> /// <remarks> /// Since the base class implementation of GetParentPath of HKLM:\foo would return /// HKLM: we must add the \ back on. /// </remarks> protected override string GetParentPath(string path, string root) { string parentPath = base.GetParentPath(path, root); // If the main path existed, we must do a semantic analysis // to find the parent -- since path elements may contain // path delimiters. We only need to do this comparison // if the base implementation returns something in our namespace. if (!string.Equals(parentPath, root, StringComparison.OrdinalIgnoreCase)) { bool originalPathExists = ItemExists(path); bool originalPathExistsWithRoot = false; // This is an expensive test, only do it if we need to. if (!originalPathExists) originalPathExistsWithRoot = ItemExists(MakePath(root, path)); if ((!string.IsNullOrEmpty(parentPath)) && (originalPathExists || originalPathExistsWithRoot)) { string parentPathToTest = parentPath; do { parentPathToTest = parentPath; if (originalPathExistsWithRoot) parentPathToTest = MakePath(root, parentPath); if (ItemExists(parentPathToTest)) break; parentPath = base.GetParentPath(parentPath, root); } while (!string.IsNullOrEmpty(parentPath)); } } return EnsureDriveIsRooted(parentPath); } /// <summary> /// Gets the child name for the given <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to get the leaf element of. /// </param> /// <returns> /// The leaf element of the given path. /// </returns> /// <remarks> /// Since the base class implementation of GetChildName will return /// normalized paths (with \), we must change them to forward slashes.. /// </remarks> protected override string GetChildName(string path) { string childName = base.GetChildName(path); return childName.Replace('\\', '/'); } private static string EnsureDriveIsRooted(string path) { string result = path; // Find the drive separator int index = path.IndexOf(':'); if (index != -1) { // if the drive separator is the end of the path, add // the root path separator back if (index + 1 == path.Length) { result = path + StringLiterals.DefaultPathSeparator; } } return result; } #region Unimplemented methods /// <summary> /// Gives the provider a chance to attach additional parameters to the /// new-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="propertyName"> /// The name of the property that should be created. /// </param> /// <param name="type"> /// The type of the property that should be created. /// </param> /// <param name="value"> /// The new value of the property that should be created. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object NewPropertyDynamicParameters( string path, string propertyName, string type, object value) { return null; } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// remove-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="propertyName"> /// The name of the property that should be removed. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object RemovePropertyDynamicParameters( string path, string propertyName) { return null; } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// rename-itemproperty cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="sourceProperty"> /// The property to rename. /// </param> /// <param name="destinationProperty"> /// The new name of the property. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object RenamePropertyDynamicParameters( string path, string sourceProperty, string destinationProperty) { return null; } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// copy-itemproperty cmdlet. /// </summary> /// <param name="sourcePath"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="sourceProperty"> /// The name of the property to copy. /// </param> /// <param name="destinationPath"> /// The path to the item on which to copy the property to. /// </param> /// <param name="destinationProperty"> /// The destination property to copy to. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object CopyPropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { return null; } /// <summary> /// Gives the provider a chance to attach additional parameters to the /// move-itemproperty cmdlet. /// </summary> /// <param name="sourcePath"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="sourceProperty"> /// The name of the property to copy. /// </param> /// <param name="destinationPath"> /// The path to the item on which to copy the property to. /// </param> /// <param name="destinationProperty"> /// The destination property to copy to. /// </param> /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> public object MovePropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { return null; } #endregion Unimplemented methods #endregion IDynamicPropertyCmdletProvider #region Private members private void CopyProperty( IRegistryWrapper sourceKey, IRegistryWrapper destinationKey, string sourceProperty, string destinationProperty, bool writeOnSuccess) { string realSourceProperty = GetPropertyName(sourceProperty); string realDestinationProperty = GetPropertyName(destinationProperty); object sourceValue = sourceKey.GetValue(sourceProperty); RegistryValueKind sourceKind = sourceKey.GetValueKind(sourceProperty); destinationKey.SetValue(destinationProperty, sourceValue, sourceKind); if (writeOnSuccess) { WriteWrappedPropertyObject(sourceValue, realSourceProperty, sourceKey.Name); } } private void MoveProperty( IRegistryWrapper sourceKey, IRegistryWrapper destinationKey, string sourceProperty, string destinationProperty) { string realSourceProperty = GetPropertyName(sourceProperty); string realDestinationProperty = GetPropertyName(destinationProperty); try { // If sourceProperty and destinationProperty happens to be the same // then we shouldn't remove the property bool continueWithRemove = true; if (string.Equals(sourceKey.Name, destinationKey.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(realSourceProperty, realDestinationProperty, StringComparison.OrdinalIgnoreCase)) { continueWithRemove = false; } // Move is implemented by copying the value and then deleting the original // Copy property will throw an exception if it fails CopyProperty( sourceKey, destinationKey, realSourceProperty, realDestinationProperty, false); // Delete sourceproperty only if it is not same as destination property if (continueWithRemove) { sourceKey.DeleteValue(realSourceProperty); } object newValue = destinationKey.GetValue(realDestinationProperty); WriteWrappedPropertyObject(newValue, destinationProperty, destinationKey.Name); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourceKey.Name)); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); return; } } /// <summary> /// Converts all / in the path to \ /// </summary> /// <param name="path"> /// The path to normalize. /// </param> /// <returns> /// The path with all / normalized to \ /// </returns> private string NormalizePath(string path) { string result = path; if (!string.IsNullOrEmpty(path)) { result = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); // Remove relative path tokens if (HasRelativePathTokens(path)) { result = NormalizeRelativePath(result, null); } } return result; } private static bool HasRelativePathTokens(string path) { return ( path.StartsWith('\\') || path.Contains("\\.\\") || path.Contains("\\..\\") || path.EndsWith("\\..", StringComparison.OrdinalIgnoreCase) || path.EndsWith("\\.", StringComparison.OrdinalIgnoreCase) || path.StartsWith("..\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith('~')); } private void GetFilteredRegistryKeyProperties(string path, Collection<string> propertyNames, bool getAll, bool writeAccess, out IRegistryWrapper key, out Collection<string> filteredCollection) { bool expandAll = false; if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } filteredCollection = new Collection<string>(); key = GetRegkeyForPathWriteIfError(path, writeAccess); if (key == null) { return; } // If properties were not specified, get all the values if (propertyNames == null) { propertyNames = new Collection<string>(); } if (propertyNames.Count == 0 && getAll) { propertyNames.Add("*"); expandAll = true; } string[] valueNames; try { valueNames = key.GetValueNames(); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } foreach (string requestedValueName in propertyNames) { WildcardPattern valueNameMatcher = WildcardPattern.Get( requestedValueName, WildcardOptions.IgnoreCase); bool hadAMatch = false; foreach (string valueName in valueNames) { string valueNameToMatch = valueName; // Need to convert the default value name to "(default)" if (string.IsNullOrEmpty(valueName)) { // Only do the conversion if the caller isn't asking for // "" or null. if (!string.IsNullOrEmpty(requestedValueName)) { valueNameToMatch = LocalizedDefaultToken; } } if ( expandAll || ((!Context.SuppressWildcardExpansion) && (valueNameMatcher.IsMatch(valueNameToMatch))) || ((Context.SuppressWildcardExpansion) && (string.Equals(valueNameToMatch, requestedValueName, StringComparison.OrdinalIgnoreCase)))) { if (string.IsNullOrEmpty(valueNameToMatch)) { // If the value name is empty then using "(default)" // as the property name when adding the note, as // PSObject does not allow an empty propertyName valueNameToMatch = LocalizedDefaultToken; } hadAMatch = true; filteredCollection.Add(valueName); } } WriteErrorIfPerfectMatchNotFound(hadAMatch, path, requestedValueName); } } private void WriteErrorIfPerfectMatchNotFound(bool hadAMatch, string path, string requestedValueName) { if (!hadAMatch && !WildcardPattern.ContainsWildcardCharacters(requestedValueName)) { // we did not have any match and the requested name did not have // any globbing characters (perfect match attempted) // we need to write an error string formatString = RegistryProviderStrings.PropertyNotAtPath; Exception e = new PSArgumentException( string.Format( CultureInfo.CurrentCulture, formatString, requestedValueName, path), (Exception)null); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, requestedValueName)); } } /// <summary> /// IT resets the a registry key value to its default. /// </summary> /// <param name="key">Key whose value has to be reset.</param> /// <param name="valueName">Name of the value to reset.</param> /// <returns>Default value the key was set to.</returns> private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) { RegistryValueKind valueKind = key.GetValueKind(valueName); object defaultValue = null; switch (valueKind) { // NOTICE: we assume that an unknown type is treated as // the same as a binary blob case RegistryValueKind.Binary: case RegistryValueKind.Unknown: { defaultValue = Array.Empty<byte>(); } break; case RegistryValueKind.DWord: { defaultValue = (int)0; } break; case RegistryValueKind.ExpandString: case RegistryValueKind.String: { defaultValue = string.Empty; } break; case RegistryValueKind.MultiString: { defaultValue = Array.Empty<string>(); } break; case RegistryValueKind.QWord: { defaultValue = (long)0; } break; } try { key.SetValue(valueName, defaultValue, valueKind); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, valueName)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, valueName)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, valueName)); } return defaultValue; } /// <summary> /// Checks if the given path is the top container path (the one containing the hives) /// </summary> /// <param name="path"> /// path to check /// </param> /// <returns> /// true if the path is empty, a \ or a /, else false /// </returns> private static bool IsHiveContainer(string path) { bool result = false; if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(path) || string.Equals(path, "\\", StringComparison.OrdinalIgnoreCase) || string.Equals(path, "/", StringComparison.OrdinalIgnoreCase)) { result = true; } return result; } /// <summary> /// Checks the container. if the container is the hive container (Registry::\) /// it throws an exception. /// </summary> /// <param name="path">Path to check.</param> /// <returns>False if the operation is not allowed.</returns> private bool CheckOperationNotAllowedOnHiveContainer(string path) { if (IsHiveContainer(path)) { string message = RegistryProviderStrings.ContainerInvalidOperationTemplate; InvalidOperationException ex = new InvalidOperationException(message); WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, path)); return false; } return true; } /// <summary> /// Checks the container. if the container is the hive container (Registry::\) /// it throws an exception. /// </summary> /// <param name="sourcePath">Source path to check.</param> /// <param name="destinationPath">Destination path to check.</param> private bool CheckOperationNotAllowedOnHiveContainer(string sourcePath, string destinationPath) { if (IsHiveContainer(sourcePath)) { string message = RegistryProviderStrings.SourceContainerInvalidOperationTemplate; InvalidOperationException ex = new InvalidOperationException(message); WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, sourcePath)); return false; } if (IsHiveContainer(destinationPath)) { string message = RegistryProviderStrings.DestinationContainerInvalidOperationTemplate; InvalidOperationException ex = new InvalidOperationException(message); WriteError(new ErrorRecord(ex, "InvalidContainer", ErrorCategory.InvalidArgument, destinationPath)); return false; } return true; } /// <summary> /// Gets the appropriate hive root name for the specified path. /// </summary> /// <param name="path"> /// The path to get the hive root name from. /// </param> /// <returns> /// A registry key for the hive root specified by the path. /// </returns> private IRegistryWrapper GetHiveRoot(string path) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } if (TransactionAvailable()) { for (int k = 0; k < s_wellKnownHivesTx.Length; k++) { if (string.Equals(path, s_hiveNames[k], StringComparison.OrdinalIgnoreCase) || string.Equals(path, s_hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) { using (CurrentPSTransaction) { return new TransactedRegistryWrapper(s_wellKnownHivesTx[k], this); } } } } else { for (int k = 0; k < s_wellKnownHives.Length; k++) { if (string.Equals(path, s_hiveNames[k], StringComparison.OrdinalIgnoreCase) || string.Equals(path, s_hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) return new RegistryWrapper(s_wellKnownHives[k]); } } return null; } /// <summary> /// Creates the parent for the keypath specified by <paramref name="path"/>. /// </summary> /// <param name="path">RegistryKey path.</param> /// <returns> /// True if key is created or already exist,False otherwise. /// </returns> /// <remarks> /// This method wont call ShouldProcess. Callers should do this before /// calling this method. /// </remarks> private bool CreateIntermediateKeys(string path) { bool result = false; // Check input. if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException(nameof(path)); } try { // 1. Normalize path ( for "//","." etc ) // 2. Open the root // 3. Create subkey path = NormalizePath(path); int index = path.IndexOf('\\'); if (index == 0) { // The user may precede a path with \ path = path.Substring(1); index = path.IndexOf('\\'); } if (index == -1) { // we are at root..there is no subkey to create // just return return true; } string keyRoot = path.Substring(0, index); // NormalizePath will trim "\" at the end. So there is always something // after index. Asserting just in case.. Dbg.Diagnostics.Assert(index + 1 < path.Length, "Bad path"); string remainingPath = path.Substring(index + 1); IRegistryWrapper rootKey = GetHiveRoot(keyRoot); if (remainingPath.Length == 0 || rootKey == null) { throw PSTraceSource.NewArgumentException(nameof(path)); } // Create new subkey..and close IRegistryWrapper subKey = rootKey.CreateSubKey(remainingPath); if (subKey != null) { subKey.Close(); } else { // SubKey is null // Unable to create intermediate keys throw PSTraceSource.NewArgumentException(nameof(path)); } result = true; } catch (ArgumentException argumentException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } catch (NotSupportedException notSupportedException) { WriteError(new ErrorRecord(notSupportedException, notSupportedException.GetType().FullName, ErrorCategory.InvalidOperation, path)); } return result; } /// <summary> /// A private helper method that retrieves a RegistryKey for the specified /// path and if an exception is thrown retrieving the key, an error is written /// and null is returned. /// </summary> /// <param name="path"> /// The path to the registry key to retrieve. /// </param> /// <param name="writeAccess"> /// If write access is required the key then this should be true. If false, /// the key will be opened with read access only. /// </param> /// <returns> /// The RegistryKey associated with the specified path. /// </returns> private IRegistryWrapper GetRegkeyForPathWriteIfError(string path, bool writeAccess) { IRegistryWrapper result = null; try { result = GetRegkeyForPath(path, writeAccess); if (result == null) { // The key was not found, write out an error. ArgumentException exception = new ArgumentException( RegistryProviderStrings.KeyDoesNotExist); WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); return null; } } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } return result; } /// <summary> /// A private helper method that retrieves a RegistryKey for the specified /// path. /// </summary> /// <param name="path"> /// The path to the registry key to retrieve. /// </param> /// <param name="writeAccess"> /// If write access is required the key then this should be true. If false, /// the key will be opened with read access only. /// </param> /// <returns> /// The RegistryKey associated with the specified path. /// </returns> private IRegistryWrapper GetRegkeyForPath(string path, bool writeAccess) { if (string.IsNullOrEmpty(path)) { // The key was not found, write out an error. ArgumentException exception = new ArgumentException( RegistryProviderStrings.KeyDoesNotExist); throw exception; } // Making sure to obey the StopProcessing. if (Stopping) { return null; } s_tracer.WriteLine("writeAccess = {0}", writeAccess); IRegistryWrapper result = null; do // false loop { int index = path.IndexOf('\\'); if (index == 0) { // The user may proceed a path with \ path = path.Substring(1); index = path.IndexOf('\\'); } if (index == -1) { result = GetHiveRoot(path); break; } string keyRoot = path.Substring(0, index); string remainingPath = path.Substring(index + 1); IRegistryWrapper resultRoot = GetHiveRoot(keyRoot); if (remainingPath.Length == 0 || resultRoot == null) { result = resultRoot; break; } try { result = resultRoot.OpenSubKey(remainingPath, writeAccess); } catch (NotSupportedException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path)); } // If we could not open the key, see if we can find the subkey that matches. if (result == null) { IRegistryWrapper currentKey = resultRoot; IRegistryWrapper tempKey = null; // While there is still more to process while (!string.IsNullOrEmpty(remainingPath)) { bool foundSubkey = false; foreach (string subKey in currentKey.GetSubKeyNames()) { string normalizedSubkey = subKey; // Check if the remaining path starts with the subkey name if (!remainingPath.Equals(subKey, StringComparison.OrdinalIgnoreCase) && !remainingPath.StartsWith(subKey + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) { // Actually normalize the subkey and then check again normalizedSubkey = NormalizePath(subKey); if (!remainingPath.Equals(normalizedSubkey, StringComparison.OrdinalIgnoreCase) && !remainingPath.StartsWith(normalizedSubkey + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) { continue; } } tempKey = currentKey.OpenSubKey(subKey, writeAccess); currentKey.Close(); currentKey = tempKey; foundSubkey = true; remainingPath = remainingPath.Equals(normalizedSubkey, StringComparison.OrdinalIgnoreCase) ? string.Empty : remainingPath.Substring((normalizedSubkey + StringLiterals.DefaultPathSeparator).Length); break; } if (!foundSubkey) { return null; } } return currentKey; } } while (false); return result; } // NB: The HKEY_DYN_DATA hive is left out of the following lists because // it is only available on Win98/ME and we do not support that platform. private static readonly string[] s_hiveNames = new string[] { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER", "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_USERS", "HKEY_PERFORMANCE_DATA" }; private static readonly string[] s_hiveShortNames = new string[] { "HKLM", "HKCU", "HKCR", "HKCC", "HKU", "HKPD" }; private static readonly RegistryKey[] s_wellKnownHives = new RegistryKey[] { Registry.LocalMachine, Registry.CurrentUser, Registry.ClassesRoot, Registry.CurrentConfig, Registry.Users, Registry.PerformanceData }; private static readonly TransactedRegistryKey[] s_wellKnownHivesTx = new TransactedRegistryKey[] { TransactedRegistry.LocalMachine, TransactedRegistry.CurrentUser, TransactedRegistry.ClassesRoot, TransactedRegistry.CurrentConfig, TransactedRegistry.Users }; /// <summary> /// Sets or creates a registry value on a key. /// </summary> /// <param name="key"> /// The key to set or create the value on. /// </param> /// <param name="propertyName"> /// The name of the value to set or create. /// </param> /// <param name="value"> /// The new data for the value. /// </param> /// <param name="kind"> /// The RegistryValueKind of the value. /// </param> /// <param name="path"> /// The path to the key that the value is being set on. /// </param> private void SetRegistryValue(IRegistryWrapper key, string propertyName, object value, RegistryValueKind kind, string path) { SetRegistryValue(key, propertyName, value, kind, path, true); } /// <summary> /// Sets or creates a registry value on a key. /// </summary> /// <param name="key"> /// The key to set or create the value on. /// </param> /// <param name="propertyName"> /// The name of the value to set or create. /// </param> /// <param name="value"> /// The new data for the value. /// </param> /// <param name="kind"> /// The RegistryValueKind of the value. /// </param> /// <param name="path"> /// The path to the key that the value is being set on. /// </param> /// <param name="writeResult"> /// If true, the value that is set will be written out. /// </param> private void SetRegistryValue( IRegistryWrapper key, string propertyName, object value, RegistryValueKind kind, string path, bool writeResult) { Dbg.Diagnostics.Assert( key != null, "Caller should have verified key"); string propertyNameToSet = GetPropertyName(propertyName); RegistryValueKind existingKind = RegistryValueKind.Unknown; // If user does not specify a kind: get the valuekind if the property // already exists if (kind == RegistryValueKind.Unknown) { existingKind = GetValueKindForProperty(key, propertyNameToSet); } // try to do a conversion based on the existing kind, if we // were able to retrieve one if (existingKind != RegistryValueKind.Unknown) { try { value = ConvertValueToKind(value, existingKind); kind = existingKind; } catch (InvalidCastException) { // failed attempt, we reset to unknown to let the // default conversion process take over existingKind = RegistryValueKind.Unknown; } } // set the kind as defined by the user if (existingKind == RegistryValueKind.Unknown) { // we use to kind passed in, either because we had // a valid one or because we failed to retrieve an existing kind to match if (kind == RegistryValueKind.Unknown) { // set the kind based on value if (value != null) { kind = GetValueKindFromObject(value); } else { // if no value and unknown kind, then default to empty string kind = RegistryValueKind.String; } } value = ConvertValueToKind(value, kind); } key.SetValue(propertyNameToSet, value, kind); if (writeResult) { // Now write out the value object newValue = key.GetValue(propertyNameToSet); WriteWrappedPropertyObject(newValue, propertyName, path); } } /// <summary> /// Helper to wrap property values when sent to the pipeline into an PSObject; /// it adds the name of the property as a note. /// </summary> /// <param name="value">The property to be written.</param> /// <param name="propertyName">Name of the property being written.</param> /// <param name="path">The path of the item being written.</param> private void WriteWrappedPropertyObject(object value, string propertyName, string path) { PSObject result = new PSObject(); string propertyNameToAdd = propertyName; if (string.IsNullOrEmpty(propertyName)) { propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, value)); WritePropertyObject(result, path); } /// <summary> /// Uses LanguagePrimitives.ConvertTo to convert the value to the type that is appropriate /// for the specified RegistryValueKind. /// </summary> /// <param name="value"> /// The value to convert. /// </param> /// <param name="kind"> /// The RegistryValueKind type to convert the value to. /// </param> /// <returns> /// The converted value. /// </returns> private static object ConvertValueToKind(object value, RegistryValueKind kind) { switch (kind) { case RegistryValueKind.Binary: value = (value != null) ? (byte[])LanguagePrimitives.ConvertTo( value, typeof(byte[]), CultureInfo.CurrentCulture) : Array.Empty<byte>(); break; case RegistryValueKind.DWord: { if (value != null) { try { value = (int)LanguagePrimitives.ConvertTo(value, typeof(int), CultureInfo.CurrentCulture); } catch (PSInvalidCastException) { value = (UInt32)LanguagePrimitives.ConvertTo(value, typeof(UInt32), CultureInfo.CurrentCulture); } } else { value = 0; } } break; case RegistryValueKind.ExpandString: value = (value != null) ? (string)LanguagePrimitives.ConvertTo( value, typeof(string), CultureInfo.CurrentCulture) : string.Empty; break; case RegistryValueKind.MultiString: value = (value != null) ? (string[])LanguagePrimitives.ConvertTo( value, typeof(string[]), CultureInfo.CurrentCulture) : Array.Empty<string>(); break; case RegistryValueKind.QWord: { if (value != null) { try { value = (long)LanguagePrimitives.ConvertTo(value, typeof(long), CultureInfo.CurrentCulture); } catch (PSInvalidCastException) { value = (UInt64)LanguagePrimitives.ConvertTo(value, typeof(UInt64), CultureInfo.CurrentCulture); } } else { value = 0; } } break; case RegistryValueKind.String: value = (value != null) ? (string)LanguagePrimitives.ConvertTo( value, typeof(string), CultureInfo.CurrentCulture) : string.Empty; break; // If kind is Unknown then just leave the value as-is. } return value; } /// <summary> /// Helper to infer the RegistryValueKind from an object. /// </summary> /// <param name="value">Object whose RegistryValueKind has to be determined.</param> /// <returns>Corresponding RegistryValueKind.</returns> private static RegistryValueKind GetValueKindFromObject(object value) { if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } RegistryValueKind result = RegistryValueKind.Unknown; Type valueType = value.GetType(); if (valueType == typeof(byte[])) { result = RegistryValueKind.Binary; } else if (valueType == typeof(int)) { result = RegistryValueKind.DWord; } if (valueType == typeof(string)) { result = RegistryValueKind.String; } if (valueType == typeof(string[])) { result = RegistryValueKind.MultiString; } if (valueType == typeof(long)) { result = RegistryValueKind.QWord; } return result; } /// <summary> /// Helper to get RegistryValueKind for a Property. /// </summary> /// <param name="key">RegistryKey containing property.</param> /// <param name="valueName">Property for which RegistryValueKind is requested.</param> /// <returns>RegistryValueKind of the property. If the property does not exit,returns RegistryValueKind.Unknown.</returns> private static RegistryValueKind GetValueKindForProperty(IRegistryWrapper key, string valueName) { try { return key.GetValueKind(valueName); } catch (System.ArgumentException) { // RegistryKey that contains the specified value does not exist } catch (System.IO.IOException) { } catch (System.Security.SecurityException) { } catch (System.UnauthorizedAccessException) { } return RegistryValueKind.Unknown; } /// <summary> /// Helper to read back an existing registry key value. /// </summary> /// <param name="key">Key to read the value from.</param> /// <param name="valueName">Name of the value to read.</param> /// <returns>Value of the key, null if it could not retrieve /// it because known exceptions were thrown, else an exception is percolated up /// </returns> private static object ReadExistingKeyValue(IRegistryWrapper key, string valueName) { try { // Since SetValue can munge the data to a specified // type (RegistryValueKind), retrieve the value again // to output it in the correct form to the user. return key.GetValue(valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames); } catch (System.IO.IOException) { } catch (System.Security.SecurityException) { } catch (System.UnauthorizedAccessException) { } return null; } /// <summary> /// Wraps a registry item in a PSObject and sets the TreatAs to /// Microsoft.Win32.RegistryKey. This way values will be presented /// in the same format as keys. /// </summary> /// <param name="key"> /// The registry key to be written out. /// </param> /// <param name="path"> /// The path to the item being written out. /// </param> private void WriteRegistryItemObject( IRegistryWrapper key, string path) { if (key == null) { Dbg.Diagnostics.Assert( key != null, "The RegistryProvider should never attempt to write out a null value"); // Don't error, but don't write out anything either. return; } // Escape any wildcard characters in the path path = EscapeSpecialChars(path); // Wrap the key in an PSObject PSObject outputObject = PSObject.AsPSObject(key.RegistryKey); // Add the registry values to the PSObject string[] valueNames = key.GetValueNames(); for (int index = 0; index < valueNames.Length; ++index) { if (string.IsNullOrEmpty(valueNames[index])) { // The first unnamed value becomes the default value valueNames[index] = LocalizedDefaultToken; break; } } outputObject.AddOrSetProperty("Property", valueNames); WriteItemObject(outputObject, path, true); } /// <summary> /// Takes a string and tries to parse it into a RegistryValueKind enum /// type. /// If the conversion fails, WriteError() is called. /// </summary> /// <param name="type"> /// The type as specified by the user that should be parsed into a RegistryValueKind enum. /// </param> /// <param name="kind">Output for the RegistryValueKind for the string.</param> /// <returns> /// true if the conversion succeeded /// </returns> private bool ParseKind(string type, out RegistryValueKind kind) { kind = RegistryValueKind.Unknown; if (string.IsNullOrEmpty(type)) { return true; } bool success = true; Exception innerException = null; try { // Convert the parameter to a RegistryValueKind kind = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), type, true); } catch (InvalidCastException invalidCast) { innerException = invalidCast; } catch (ArgumentException argException) { innerException = argException; } if (innerException != null) { success = false; string formatString = RegistryProviderStrings.TypeParameterBindingFailure; Exception e = new ArgumentException( string.Format( CultureInfo.CurrentCulture, formatString, type, typeof(RegistryValueKind).FullName), innerException); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, type)); } return success; } /// <summary> /// Gets the default value name token from the resource. /// In English that token is "(default)" without the quotes. /// </summary> /// <remarks> /// This should not be localized as it will break scripts. /// </remarks> /// <returns> /// A string containing the default value name. /// </returns> private static string LocalizedDefaultToken => "(default)"; /// <summary> /// Converts an empty or null userEnteredPropertyName to the localized /// string for the default property name. /// </summary> /// <param name="userEnteredPropertyName"> /// The property name to convert. /// </param> /// <returns> /// If userEnteredPropertyName is null or empty, the localized default /// property name is returned, else the userEnteredPropertyName is returned. /// </returns> private string GetPropertyName(string userEnteredPropertyName) { string result = userEnteredPropertyName; if (!string.IsNullOrEmpty(userEnteredPropertyName)) { var stringComparer = Host.CurrentCulture.CompareInfo; if (stringComparer.Compare( userEnteredPropertyName, LocalizedDefaultToken, CompareOptions.IgnoreCase) == 0) { result = null; } } return result; } #endregion Private members } /// <summary> /// Defines dynamic parameters for the registry provider. /// </summary> public class RegistryProviderSetItemDynamicParameter { /// <summary> /// Gets or sets the Type parameter as a dynamic parameter for /// the registry provider's SetItem method. /// </summary> /// <remarks> /// The only acceptable values for this parameter are those found /// in the RegistryValueKind enum /// </remarks> [Parameter(ValueFromPipelineByPropertyName = true)] public RegistryValueKind Type { get; set; } = RegistryValueKind.Unknown; } } #endif // !UNIX
{ "content_hash": "923ef7f2033daaa97988b292d879ec12", "timestamp": "", "source": "github", "line_count": 4167, "max_line_length": 183, "avg_line_length": 37.48932085433165, "alnum_prop": 0.5086417698344621, "repo_name": "daxian-dbw/PowerShell", "id": "51f768c0277414976abae029a08c4eeebbf1bc2e", "size": "156305", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/System.Management.Automation/namespaces/RegistryProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24" }, { "name": "C#", "bytes": "30861483" }, { "name": "Dockerfile", "bytes": "6482" }, { "name": "HTML", "bytes": "18060" }, { "name": "JavaScript", "bytes": "8738" }, { "name": "PowerShell", "bytes": "5008481" }, { "name": "Rich Text Format", "bytes": "40664" }, { "name": "Roff", "bytes": "214981" }, { "name": "Shell", "bytes": "57893" }, { "name": "XSLT", "bytes": "14397" } ], "symlink_target": "" }