text stringlengths 2 1.04M | meta dict |
|---|---|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["cellx"] = factory();
else
root["cellx"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Cell_1 = __webpack_require__(1);
var EventEmitter_1 = __webpack_require__(4);
exports.EventEmitter = EventEmitter_1.EventEmitter;
var ObservableMap_1 = __webpack_require__(6);
exports.ObservableMap = ObservableMap_1.ObservableMap;
var ObservableList_1 = __webpack_require__(7);
exports.ObservableList = ObservableList_1.ObservableList;
var Cell_2 = __webpack_require__(1);
exports.Cell = Cell_2.Cell;
var WaitError_1 = __webpack_require__(5);
exports.WaitError = WaitError_1.WaitError;
const hasOwn = Object.prototype.hasOwnProperty;
const slice = Array.prototype.slice;
const global_ = Function('return this;')();
exports.KEY_CELLS = Symbol('cellx[cells]');
function cellx(value, options) {
if (!options) {
options = {};
}
let initialValue = value;
let cx = function (value) {
let context = this;
if (!context || context == global_) {
context = cx;
}
if (!hasOwn.call(context, exports.KEY_CELLS)) {
context[exports.KEY_CELLS] = new Map();
}
let cell = context[exports.KEY_CELLS].get(cx);
if (!cell) {
if (value === 'dispose' && arguments.length >= 2) {
return;
}
cell = new Cell_1.Cell(initialValue, {
__proto__: options,
context
});
context[exports.KEY_CELLS].set(cx, cell);
}
switch (arguments.length) {
case 0: {
return cell.get();
}
case 1: {
cell.set(value);
return value;
}
}
let method = value;
switch (method) {
case 'cell': {
return cell;
}
case 'bind': {
cx = cx.bind(context);
cx.constructor = cellx;
return cx;
}
}
let result = Cell_1.Cell.prototype[method].apply(cell, slice.call(arguments, 1));
return result === cell ? cx : result;
};
cx.constructor = cellx;
if (options.onChange || options.onError) {
cx.call(options.context || global_);
}
return cx;
}
exports.cellx = cellx;
function defineObservableProperty(obj, name, value) {
let cellName = name + 'Cell';
Object.defineProperty(obj, cellName, {
configurable: true,
enumerable: false,
writable: true,
value: value instanceof Cell_1.Cell ? value : new Cell_1.Cell(value, { context: obj })
});
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get() {
return this[cellName].get();
},
set(value) {
this[cellName].set(value);
}
});
return obj;
}
exports.defineObservableProperty = defineObservableProperty;
function defineObservableProperties(obj, props) {
Object.keys(props).forEach(name => {
defineObservableProperty(obj, name, props[name]);
});
return obj;
}
exports.defineObservableProperties = defineObservableProperties;
function define(obj, name, value) {
if (typeof name == 'string') {
defineObservableProperty(obj, name, value);
}
else {
defineObservableProperties(obj, name);
}
return obj;
}
exports.define = define;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = __webpack_require__(2);
const next_tick_1 = __webpack_require__(3);
const EventEmitter_1 = __webpack_require__(4);
const WaitError_1 = __webpack_require__(5);
function defaultPut(cell, value) {
cell.push(value);
}
const pendingCells = [];
let pendingCellsIndex = 0;
let afterRelease;
let currentCell = null;
const $error = { error: null };
let lastUpdationId = 0;
function release() {
for (; pendingCellsIndex < pendingCells.length; pendingCellsIndex++) {
if (pendingCells[pendingCellsIndex]._active) {
pendingCells[pendingCellsIndex].actualize();
}
}
pendingCells.length = 0;
pendingCellsIndex = 0;
if (afterRelease) {
let afterRelease_ = afterRelease;
afterRelease = null;
for (let cb of afterRelease_) {
cb();
}
}
}
class Cell extends EventEmitter_1.EventEmitter {
constructor(value, options) {
super();
this._reactions = [];
this._error = null;
this._lastErrorEvent = null;
this._hasSubscribers = false;
this._active = false;
this._currentlyPulling = false;
this._updationId = -1;
this.debugKey = options && options.debugKey;
this.context = options && options.context !== undefined ? options.context : this;
this._pull =
(options && options.pull) || (typeof value == 'function' ? value : null);
this._get = (options && options.get) || null;
this._validate = (options && options.validate) || null;
this._merge = (options && options.merge) || null;
this._put = (options && options.put) || defaultPut;
this._reap = (options && options.reap) || null;
this.meta = (options && options.meta) || null;
if (this._pull) {
this._dependencies = undefined;
this._value = undefined;
this._state = 'dirty';
this._inited = false;
}
else {
this._dependencies = null;
if (options && options.value !== undefined) {
value = options.value;
}
if (this._validate) {
this._validate(value, undefined);
}
if (this._merge) {
value = this._merge(value, undefined);
}
this._value = value;
this._state = 'actual';
this._inited = true;
if (value instanceof EventEmitter_1.EventEmitter) {
value.on('change', this._onValueChange, this);
}
}
if (options) {
if (options.onChange) {
this.on('change', options.onChange);
}
if (options.onError) {
this.on('error', options.onError);
}
}
}
static get currentlyPulling() {
return !!currentCell;
}
static autorun(cb, context) {
let disposer;
new Cell(function () {
if (!disposer) {
disposer = () => {
this.dispose();
};
}
cb.call(context, disposer);
}, {
onChange() { }
});
return disposer;
}
static release() {
release();
}
static afterRelease(cb) {
(afterRelease || (afterRelease = [])).push(cb);
}
on(type, listener, context) {
if (this._dependencies !== null) {
this.actualize();
}
if (typeof type == 'object') {
super.on(type, listener !== undefined ? listener : this.context);
}
else {
super.on(type, listener, context !== undefined ? context : this.context);
}
this._hasSubscribers = true;
this._activate(true);
return this;
}
off(type, listener, context) {
if (this._dependencies !== null) {
this.actualize();
}
if (type) {
if (typeof type == 'object') {
super.off(type, listener !== undefined ? listener : this.context);
}
else {
super.off(type, listener, context !== undefined ? context : this.context);
}
}
else {
super.off();
}
if (this._hasSubscribers &&
!this._reactions.length &&
!this._events.has('change') &&
!this._events.has('error')) {
this._hasSubscribers = false;
this._deactivate();
if (this._reap) {
this._reap.call(this.context);
}
}
return this;
}
_addReaction(reaction, actual) {
this._reactions.push(reaction);
this._hasSubscribers = true;
this._activate(actual);
}
_deleteReaction(reaction) {
this._reactions.splice(this._reactions.indexOf(reaction), 1);
if (this._hasSubscribers &&
!this._reactions.length &&
!this._events.has('change') &&
!this._events.has('error')) {
this._hasSubscribers = false;
this._deactivate();
if (this._reap) {
this._reap.call(this.context);
}
}
}
_activate(actual) {
if (this._active || !this._pull) {
return;
}
let deps = this._dependencies;
if (deps) {
let i = deps.length;
do {
deps[--i]._addReaction(this, actual);
} while (i);
if (actual) {
this._state = 'actual';
}
this._active = true;
}
}
_deactivate() {
if (!this._active) {
return;
}
let deps = this._dependencies;
let i = deps.length;
do {
deps[--i]._deleteReaction(this);
} while (i);
this._state = 'dirty';
this._active = false;
}
_onValueChange(evt) {
this._inited = true;
this._updationId = ++lastUpdationId;
let reactions = this._reactions;
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < reactions.length; i++) {
reactions[i]._addToRelease(true);
}
this.handleEvent(evt);
}
_addToRelease(dirty) {
this._state = dirty ? 'dirty' : 'check';
let reactions = this._reactions;
let i = reactions.length;
if (i) {
do {
if (reactions[--i]._state == 'actual') {
reactions[i]._addToRelease(false);
}
} while (i);
}
else if (pendingCells.push(this) == 1) {
next_tick_1.nextTick(release);
}
}
actualize() {
if (this._state == 'dirty') {
this.pull();
}
else if (this._state == 'check') {
let deps = this._dependencies;
for (let i = 0;;) {
deps[i].actualize();
if (this._state == 'dirty') {
this.pull();
break;
}
if (++i == deps.length) {
this._state = 'actual';
break;
}
}
}
}
get value() {
return this.get();
}
set value(value) {
this.set(value);
}
get() {
if (this._state != 'actual' && this._updationId != lastUpdationId) {
this.actualize();
}
if (currentCell) {
if (currentCell._dependencies) {
if (currentCell._dependencies.indexOf(this) == -1) {
currentCell._dependencies.push(this);
}
}
else {
currentCell._dependencies = [this];
}
if (this._error && this._error instanceof WaitError_1.WaitError) {
throw this._error;
}
}
return this._get ? this._get(this._value) : this._value;
}
pull() {
if (!this._pull) {
return false;
}
if (this._currentlyPulling) {
throw new TypeError('Circular pulling detected');
}
this._currentlyPulling = true;
let prevDeps = this._dependencies;
this._dependencies = null;
let prevCell = currentCell;
currentCell = this;
let value;
try {
value = this._pull.length
? this._pull.call(this.context, this, this._value)
: this._pull.call(this.context);
}
catch (err) {
$error.error = err;
value = $error;
}
currentCell = prevCell;
this._currentlyPulling = false;
if (this._hasSubscribers) {
let deps = this._dependencies;
let newDepCount = 0;
if (deps) {
let i = deps.length;
do {
let dep = deps[--i];
if (!prevDeps || prevDeps.indexOf(dep) == -1) {
dep._addReaction(this, false);
newDepCount++;
}
} while (i);
}
if (prevDeps && (!deps || deps.length - newDepCount < prevDeps.length)) {
for (let i = prevDeps.length; i;) {
i--;
if (!deps || deps.indexOf(prevDeps[i]) == -1) {
prevDeps[i]._deleteReaction(this);
}
}
}
if (deps) {
this._active = true;
}
else {
this._state = 'actual';
this._active = false;
}
}
else {
this._state = this._dependencies ? 'dirty' : 'actual';
}
return value === $error ? this.fail($error.error) : this.push(value);
}
set(value) {
if (!this._inited) {
// Не инициализированная ячейка не может иметь _state == 'check', поэтому вместо
// actualize сразу pull.
this.pull();
}
if (this._validate) {
this._validate(value, this._value);
}
if (this._merge) {
value = this._merge(value, this._value);
}
if (this._put.length >= 3) {
this._put.call(this.context, this, value, this._value);
}
else {
this._put.call(this.context, this, value);
}
return this;
}
push(value) {
this._inited = true;
if (this._error) {
this._setError(null);
}
let prevValue = this._value;
let changed = !Object.is(value, prevValue);
if (changed) {
this._value = value;
if (prevValue instanceof EventEmitter_1.EventEmitter) {
prevValue.off('change', this._onValueChange, this);
}
if (value instanceof EventEmitter_1.EventEmitter) {
value.on('change', this._onValueChange, this);
}
}
if (this._active) {
this._state = 'actual';
}
this._updationId = ++lastUpdationId;
if (changed) {
let reactions = this._reactions;
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < reactions.length; i++) {
reactions[i]._addToRelease(true);
}
this.emit('change', {
prevValue,
value
});
}
return changed;
}
fail(err) {
this._inited = true;
let isWaitError = err instanceof WaitError_1.WaitError;
if (!isWaitError) {
if (this.debugKey) {
logger_1.error('[' + this.debugKey + ']', err);
}
else {
logger_1.error(err);
}
if (!(err instanceof Error)) {
err = new Error(String(err));
}
}
this._setError(err);
if (this._active) {
this._state = 'actual';
}
return isWaitError;
}
_setError(err) {
this._error = err;
this._updationId = ++lastUpdationId;
if (err) {
this._handleErrorEvent({
target: this,
type: 'error',
data: {
error: err
}
});
}
}
_handleErrorEvent(evt) {
if (this._lastErrorEvent === evt) {
return;
}
this._lastErrorEvent = evt;
this.handleEvent(evt);
let reactions = this._reactions;
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < reactions.length; i++) {
reactions[i]._handleErrorEvent(evt);
}
}
wait() {
throw new WaitError_1.WaitError();
}
reap() {
this.off();
let reactions = this._reactions;
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < reactions.length; i++) {
reactions[i].reap();
}
return this;
}
dispose() {
return this.reap();
}
}
exports.Cell = Cell;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function noop() { }
var defaultHandler = function (type) {
var msg = [];
for (var _i = 1; _i < arguments.length; _i++) {
msg[_i - 1] = arguments[_i];
}
(console[type] || noop).apply(console, type == 'error' ? msg.map(function (m) { return (m && typeof m == 'object' && m.stack) || m; }) : msg);
};
var Logger = /** @class */ (function () {
function Logger(handler) {
this.handler = handler || defaultHandler;
}
Logger.prototype.log = function () {
var msg = [];
for (var _i = 0; _i < arguments.length; _i++) {
msg[_i] = arguments[_i];
}
this.handler.apply(this, ['log'].concat(msg));
};
Logger.prototype.warn = function () {
var msg = [];
for (var _i = 0; _i < arguments.length; _i++) {
msg[_i] = arguments[_i];
}
this.handler.apply(this, ['warn'].concat(msg));
};
Logger.prototype.error = function () {
var msg = [];
for (var _i = 0; _i < arguments.length; _i++) {
msg[_i] = arguments[_i];
}
this.handler.apply(this, ['error'].concat(msg));
};
return Logger;
}());
exports.Logger = Logger;
exports.logger = (Logger.$instance = new Logger());
exports.log = exports.logger.log.bind(exports.logger);
exports.warn = exports.logger.warn.bind(exports.logger);
exports.error = exports.logger.error.bind(exports.logger);
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = __webpack_require__(2);
exports.nextTick = (() => {
const global = Function('return this;')();
if (global.process &&
global.process.toString() == '[object process]' &&
global.process.nextTick) {
return global.process.nextTick;
}
if (global.setImmediate && global.setImmediate.toString().indexOf('[native code]') != -1) {
const setImmediate = global.setImmediate;
return (cb) => {
setImmediate(cb);
};
}
if (global.Promise && Promise.toString().indexOf('[native code]') != -1) {
const prm = Promise.resolve();
return (cb) => {
prm.then(() => {
cb();
});
};
}
let queue;
global.addEventListener('message', () => {
if (queue) {
let track = queue;
queue = null;
for (let i = 0, l = track.length; i < l; i++) {
try {
track[i]();
}
catch (err) {
logger_1.error(err);
}
}
}
});
return (cb) => {
if (queue) {
queue.push(cb);
}
else {
queue = [cb];
postMessage('__tic__', '*');
}
};
})();
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = __webpack_require__(2);
const hasOwn = Object.prototype.hasOwnProperty;
let currentlySubscribing = false;
let transactionLevel = 0;
let transactionEvents = [];
let silently = 0;
class EventEmitter {
static get currentlySubscribing() {
return currentlySubscribing;
}
static transact(cb) {
transactionLevel++;
try {
cb();
}
catch (err) {
logger_1.error(err);
}
if (--transactionLevel) {
return;
}
let events = transactionEvents;
transactionEvents = [];
for (let evt of events) {
evt.target.handleEvent(evt);
}
}
static silently(cb) {
silently++;
try {
cb();
}
catch (err) {
logger_1.error(err);
}
silently--;
}
constructor() {
this._events = new Map();
}
getEvents(type) {
if (type) {
let events = this._events.get(type);
if (!events) {
return [];
}
return Array.isArray(events) ? events : [events];
}
let events = { __proto__: null };
this._events.forEach((typeEvents, type) => {
events[type] = Array.isArray(typeEvents) ? typeEvents : [typeEvents];
});
return events;
}
on(type, listener, context) {
if (typeof type == 'object') {
context = listener !== undefined ? listener : this;
let listeners = type;
for (type in listeners) {
if (hasOwn.call(listeners, type)) {
this._on(type, listeners[type], context);
}
}
}
else {
this._on(type, listener, context !== undefined ? context : this);
}
return this;
}
off(type, listener, context) {
if (type) {
if (typeof type == 'object') {
context = listener !== undefined ? listener : this;
let listeners = type;
for (type in listeners) {
if (hasOwn.call(listeners, type)) {
this._off(type, listeners[type], context);
}
}
}
else {
this._off(type, listener, context !== undefined ? context : this);
}
}
else {
this._events.clear();
}
return this;
}
_on(type, listener, context) {
let index = type.indexOf(':');
if (index != -1) {
let propName = type.slice(index + 1);
currentlySubscribing = true;
(this[propName + 'Cell'] || (this[propName], this[propName + 'Cell'])).on(type.slice(0, index), listener, context);
currentlySubscribing = false;
}
else {
let events = this._events.get(type);
let evt = { listener, context };
if (!events) {
this._events.set(type, evt);
}
else if (Array.isArray(events)) {
events.push(evt);
}
else {
this._events.set(type, [events, evt]);
}
}
}
_off(type, listener, context) {
let index = type.indexOf(':');
if (index != -1) {
let propName = type.slice(index + 1);
(this[propName + 'Cell'] || (this[propName], this[propName + 'Cell'])).off(type.slice(0, index), listener, context);
}
else {
let events = this._events.get(type);
if (!events) {
return;
}
let evt;
if (!Array.isArray(events)) {
evt = events;
}
else if (events.length == 1) {
evt = events[0];
}
else {
for (let i = events.length; i;) {
evt = events[--i];
if (evt.listener == listener && evt.context === context) {
events.splice(i, 1);
break;
}
}
return;
}
if (evt.listener == listener && evt.context === context) {
this._events.delete(type);
}
}
}
once(type, listener, context) {
if (context === undefined) {
context = this;
}
function wrapper(evt) {
this._off(type, wrapper, context);
return listener.call(this, evt);
}
this._on(type, wrapper, context);
return wrapper;
}
emit(evt, data) {
if (typeof evt == 'string') {
evt = {
target: this,
type: evt
};
}
else if (!evt.target) {
evt.target = this;
}
else if (evt.target != this) {
throw new TypeError('Event cannot be emitted on this object');
}
if (data) {
evt.data = data;
}
if (!silently) {
if (transactionLevel) {
for (let i = transactionEvents.length;;) {
if (!i) {
(evt.data || (evt.data = {})).prevEvent = null;
transactionEvents.push(evt);
break;
}
let event = transactionEvents[--i];
if (event.target == this && event.type == evt.type) {
(evt.data || (evt.data = {})).prevEvent = event;
transactionEvents[i] = evt;
break;
}
}
}
else {
this.handleEvent(evt);
}
}
return evt;
}
handleEvent(evt) {
let events = this._events.get(evt.type);
if (!events) {
return;
}
if (Array.isArray(events)) {
if (events.length == 1) {
if (this._tryEventListener(events[0], evt) === false) {
evt.propagationStopped = true;
}
}
else {
events = events.slice();
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < events.length; i++) {
if (this._tryEventListener(events[i], evt) === false) {
evt.propagationStopped = true;
}
}
}
}
else if (this._tryEventListener(events, evt) === false) {
evt.propagationStopped = true;
}
}
_tryEventListener(emEvt, evt) {
try {
return emEvt.listener.call(emEvt.context, evt);
}
catch (err) {
logger_1.error(err);
}
}
}
exports.EventEmitter = EventEmitter;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function WaitError() { }
exports.WaitError = WaitError;
WaitError.prototype = {
__proto__: Error.prototype,
constructor: WaitError
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const EventEmitter_1 = __webpack_require__(4);
const hasOwn = Object.prototype.hasOwnProperty;
class ObservableMap extends EventEmitter_1.EventEmitter {
constructor(entries) {
super();
this._entries = new Map();
if (entries) {
let mapEntries = this._entries;
if (entries instanceof Map || entries instanceof ObservableMap) {
(entries instanceof Map ? entries : entries._entries).forEach((value, key) => {
mapEntries.set(key, value);
});
}
else if (Array.isArray(entries)) {
for (let i = 0, l = entries.length; i < l; i++) {
mapEntries.set(entries[i][0], entries[i][1]);
}
}
else {
for (let key in entries) {
if (hasOwn.call(entries, key)) {
mapEntries.set(key, entries[key]);
}
}
}
}
}
get size() {
return this._entries.size;
}
has(key) {
return this._entries.has(key);
}
get(key) {
return this._entries.get(key);
}
set(key, value) {
let entries = this._entries;
let hasKey = entries.has(key);
let prev;
if (hasKey) {
prev = entries.get(key);
if (Object.is(value, prev)) {
return this;
}
}
entries.set(key, value);
this.emit('change', {
subtype: hasKey ? 'update' : 'add',
key,
prevValue: prev,
value
});
return this;
}
delete(key) {
let entries = this._entries;
if (entries.has(key)) {
let value = entries.get(key);
entries.delete(key);
this.emit('change', {
subtype: 'delete',
key,
value
});
return true;
}
return false;
}
clear() {
if (this._entries.size) {
this._entries.clear();
this.emit('change', { subtype: 'clear' });
}
return this;
}
forEach(cb, context) {
this._entries.forEach(function (value, key) {
cb.call(context, value, key, this);
}, this);
}
keys() {
return this._entries.keys();
}
values() {
return this._entries.values();
}
entries() {
return this._entries.entries();
}
clone(deep) {
let entries;
if (deep) {
entries = [];
this._entries.forEach((value, key) => {
entries.push([
key,
value && value.clone ? value.clone(true) : value
]);
});
}
return new this.constructor(entries || this);
}
}
exports.ObservableMap = ObservableMap;
ObservableMap.prototype[Symbol.iterator] = ObservableMap.prototype.entries;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const EventEmitter_1 = __webpack_require__(4);
const push = Array.prototype.push;
const splice = Array.prototype.splice;
const defaultComparator = (a, b) => {
return a < b ? -1 : a > b ? 1 : 0;
};
class ObservableList extends EventEmitter_1.EventEmitter {
constructor(items, options) {
super();
this._items = [];
if (options && (options.sorted || (options.comparator && options.sorted !== false))) {
this._comparator = options.comparator || defaultComparator;
this._sorted = true;
}
else {
this._comparator = null;
this._sorted = false;
}
if (items) {
if (this._sorted) {
if (items instanceof ObservableList) {
items = items._items;
}
for (let i = 0, l = items.length; i < l; i++) {
this._insertSortedValue(items[i]);
}
}
else {
push.apply(this._items, items instanceof ObservableList ? items._items : items);
}
}
}
get length() {
return this._items.length;
}
_validateIndex(index, allowEndIndex) {
if (index === undefined) {
return index;
}
if (index < 0) {
index += this._items.length;
if (index < 0) {
throw new RangeError('Index out of valid range');
}
}
else if (index > this._items.length - (allowEndIndex ? 0 : 1)) {
throw new RangeError('Index out of valid range');
}
return index;
}
contains(value) {
return this._items.indexOf(value) != -1;
}
indexOf(value, fromIndex) {
return this._items.indexOf(value, this._validateIndex(fromIndex, true));
}
lastIndexOf(value, fromIndex) {
return this._items.lastIndexOf(value, fromIndex === undefined ? -1 : this._validateIndex(fromIndex, true));
}
get(index) {
return this._items[this._validateIndex(index, true)];
}
getRange(index, count) {
index = this._validateIndex(index, true);
if (count === undefined) {
return this._items.slice(index);
}
if (index + count > this._items.length) {
throw new RangeError('Sum of "index" and "count" out of valid range');
}
return this._items.slice(index, index + count);
}
set(index, value) {
if (this._sorted) {
throw new TypeError('Cannot set to sorted list');
}
index = this._validateIndex(index, true);
if (!Object.is(value, this._items[index])) {
this._items[index] = value;
this.emit('change');
}
return this;
}
setRange(index, values) {
if (this._sorted) {
throw new TypeError('Cannot set to sorted list');
}
index = this._validateIndex(index, true);
if (values instanceof ObservableList) {
values = values._items;
}
let valueCount = values.length;
if (!valueCount) {
return this;
}
if (index + valueCount > this._items.length) {
throw new RangeError('Sum of "index" and "values.length" out of valid range');
}
let items = this._items;
let changed = false;
for (let i = index + valueCount; i > index;) {
let value = values[--i - index];
if (!Object.is(value, items[i])) {
items[i] = value;
changed = true;
}
}
if (changed) {
this.emit('change');
}
return this;
}
add(value, unique) {
if (unique && this._items.indexOf(value) != -1) {
return this;
}
if (this._sorted) {
this._insertSortedValue(value);
}
else {
this._items.push(value);
}
this.emit('change');
return this;
}
addRange(values, unique) {
if (values instanceof ObservableList) {
values = values._items;
}
if (values.length) {
if (unique) {
let items = this._items;
let sorted = this._sorted;
let changed = false;
for (let value of values) {
if (items.indexOf(value) == -1) {
if (sorted) {
this._insertSortedValue(value);
}
else {
items.push(value);
}
changed = true;
}
}
if (changed) {
this.emit('change');
}
}
else {
if (this._sorted) {
for (let i = 0, l = values.length; i < l; i++) {
this._insertSortedValue(values[i]);
}
}
else {
push.apply(this._items, values);
}
this.emit('change');
}
}
return this;
}
insert(index, value) {
if (this._sorted) {
throw new TypeError('Cannot insert to sorted list');
}
this._items.splice(this._validateIndex(index, true), 0, value);
this.emit('change');
return this;
}
insertRange(index, values) {
if (this._sorted) {
throw new TypeError('Cannot insert to sorted list');
}
index = this._validateIndex(index, true);
if (values instanceof ObservableList) {
values = values._items;
}
if (values.length) {
splice.apply(this._items, [index, 0].concat(values));
this.emit('change');
}
return this;
}
remove(value, fromIndex) {
let index = this._items.indexOf(value, this._validateIndex(fromIndex, true));
if (index == -1) {
return false;
}
this._items.splice(index, 1);
this.emit('change');
return true;
}
removeAll(value, fromIndex) {
let index = this._validateIndex(fromIndex, true);
let items = this._items;
let changed = false;
while ((index = items.indexOf(value, index)) != -1) {
items.splice(index, 1);
changed = true;
}
if (changed) {
this.emit('change');
}
return changed;
}
removeEach(values, fromIndex) {
fromIndex = this._validateIndex(fromIndex, true);
if (values instanceof ObservableList) {
values = values._items.slice();
}
let items = this._items;
let changed = false;
for (let i = 0, l = values.length; i < l; i++) {
let index = items.indexOf(values[i], fromIndex);
if (index != -1) {
items.splice(index, 1);
changed = true;
}
}
if (changed) {
this.emit('change');
}
return changed;
}
removeAt(index) {
let value = this._items.splice(this._validateIndex(index), 1)[0];
this.emit('change');
return value;
}
removeRange(index, count) {
index = this._validateIndex(index, true);
if (count === undefined) {
count = this._items.length - index;
if (!count) {
return [];
}
}
else {
if (!count) {
return [];
}
if (index + count > this._items.length) {
throw new RangeError('Sum of "index" and "count" out of valid range');
}
}
let values = this._items.splice(index, count);
this.emit('change');
return values;
}
clear() {
if (this._items.length) {
this._items.length = 0;
this.emit('change', { subtype: 'clear' });
}
return this;
}
join(separator) {
return this._items.join(separator);
}
find(cb, context) {
let items = this._items;
for (let i = 0, l = items.length; i < l; i++) {
let item = items[i];
if (cb.call(context, item, i, this)) {
return item;
}
}
return;
}
findIndex(cb, context) {
let items = this._items;
for (let i = 0, l = items.length; i < l; i++) {
if (cb.call(context, items[i], i, this)) {
return i;
}
}
return -1;
}
clone(deep) {
return new this.constructor(deep
? this._items.map(item => item && item.clone ? item.clone(true) : item)
: this, {
comparator: this._comparator || undefined,
sorted: this._sorted
});
}
toArray() {
return this._items.slice();
}
toString() {
return this._items.join();
}
_insertSortedValue(value) {
let items = this._items;
let comparator = this._comparator;
let low = 0;
let high = items.length;
while (low != high) {
let mid = (low + high) >> 1;
if (comparator(value, items[mid]) < 0) {
high = mid;
}
else {
low = mid + 1;
}
}
items.splice(low, 0, value);
}
}
exports.ObservableList = ObservableList;
['forEach', 'map', 'filter', 'every', 'some'].forEach(name => {
ObservableList.prototype[name] = function (cb, context) {
return this._items[name](function (item, index) {
return cb.call(context, item, index, this);
}, this);
};
});
['reduce', 'reduceRight'].forEach(name => {
ObservableList.prototype[name] = function (cb, initialValue) {
let list = this;
function wrapper(accumulator, item, index) {
return cb(accumulator, item, index, list);
}
return arguments.length >= 2
? this._items[name](wrapper, initialValue)
: this._items[name](wrapper);
};
});
[
['keys', (index) => index],
['values', (index, item) => item],
['entries', (index, item) => [index, item]]
].forEach((settings) => {
let getStepValue = settings[1];
ObservableList.prototype[settings[0]] = function () {
let items = this._items;
let index = 0;
let done = false;
return {
next() {
if (!done) {
if (index < items.length) {
return {
value: getStepValue(index, items[index++]),
done: false
};
}
done = true;
}
return {
value: undefined,
done: true
};
}
};
};
});
ObservableList.prototype[Symbol.iterator] = ObservableList.prototype.values;
/***/ })
/******/ ]);
}); | {
"content_hash": "0fc20d45cdbdd659d56c4ef301012abc",
"timestamp": "",
"source": "github",
"line_count": 1499,
"max_line_length": 159,
"avg_line_length": 30.559706470980654,
"alnum_prop": 0.4744919120696806,
"repo_name": "cdnjs/cdnjs",
"id": "b40fe06a0b2ac99b284a9d0dca646099966c0e8b",
"size": "45865",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/cellx/1.8.6/cellx.umd.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
*
*/
package com.thinkbiganalytics.metadata.modeshape.op;
/*-
* #%L
* thinkbig-metadata-modeshape
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Predicate;
import javax.inject.Inject;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thinkbiganalytics.jobrepo.query.model.ExecutedJob;
import com.thinkbiganalytics.jobrepo.query.model.ExecutionStatus;
import com.thinkbiganalytics.metadata.api.MetadataAccess;
import com.thinkbiganalytics.metadata.api.feed.Feed;
import com.thinkbiganalytics.metadata.api.feed.FeedNotFoundExcepton;
import com.thinkbiganalytics.metadata.api.feed.OpsManagerFeedProvider;
import com.thinkbiganalytics.metadata.api.jobrepo.job.BatchJobExecution;
import com.thinkbiganalytics.metadata.api.jobrepo.job.BatchJobExecutionProvider;
import com.thinkbiganalytics.metadata.api.op.FeedDependencyDeltaResults;
import com.thinkbiganalytics.metadata.api.op.FeedOperation;
import com.thinkbiganalytics.metadata.api.op.FeedOperation.ID;
import com.thinkbiganalytics.metadata.api.op.FeedOperation.State;
import com.thinkbiganalytics.metadata.api.op.FeedOperationCriteria;
import com.thinkbiganalytics.metadata.api.op.FeedOperationsProvider;
import com.thinkbiganalytics.metadata.core.AbstractMetadataCriteria;
import com.thinkbiganalytics.metadata.modeshape.feed.JcrFeedProvider;
import com.thinkbiganalytics.metadata.modeshape.op.FeedOperationExecutedJobWrapper.OpId;
import com.thinkbiganalytics.support.FeedNameUtil;
/**
*
*/
public class JobRepoFeedOperationsProvider implements FeedOperationsProvider {
private static final Logger LOG = LoggerFactory.getLogger(JobRepoFeedOperationsProvider.class);
@Inject
OpsManagerFeedProvider opsManagerFeedProvider;
// @Inject
// private FeedRepository feedRepo;
// @Inject
// private JobRepository jobRepo;
@Inject
private JcrFeedProvider feedProvider;
@Inject
private BatchJobExecutionProvider jobExecutionProvider;
@Inject
private MetadataAccess metadata;
protected static FeedOperation.State asOperationState(ExecutionStatus status) {
switch (status) {
case ABANDONED:
return State.ABANDONED;
case COMPLETED:
return State.SUCCESS;
case FAILED:
return State.FAILURE;
case STARTED:
return State.STARTED;
case STARTING:
return State.STARTED;
case STOPPING:
return State.STARTED;
case STOPPED:
return State.CANCELED;
case UNKNOWN:
return State.STARTED;
default:
return State.FAILURE;
}
}
protected static FeedOperation.State asOperationState(BatchJobExecution.JobStatus status) {
switch (status) {
case ABANDONED:
return State.ABANDONED;
case COMPLETED:
return State.SUCCESS;
case FAILED:
return State.FAILURE;
case STARTED:
return State.STARTED;
case STARTING:
return State.STARTED;
case STOPPING:
return State.STARTED;
case STOPPED:
return State.CANCELED;
case UNKNOWN:
return State.STARTED;
default:
return State.FAILURE;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.api.op.FeedOperationsProvider#criteria()
*/
@Override
public FeedOperationCriteria criteria() {
return new Criteria();
}
public boolean isFeedRunning(Feed.ID feedId) {
if (feedId != null) {
return opsManagerFeedProvider.isFeedRunning(opsManagerFeedProvider.resolveId(feedId.toString()));
}
return false;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.api.op.FeedOperationsProvider#getOperation(com.thinkbiganalytics.metadata.api.op.FeedOperation.ID)
*/
@Override
public FeedOperation getOperation(ID id) {
OpId opId = (OpId) id;
BatchJobExecution jobExecution = jobExecutionProvider.findByJobExecutionId(new Long(opId.toString()));
if (jobExecution != null) {
return createOperation(jobExecution);
} else {
return null;
}
}
@Override
public List<FeedOperation> findLatestCompleted(Feed.ID feedId) {
return metadata.read(() -> {
List<FeedOperation> operations = new ArrayList<>();
Feed feed = this.feedProvider.getFeed(feedId);
if (feed != null) {
BatchJobExecution latestJobExecution = this.jobExecutionProvider.findLatestCompletedJobForFeed(feed.getQualifiedName());
if (latestJobExecution != null) {
LOG.debug("Latest completed job execution id {} ", latestJobExecution.getJobExecutionId());
operations.add(createOperation(latestJobExecution));
}
}
return operations;
});
}
@Override
public List<FeedOperation> findLatest(Feed.ID feedId) {
return metadata.read(() -> {
List<FeedOperation> operations = new ArrayList<>();
Feed feed = this.feedProvider.getFeed(feedId);
if (feed != null) {
BatchJobExecution latestJobExecution = this.jobExecutionProvider.findLatestJobForFeed(feed.getQualifiedName());
if (latestJobExecution != null) {
operations.add(createOperation(latestJobExecution));
}
}
return operations;
});
}
@Override
public FeedDependencyDeltaResults getDependentDeltaResults(Feed.ID feedId, Set<String> props) {
Feed feed = this.feedProvider.getFeed(feedId);
if (feed != null) {
String systemFeedName = FeedNameUtil.fullName(feed.getCategory().getSystemName(), feed.getName());
FeedDependencyDeltaResults results = new FeedDependencyDeltaResults(feed.getId().toString(), systemFeedName);
//find this feeds latest completion
BatchJobExecution latest = jobExecutionProvider.findLatestCompletedJobForFeed(systemFeedName);
//get the dependent feeds
List<Feed> dependents = feed.getDependentFeeds();
if (dependents != null) {
for (Feed depFeed : dependents) {
String depFeedSystemName = FeedNameUtil.fullName(depFeed.getCategory().getSystemName(), depFeed.getName());
//find Completed feeds executed since time
Set<BatchJobExecution> jobs = null;
if (latest != null) {
jobs = (Set<BatchJobExecution>) jobExecutionProvider.findJobsForFeedCompletedSince(depFeedSystemName, latest.getStartTime());
} else {
BatchJobExecution job = jobExecutionProvider.findLatestCompletedJobForFeed(depFeedSystemName);
if (job != null) {
jobs = new HashSet<>();
jobs.add(job);
}
}
if (jobs != null) {
for (BatchJobExecution job : jobs) {
DateTime endTime = job.getEndTime();
Map<String, String> executionContext = job.getJobExecutionContextAsMap();
Map<String, Object> map = new HashMap<>();
//filter the map
if (executionContext != null) {
//add those requested to the results map
for (Entry<String, String> entry : executionContext.entrySet()) {
if (props == null || props.isEmpty() || props.contains(entry.getKey())) {
map.put(entry.getKey(), entry.getValue());
}
}
}
results.addFeedExecutionContext(depFeedSystemName, job.getJobExecutionId(), job.getStartTime(), endTime, map);
}
} else {
results.getDependentFeedNames().add(depFeedSystemName);
}
}
}
return results;
} else {
throw new FeedNotFoundExcepton(feedId);
}
}
/*
@Override
public Map<DateTime, Map<String, Object>> getAllResults(FeedOperationCriteria criteria, Set<String> props) {
Map<DateTime, Map<String, Object>> results = new HashMap<DateTime, Map<String,Object>>();
// List<FeedOperation> ops = find(criteria);
for (FeedOperation op : ops) {
DateTime time = op.getStopTime();
Map<String, Object> map = results.get(time);
for (Entry<String, Object> entry : op.getResults().entrySet()) {
if (props.isEmpty() || props.contains(entry.getKey())) {
if (map == null) {
map = new HashMap<>();
results.put(time, map);
}
map.put(entry.getKey(), entry.getValue());
}
}
}
return results;
}
private FeedOperationExecutedJobWrapper createOperation(ExecutedJob exec) {
Long id = exec.getExecutionId();
// TODO Inefficient
ExecutedJob fullExec = this.jobRepo.findByExecutionId(id.toString());
return new FeedOperationExecutedJobWrapper(fullExec);
}
*/
private FeedOperationBatchJobExecutionJobWrapper createOperation(BatchJobExecution exec) {
return new FeedOperationBatchJobExecutionJobWrapper(exec);
}
private class Criteria extends AbstractMetadataCriteria<FeedOperationCriteria> implements FeedOperationCriteria, Predicate<ExecutedJob> {
private Set<State> states = new HashSet<>();
private Set<Feed.ID> feedIds = new HashSet<>();
private DateTime startedBefore;
private DateTime startedSince;
private DateTime stoppedBefore;
private DateTime stoppedSince;
// TODO This is a temporary filtering solution. Replace with an implementation that uses
// the criteria to create SQL.
@Override
public boolean test(ExecutedJob job) {
Feed.ID id = null;
if (!feedIds.isEmpty()) {
String[] jobName = job.getJobName().split("\\.");
Feed feed = feedProvider.findBySystemName(jobName[0], jobName[1]);
id = feed != null ? feed.getId() : null;
}
return
(states.isEmpty() || states.contains(asOperationState(job.getStatus()))) &&
(feedIds.isEmpty() || (id != null && feedIds.contains(id))) &&
(this.startedBefore == null || this.startedBefore.isAfter(job.getStartTime())) &&
(this.startedSince == null || this.startedSince.isBefore(job.getStartTime())) &&
(this.stoppedBefore == null || this.stoppedBefore.isAfter(job.getEndTime())) &&
(this.stoppedSince == null || this.stoppedSince.isBefore(job.getEndTime()));
}
@Override
public FeedOperationCriteria state(State... states) {
this.states.addAll(Arrays.asList(states));
return this;
}
@Override
public FeedOperationCriteria feed(Feed.ID... feedIds) {
this.feedIds.addAll(Arrays.asList(feedIds));
return this;
}
@Override
public FeedOperationCriteria startedSince(DateTime time) {
this.startedSince = time;
return this;
}
@Override
public FeedOperationCriteria startedBefore(DateTime time) {
this.startedBefore = time;
return this;
}
@Override
public FeedOperationCriteria startedBetween(DateTime after, DateTime before) {
startedSince(after);
startedBefore(before);
return this;
}
@Override
public FeedOperationCriteria stoppedSince(DateTime time) {
this.stoppedSince = time;
return this;
}
@Override
public FeedOperationCriteria stoppedBefore(DateTime time) {
this.stoppedBefore = time;
return this;
}
@Override
public FeedOperationCriteria stoppedBetween(DateTime after, DateTime before) {
stoppedSince(after);
stoppedBefore(before);
return this;
}
}
}
| {
"content_hash": "fdbf7a9e86e469240c5beea7d65a44b7",
"timestamp": "",
"source": "github",
"line_count": 374,
"max_line_length": 149,
"avg_line_length": 36.794117647058826,
"alnum_prop": 0.6040985393503379,
"repo_name": "claudiu-stanciu/kylo",
"id": "b05da162f735555509ba6f8e1384fe539f787b07",
"size": "13761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "metadata/metadata-modeshape/src/main/java/com/thinkbiganalytics/metadata/modeshape/op/JobRepoFeedOperationsProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "265273"
},
{
"name": "FreeMarker",
"bytes": "785"
},
{
"name": "HTML",
"bytes": "764976"
},
{
"name": "Java",
"bytes": "10148636"
},
{
"name": "JavaScript",
"bytes": "3529132"
},
{
"name": "PLpgSQL",
"bytes": "31537"
},
{
"name": "SQLPL",
"bytes": "11241"
},
{
"name": "Scala",
"bytes": "32595"
},
{
"name": "Shell",
"bytes": "102225"
},
{
"name": "TypeScript",
"bytes": "543195"
}
],
"symlink_target": ""
} |
package org.nibiru.ui.ios.builder;
import org.nibiru.ui.core.impl.builder.RadioButtonGroupBuilder;
import org.nibiru.ui.core.impl.builder.RadioButtonGroupBuilderFactory;
import org.nibiru.ui.ios.widget.IOSRadioButtonGroup;
import javax.inject.Inject;
public class IOSRadioButtonGroupBuilderFactory implements RadioButtonGroupBuilderFactory {
@Inject
public IOSRadioButtonGroupBuilderFactory() {
}
@Override
public <T> RadioButtonGroupBuilder<T> create(Class<T> valueClass) {
return new RadioButtonGroupBuilder<T>(new IOSRadioButtonGroup<T>());
}
}
| {
"content_hash": "bff8e0f47c3ae330593781a3391485c5",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 90,
"avg_line_length": 31.11111111111111,
"alnum_prop": 0.8196428571428571,
"repo_name": "NibiruOS/ui",
"id": "7f36b9f12b7597b41a31f9c7fcd91316ef5e390f",
"size": "560",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "org.nibiru.ui.ios/src/main/java/org/nibiru/ui/ios/builder/IOSRadioButtonGroupBuilderFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "89"
},
{
"name": "Java",
"bytes": "312200"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/notification_service.proto
package com.google.monitoring.v3;
public interface DeleteNotificationChannelRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.monitoring.v3.DeleteNotificationChannelRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The channel for which to execute the request. The format is
* `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`.
* </pre>
*
* <code>string name = 3;</code>
*/
java.lang.String getName();
/**
*
*
* <pre>
* The channel for which to execute the request. The format is
* `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`.
* </pre>
*
* <code>string name = 3;</code>
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* If true, the notification channel will be deleted regardless of its
* use in alert policies (the policies will be updated to remove the
* channel). If false, channels that are still referenced by an existing
* alerting policy will fail to be deleted in a delete operation.
* </pre>
*
* <code>bool force = 5;</code>
*/
boolean getForce();
}
| {
"content_hash": "a2478259940f17d7cfef9d601074019e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 104,
"avg_line_length": 27.19148936170213,
"alnum_prop": 0.6697965571205008,
"repo_name": "vam-google/google-cloud-java",
"id": "fbe5f3b2c222a4c8f8a2de2329db64fc67333970",
"size": "1278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "google-api-grpc/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/DeleteNotificationChannelRequestOrBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "128"
},
{
"name": "CSS",
"bytes": "23036"
},
{
"name": "Dockerfile",
"bytes": "127"
},
{
"name": "Go",
"bytes": "9641"
},
{
"name": "HTML",
"bytes": "16158"
},
{
"name": "Java",
"bytes": "47356483"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "110799"
},
{
"name": "Shell",
"bytes": "9162"
}
],
"symlink_target": ""
} |
layout: api
title: v1.0.0
categories: api
version: v1.0.0
splash: true
navigation:
- title: MapBox.js & Leaflet
items:
- title: L.mapbox.map
items:
- title: map.getTileJSON
items:
- title: L.mapbox.tileLayer
items:
- tileLayer.getTileJSON
- tileLayer.setFormat
- title: L.mapbox.gridLayer
items:
- gridLayer.getTileJSON
- gridLayer.getData
- title: L.mapbox.markerLayer
items:
- markerLayer.loadURL
- markerLayer.loadID
- markerLayer.setFilter
- markerLayer.getFilter
- markerLayer.setGeoJSON
- markerLayer.getGeoJSON
- title: L.mapbox.geocoder
items:
- geocoder.query
- geocoder.reverseQuery
- title: L.mapbox.legendControl
items:
- title: L.mapbox.gridControl
items:
- title: L.mapbox.geocoderControl
items:
- geocoderControl.setURL
- geocoderControl.setID
- geocoderControl.setTileJSON
- geocoderControl.setErrorHandler
- geocoderControl.getErrorHandler
- title: L.mapbox.marker.icon
items:
- title: L.mapbox.marker.style
items:
---
<div></div><h1>Map</h1>
<div id="content-undefined"class="space-bottom depth-1"></div><h2 id="L.mapbox.map">L.mapbox.map<span class="bracket">(</span><span class="args">element: Element, id: string | url: string | tilejson: object, [options: object]</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.map"class="space-bottom depth-2"><p>Create and automatically configure a map with layers, markers, and
interactivity.
</p>
<p><em>Arguments</em>:
</p>
<p>The first argument is required and must be the id of an element, or a DOM element
reference.
</p>
<p>The second argument is optional and can be:
</p>
<ul>
<li>A map <code>id</code> string <code>examples.map-foo</code></li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
<li>A <a href="http://mapbox.com/wax/tilejson.html">TileJSON</a> object, from your own Javascript code</li>
</ul>
<p>The third argument is optional. If provided, it is the same options
as provided to <a href="http://leafletjs.com/reference.html#map-options">L.Map</a>
with the following additions:
</p>
<ul>
<li><code>tileLayer</code> (boolean). Whether or not to add a <code>L.mapbox.tileLayer</code> based on
the TileJSON. Default: <code>true</code>.</li>
<li><code>markerLayer</code> (boolean). Whether or not to add a <code>L.mapbox.markerLayer</code> based on
the TileJSON. Default: <code>true</code>.</li>
<li><code>gridLayer</code> (boolean). Whether or not to add a <code>L.mapbox.gridLayer</code> based on
the TileJSON. Default: <code>true</code>.</li>
<li><code>legendControl</code> (boolean). Whether or not to add a <code>L.mapbox.legendControl</code>.
Default: <code>true</code>.</li>
</ul>
<p><em>Example</em>:
</p>
<pre><code>// map refers to a <div> element with the ID map
// examples.map-4l7djmvo is the ID of a map on MapBox.com
var map = L.mapbox.map('map', 'examples.map-4l7djmvo');
// map refers to a <div> element with the ID map
// This map will have no layers initially
var map = L.mapbox.map('map');</code></pre>
<p><em>Returns</em>: a map object
</p>
</div><h2 id="map.getTileJSON">map.getTileJSON<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2>
<div id="content-map.getTileJSON"class="space-bottom depth-2"><p>Returns this map's TileJSON object which determines its tile source,
zoom bounds and other metadata.
</p>
<p><em>Arguments</em>: none
</p>
<p><em>Returns</em>: the TileJSON object
</p>
</div><h1>Layers</h1>
<div id="content-map.getTileJSON"class="space-bottom depth-1"></div><h2 id="L.mapbox.tileLayer">L.mapbox.tileLayer<span class="bracket">(</span><span class="args">id: string | url: string | tilejson: object, [options: object]</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.tileLayer"class="space-bottom depth-2"><p>You can add a tiled layer to your map with <code>L.mapbox.tileLayer()</code>, a simple
interface to layers from MapBox and elsewhere.
</p>
<p><em>Arguments</em>:
</p>
<p>The first argument is required and must be:
</p>
<ul>
<li>An <code>id</code> string <code>examples.map-foo</code></li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
<li>A TileJSON object, from your own Javascript code</li>
</ul>
<p>The second argument is optional. If provided, it is the same options
as provided to <a href="http://leafletjs.com/reference.html#tilelayer">L.TileLayer</a>
with one addition:
</p>
<ul>
<li><code>retinaVersion</code>, if provided, is an alternative value for the first argument
to <code>L.mapbox.tileLayer</code> which, if retina is detected, is used instead.</li>
</ul>
<p><em>Example</em>:
</p>
<pre><code>// the second argument is optional
var layer = L.mapbox.tileLayer('examples.map-20v6611k');
// you can also provide a full url to a tilejson resource
var layer = L.mapbox.tileLayer('{{site.tileApi}}/v3/examples.map-0l53fhk2.json');
// if provided,you can support retina tiles
var layer = L.mapbox.tileLayer('examples.map-20v6611k', {
detectRetina: true,
// if retina is detected, this layer is used instead
retinaVersion: 'examples.map-zswgei2n'
});</code></pre>
<p><em>Returns</em> a <code>L.mapbox.tileLayer</code> object.
</p>
</div><h3 id="tileLayer.getTileJSON">tileLayer.getTileJSON<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3>
<div id="content-tileLayer.getTileJSON"class="space-bottom depth-3"><p>Returns this layer's TileJSON object which determines its tile source,
zoom bounds and other metadata.
</p>
<p><em>Arguments</em>: none
</p>
<p><em>Example</em>:
</p>
<pre><code>var layer = L.mapbox.tileLayer('examples.map-20v6611k')
// since layers load asynchronously through AJAX, use the
// `.on` function to listen for them to be loaded before
// calling `getTileJSON()`
.on('load', function() {
// get TileJSON data from the loaded layer
var TileJSON = layer.getTileJSON();
});</code></pre>
<p><em>Returns</em>: the TileJSON object
</p>
</div><h3 id="tileLayer.setFormat">tileLayer.setFormat<span class="bracket">(</span><span class="args">format: string</span><span class="bracket">)</span></h3>
<div id="content-tileLayer.setFormat"class="space-bottom depth-3"><p>Set the image format of tiles in this layer. You can use lower-quality tiles
in order to load maps faster
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><code>string</code> an image format. valid options are: 'png', 'png32', 'png64', 'png128', 'png256', 'jpg70', 'jpg80', 'jpg90'</li>
</ol>
<p><em>Example</em>:
</p>
<pre><code>// Downsample tiles for faster loading times on slow
// internet connections
var layer = L.mapbox.tileLayer('examples.map-20v6611k', {
format: 'jpg70'
});</code></pre>
<p><em>Returns</em>: the layer object
</p>
</div><h2 id="L.mapbox.gridLayer">L.mapbox.gridLayer<span class="bracket">(</span><span class="args">id: string | url: string | tilejson: object, [options: object]</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.gridLayer"class="space-bottom depth-2"><p>An <code>L.mapbox.gridLayer</code> loads <a href="http://mapbox.com/developers/utfgrid/">UTFGrid</a> tiles of
interactivity into your map, which you can easily access with <code>L.mapbox.gridControl</code>.
</p>
<p><em>Arguments</em>:
</p>
<p>The first argument is required and must be:
</p>
<ul>
<li>An <code>id</code> string <code>examples.map-foo</code></li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
<li>A TileJSON object, from your own Javascript code</li>
</ul>
<p><em>Example</em>:
</p>
<pre><code>// the second argument is optional
var layer = L.mapbox.gridLayer('examples.map-20v6611k');</code></pre>
<p><em>Returns</em> a <code>L.mapbox.gridLayer</code> object.
</p>
</div><h3 id="gridLayer.getTileJSON">gridLayer.getTileJSON<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3>
<div id="content-gridLayer.getTileJSON"class="space-bottom depth-3"><p>Returns this layer's TileJSON object which determines its tile source,
zoom bounds and other metadata.
</p>
<p><em>Arguments</em>: none
</p>
<p><em>Example</em>:
</p>
<pre><code>var layer = L.mapbox.gridLayer('examples.map-20v6611k')
// since layers load asynchronously through AJAX, use the
// `.on` function to listen for them to be loaded before
// calling `getTileJSON()`
.on('load', function() {
// get TileJSON data from the loaded layer
var TileJSON = layer.getTileJSON();
});</code></pre>
<p><em>Returns</em>: the TileJSON object
</p>
</div><h3 id="gridLayer.getData">gridLayer.getData<span class="bracket">(</span><span class="args">latlng: LatLng, callback: function</span><span class="bracket">)</span></h3>
<div id="content-gridLayer.getData"class="space-bottom depth-3"><p>Load data for a given latitude, longitude point on the map, and call the callback
function with that data, if any.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><code>latlng</code> an L.LatLng object</li>
<li><code>callback</code> a function that is called with the grid data as an argument</li>
</ol>
<p><em>Returns</em>: the L.mapbox.gridLayer object
</p>
</div><h2 id="L.mapbox.markerLayer">L.mapbox.markerLayer<span class="bracket">(</span><span class="args">id: string | url: string | tilejson: object, [options: object]</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.markerLayer"class="space-bottom depth-2"><p><code>L.mapbox.markerLayer</code> provides an easy way to integrate <a href="http://www.geojson.org/">GeoJSON</a>
from MapBox and elsewhere into your map.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><p>required and must be:</p>
</li>
<li><p>An <code>id</code> string <code>examples.map-foo</code></p>
</li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
<li>A GeoJSON object, from your own Javascript code</li>
</ol>
<p>The second argument is optional. If provided, it is the same options
as provided to <a href="http://leafletjs.com/reference.html#featuregroup">L.FeatureGroup</a>
with one addition:
</p>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
.addTo(map);</code></pre>
<p><em>Returns</em> a <code>L.mapbox.markerLayer</code> object.
</p>
</div><h3 id="markerLayer.loadURL">markerLayer.loadURL<span class="bracket">(</span><span class="args">url: string</span><span class="bracket">)</span></h3>
<div id="content-markerLayer.loadURL"class="space-bottom depth-3"><p>Load GeoJSON data for this layer from the URL given by <code>url</code>.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><code>string</code> a map id</li>
</ol>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
.addTo(map);
markerLayer.loadURL('my_local_markers.geojson');</code></pre>
<p><em>Returns</em>: the layer object
</p>
</div><h3 id="markerLayer.loadID">markerLayer.loadID<span class="bracket">(</span><span class="args">id: string</span><span class="bracket">)</span></h3>
<div id="content-markerLayer.loadID"class="space-bottom depth-3"><p>Load tiles from a map with the given <code>id</code> on MapBox.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><code>string</code> a map id</li>
</ol>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
.addTo(map);
// loads markers from the map `examples.map-0l53fhk2` on MapBox,
// if that map has markers
markerLayer.loadID('examples.map-0l53fhk2');</code></pre>
<p><em>Returns</em>: the layer object
</p>
</div><h3 id="markerLayer.setFilter">markerLayer.setFilter<span class="bracket">(</span><span class="args">filter: function</span><span class="bracket">)</span></h3>
<div id="content-markerLayer.setFilter"class="space-bottom depth-3"><p>Sets the filter function for this data layer.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>a function that takes GeoJSON features and
returns true to show and false to hide features.</li>
</ol>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
// hide all markers
.setFilter(function() { return false; })
.addTo(map);</code></pre>
<p><em>Returns</em> the markerLayer object.
</p>
</div><h3 id="markerLayer.getFilter">markerLayer.getFilter<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3>
<div id="content-markerLayer.getFilter"class="space-bottom depth-3"><p>Gets the filter function for this data layer.
</p>
<p><em>Arguments</em>: none
</p>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
// hide all markers
.setFilter(function() { return false; })
.addTo(map);
// get the filter function
var fn = markerLayer.getFilter()</code></pre>
<p><em>Returns</em> the filter function.
</p>
</div><h3 id="markerLayer.setGeoJSON">markerLayer.setGeoJSON<span class="bracket">(</span><span class="args">geojson: object</span><span class="bracket">)</span></h3>
<div id="content-markerLayer.setGeoJSON"class="space-bottom depth-3"><p>Set the contents of a markers layer: run the provided
features through the filter function and then through the factory function to create elements
for the map. If the layer already has features, they are replaced with the new features.
An empty array will clear the layer of all features.
</p>
<p><em>Arguments:</em>
</p>
<ul>
<li><code>features</code>, an array of <a href="http://geojson.org/geojson-spec.html#feature-objects">GeoJSON feature objects</a>,
or omitted to get the current value.</li>
</ul>
<p><em>Example</em>:
</p>
<pre><code>var markerLayer = L.mapbox.markerLayer(geojson)
.addTo(map);
// a simple GeoJSON featureset with a single point
// with no properties
markerLayer.setGeoJSON({
type: "FeatureCollection",
features: [{
type: "Feature",
geometry: {
type: "Point",
coordinates: [102.0, 0.5]
},
properties: { }
}]
});</code></pre>
<p><em>Returns</em> the markerLayer object
</p>
</div><h3 id="markerLayer.getGeoJSON">markerLayer.getGeoJSON<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3>
<div id="content-markerLayer.getGeoJSON"class="space-bottom depth-3"><p>Get the contents of this layer as GeoJSON data.
</p>
<p><em>Arguments:</em> none
</p>
<p><em>Returns</em> the GeoJSON represented by this layer
</p>
</div><h1>Geocoding</h1>
<div id="content-markerLayer.getGeoJSON"class="space-bottom depth-1"></div><h2 id="L.mapbox.geocoder">L.mapbox.geocoder<span class="bracket">(</span><span class="args">id: string | url: string</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.geocoder"class="space-bottom depth-2"><p>A low-level interface to geocoding, useful for more complex uses and reverse-geocoding.
</p>
<ol>
<li><p>(required) must be:</p>
</li>
<li><p>An <code>id</code> string <code>examples.map-foo</code></p>
</li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
</ol>
<p><em>Returns</em> a <code>L.mapbox.geocoder</code> object.
</p>
</div><h3 id="geocoder.query">geocoder.query<span class="bracket">(</span><span class="args">queryString: string, callback: function</span><span class="bracket">)</span></h3>
<div id="content-geocoder.query"class="space-bottom depth-3"><p>Queries the geocoder with a query string, and returns its result, if any.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>(required) a query, expressed as a string, like 'Arkansas'</li>
<li>(required) a callback</li>
</ol>
<p>The callback is called with arguments
</p>
<ol>
<li>An error, if any</li>
<li><p>The result. This is an object with the following members:</p>
<pre><code> { results: // raw results
latlng: // a map-friendly latlng array
bounds: // geojson-style bounds of the first result
lbounds: // leaflet-style bounds of the first result
}</code></pre>
</li>
</ol>
<p><em>Returns</em>: the geocoder object. The return value of this function is not useful - you must use a callback to get results.
</p>
</div><h3 id="geocoder.reverseQuery">geocoder.reverseQuery<span class="bracket">(</span><span class="args">location: object, callback: function</span><span class="bracket">)</span></h3>
<div id="content-geocoder.reverseQuery"class="space-bottom depth-3"><p>Queries the geocoder with a location, and returns its result, if any.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><p>(required) a query, expressed as an object:</p>
<pre><code> [lon, lat] // an array of lon, lat
{ lat: 0, lon: 0 } // a lon, lat object
{ lat: 0, lng: 0 } // a lng, lat object</code></pre>
</li>
</ol>
<p>The first argument can also be an array of objects in that
form to geocode more than one item.
</p>
<ol>
<li>(required) a callback</li>
</ol>
<p>The callback is called with arguments
</p>
<ol>
<li>An error, if any</li>
<li>The result. This is an object of the raw result from MapBox.</li>
</ol>
<p><em>Returns</em>: the geocoder object. The return value of this function is not useful - you must use a callback to get results.
</p>
</div><h1>Controls</h1>
<div id="content-geocoder.reverseQuery"class="space-bottom depth-1"></div><h2 id="L.mapbox.legendControl">L.mapbox.legendControl<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.legendControl"class="space-bottom depth-2"><p>A map control that shows legends added to maps in MapBox. Legends are auto-detected from active layers.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><p>(optional) an options object. Beyond the default options for map controls,
this object has one special parameter:</p>
</li>
<li><p><code>sanitizer</code>: A function that accepts a string containing legend data, and returns a
sanitized result for HTML display. The default will remove dangerous script content,
and is recommended.</p>
</li>
</ol>
<p><em>Example</em>:
</p>
<pre><code>var map = L.mapbox.map('map').setView([38, -77], 5);
map.addControl(L.mapbox.legendControl());</code></pre>
<p><em>Returns</em>: a <code>L.mapbox.legendControl</code> object.
</p>
</div><h2 id="L.mapbox.gridControl">L.mapbox.gridControl<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.gridControl"class="space-bottom depth-2"><p>Interaction is what we call interactive parts of maps that are created with
the powerful <a href="http://mapbox.com/tilemill/docs/crashcourse/tooltips/">tooltips & regions system</a>
in TileMill. Under the hood, it's powered by
the <a href="https://github.com/mapbox/utfgrid-spec">open UTFGrid specification.</a>.
</p>
<p><em>Arguments</em>:
</p>
<ul>
<li>The first argument must be a layer created with <code>L.mapbox.gridLayer()</code></li>
<li><p>The second argument can be an options object. Valid options are:</p>
</li>
<li><p><code>sanitizer</code>: A function that accepts a string containing interactivity data, and returns a
sanitized result for HTML display. The default will remove dangerous script content,
and is recommended.</p>
</li>
<li><code>template</code>: A string in the <a href="http://mustache.github.io/">Mustache</a> template
language that will be evaluated with data from the grid to produce HTML for the
interaction.</li>
<li><code>follow</code>: Whether the tooltip should follow the mouse in a constant
relative position, or should be fixed in the top-right side of the map.
By default, this is <code>false</code> and the tooltip is stationary.</li>
<li><code>pinnable</code>: Whether clicking will 'pin' the tooltip open and expose a
'close' button for the user to close the tooltip. By default, this is <code>true</code>.</li>
</ul>
<p><em>Example</em>:
</p>
<pre><code>var map = L.mapbox.map('map').setView([38, -77], 5);
var gridLayer = L.mapbox.gridLayer('examples.map-8ced9urs');
map.addLayer(L.mapbox.tileLayer('examples.map-8ced9urs'));
map.addLayer(gridLayer);
map.addControl(L.mapbox.gridControl(gridLayer));</code></pre>
<p><em>Returns</em>: a <code>L.mapbox.gridControl</code> object.
</p>
</div><h2 id="L.mapbox.geocoderControl">L.mapbox.geocoderControl<span class="bracket">(</span><span class="args">id: string | url: string</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.geocoderControl"class="space-bottom depth-2"><p>Adds geocoder functionality as well as a UI element to a map. This uses
the <a href="http://mapbox.com/developers/api/#geocoding">MapBox Geocoding API</a>.
</p>
<p>This function is currently in private beta:
<a href="http://mapbox.com/about/contact/">contact MapBox</a> before using this functionality.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li><p>(required) either:</p>
</li>
<li><p>An <code>id</code> string <code>examples.map-foo</code></p>
</li>
<li>A URL to TileJSON, like <code>{{site.tileApi}}/v3/examples.map-0l53fhk2.json</code></li>
</ol>
<p><em>Example</em>
</p>
<pre><code>var map = L.map('map')
.setView([37, -77], 5)
.addControl( L.mapbox.geocoder('examples.map-i875kd35'));</code></pre>
<p><em>Returns</em> a <code>L.mapbox.geocoderControl</code> object.
</p>
</div><h3 id="geocoderControl.setURL">geocoderControl.setURL<span class="bracket">(</span><span class="args">url: string</span><span class="bracket">)</span></h3>
<div id="content-geocoderControl.setURL"class="space-bottom depth-3"><p>Set the url used for geocoding.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>a geocoding url</li>
</ol>
<p><em>Returns</em>: the geocoder control object
</p>
</div><h3 id="geocoderControl.setID">geocoderControl.setID<span class="bracket">(</span><span class="args">id: string</span><span class="bracket">)</span></h3>
<div id="content-geocoderControl.setID"class="space-bottom depth-3"><p>Set the map id used for geocoding.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>a map id to geocode from</li>
</ol>
<p><em>Returns</em>: the geocoder control object
</p>
</div><h3 id="geocoderControl.setTileJSON">geocoderControl.setTileJSON<span class="bracket">(</span><span class="args">tilejson: object</span><span class="bracket">)</span></h3>
<div id="content-geocoderControl.setTileJSON"class="space-bottom depth-3"><p>Set the TileJSON used for geocoding.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>A TileJSON object</li>
</ol>
<p><em>Returns</em>: the geocoder object
</p>
</div><h3 id="geocoderControl.setErrorHandler">geocoderControl.setErrorHandler<span class="bracket">(</span><span class="args">errorhandler: function</span><span class="bracket">)</span></h3>
<div id="content-geocoderControl.setErrorHandler"class="space-bottom depth-3"><p>Set the function called if a geocoding request returns an error.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>a function that takes an error object - typically an XMLHttpRequest, and
handles it.</li>
</ol>
<p><em>Returns</em>: the geocoder control object
</p>
</div><h3 id="geocoderControl.getErrorHandler">geocoderControl.getErrorHandler<span class="bracket">(</span><span class="args"></span><span class="bracket">)</span></h3>
<div id="content-geocoderControl.getErrorHandler"class="space-bottom depth-3"><p>Returns the current function used by this geocoderControl for error handling.
</p>
<p><em>Arguments</em>: none
</p>
<p><em>Returns</em>: the geocoder control's error handler
</p>
</div><h1>Markers</h1>
<div id="content-geocoderControl.getErrorHandler"class="space-bottom depth-1"></div><h2 id="L.mapbox.marker.icon">L.mapbox.marker.icon<span class="bracket">(</span><span class="args">feature: object</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.marker.icon"class="space-bottom depth-2"><p>A core icon generator used in <code>L.mapbox.marker.style</code>
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>A GeoJSON feature object</li>
</ol>
<p><em>Returns</em>:
</p>
<p>A <code>L.Icon</code> object with custom settings for <code>iconUrl</code>, <code>iconSize</code>, <code>iconAnchor</code>,
and <code>popupAnchor</code>.
</p>
</div><h2 id="L.mapbox.marker.style">L.mapbox.marker.style<span class="bracket">(</span><span class="args">feature: object | latlon: object</span><span class="bracket">)</span></h2>
<div id="content-L.mapbox.marker.style"class="space-bottom depth-2"><p>An icon generator for use in conjunction with <code>pointToLayer</code> to generate
markers from the <a href="http://mapbox.com/developers/api/#markers">MapBox Markers API</a>
and support the <a href="https://github.com/mapbox/simplestyle-spec">simplestyle-spec</a> for
features.
</p>
<p><em>Arguments</em>:
</p>
<ol>
<li>A GeoJSON feature object</li>
<li>The latitude, longitude position of the marker</li>
</ol>
<p><em>Examples</em>:
</p>
<pre><code>L.geoJson(geoJson, {
pointToLayer: L.mapbox.marker.style,
});</code></pre>
<p><em>Returns</em>:
</p>
<p>A <code>L.Marker</code> object with the latitude, longitude position and a styled marker
</p>
</div><h1>Theming</h1>
<div id="content-L.mapbox.marker.style"class="space-bottom depth-1"></div><h2>Dark theme</h2>
<div id="content-L.mapbox.marker.style"class="space-bottom depth-2"><p>Mapbox.js implements a simple, light style on all interaction elements. A dark theme
is available by applying <code>class="dark"</code> to the map div.
</p>
<p><em>Example</em>:
</p>
<pre><code><div id="map" class="dark"></div></code></pre>
</div>
| {
"content_hash": "4b5646ce697c05c81500ed0ce006a1e7",
"timestamp": "",
"source": "github",
"line_count": 700,
"max_line_length": 267,
"avg_line_length": 36.70142857142857,
"alnum_prop": 0.6991164220933401,
"repo_name": "jackhummah/bootles",
"id": "a09339f3b162ce0c20e4dd589e5bed354998a371",
"size": "25695",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/mapbox/mapbox.js-2.4.0/docs/_posts/api/0200-01-01-v1.0.0.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "642692"
},
{
"name": "HTML",
"bytes": "476397"
},
{
"name": "JavaScript",
"bytes": "360085"
},
{
"name": "TypeScript",
"bytes": "16808"
}
],
"symlink_target": ""
} |
using Microsoft.VisualStudio.Shell;
using Spect.Net.VsPackage.Vsx;
namespace Spect.Net.VsPackage.Commands
{
/// <summary>
/// Run the default Z80 program command
/// </summary>
[CommandId(0x0811)]
public class CompileDefaultZ80CodeCommand : CompileZ80CodeCommand
{
/// <summary>
/// Allows the project node to run the default Z80 code file
/// </summary>
public override bool AllowProjectItem => true;
/// <summary>
/// The item is allowed only when there is a default code file selected
/// </summary>
protected override void OnQueryStatus(OleMenuCommand mc)
{
base.OnQueryStatus(mc);
if (!mc.Visible) return;
var project = Package.CodeDiscoverySolution.CurrentProject;
var enabled = project.DefaultZ80CodeItem != null;
if (enabled)
{
project.GetHierarchyByIdentity(project.DefaultZ80CodeItem.Identity, out var hierarchy, out _);
enabled &= hierarchy != null;
}
mc.Enabled = enabled;
}
}
} | {
"content_hash": "3c722feee6e7d4d1646f56cae27c02ea",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 110,
"avg_line_length": 32.285714285714285,
"alnum_prop": 0.6,
"repo_name": "Dotneteer/spectnetide",
"id": "7a8d549b7e2617b3a1dab6cf677d0105e7c1946a",
"size": "1132",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "VsIntegration/Old-Spect.Net.VsPackage/Commands/CompileDefaultZ80CodeCommand.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "76707"
},
{
"name": "Assembly",
"bytes": "3125120"
},
{
"name": "C",
"bytes": "442740"
},
{
"name": "C#",
"bytes": "19216822"
},
{
"name": "HTML",
"bytes": "277068"
}
],
"symlink_target": ""
} |
export interface ICoginitiveServiceSpeechResult{
Confidence: number;
Display: string;
ITN: string;
Lexical: string;
MaskedITN: string;
} | {
"content_hash": "2ee96ff4783ac80aab14a5a2d4beaab5",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 48,
"avg_line_length": 22.285714285714285,
"alnum_prop": 0.7115384615384616,
"repo_name": "anteloe/speech-polyfill",
"id": "850abe5db240b91d2e06de3f16b73a901ca52cbc",
"size": "156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/contracts/ICoginitiveServiceSpeechResult.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "11961"
},
{
"name": "TypeScript",
"bytes": "13681"
}
],
"symlink_target": ""
} |
<footer class="footer">
<p class="text-muted">Todos os direitos reservados a Xulipa SoftWorks.</p>
</footer>
<!-- Jquery -->
<script src="<?php echo base_url('lib/jquery/jquery-2.1.4.min.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('lib/jquery/jquery-mask.js') ?>" type="text/javascript"></script>
<!-- Bootstrap Script -->
<script src="<?php echo base_url('lib/bootstrap/js/bootstrap.min.js') ?>"></script>
<!-- App Script -->
<script src="<?php echo base_url('lib/script/script_app.js') ?>" type="text/javascript"></script>
</body>
</html>
| {
"content_hash": "d896d09d9d1f832f0413433ad0b0c30e",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 103,
"avg_line_length": 38.86666666666667,
"alnum_prop": 0.6518010291595198,
"repo_name": "xulipaxulepa/SGAP",
"id": "bc1899b6228b58a28965a77bb0f145e75d1e0a89",
"size": "583",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/componentesFixos/footer.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "364"
},
{
"name": "CSS",
"bytes": "17500"
},
{
"name": "HTML",
"bytes": "8227586"
},
{
"name": "JavaScript",
"bytes": "56355"
},
{
"name": "PHP",
"bytes": "1807588"
}
],
"symlink_target": ""
} |
package com.atlassian.plugin.testpackage1;
/**
* This is used by {@link com.atlassian.plugin.osgi.container.felix.TestExportsBuilder}
* for testing conflicting packages thus it has to be here.
*/
public class Dummy1
{
}
| {
"content_hash": "7f0f5112d43899ef61c8873626c8ad4b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 87,
"avg_line_length": 24.88888888888889,
"alnum_prop": 0.7589285714285714,
"repo_name": "mrdon/PLUG",
"id": "dd2e5fc01f197c32d44386f721a6c3a339668ef8",
"size": "224",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "atlassian-plugins-osgi/src/test/java/com/atlassian/plugin/testpackage1/Dummy1.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "2614284"
}
],
"symlink_target": ""
} |
set(target_libraries
CTKPluginFramework
Poco
QT_LIBRARIES
)
| {
"content_hash": "559e21c9c55caab055c94c111914dccc",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 20,
"avg_line_length": 13.2,
"alnum_prop": 0.7727272727272727,
"repo_name": "gaoxiaojun/miniCTK",
"id": "c6976638556b9a72a30bb4005d9e69b9df95fa3b",
"size": "271",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Plugins/org.blueberry.ui.qt/target_libraries.cmake",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9203"
},
{
"name": "C++",
"bytes": "8382102"
},
{
"name": "CMake",
"bytes": "588897"
},
{
"name": "HTML",
"bytes": "2448"
},
{
"name": "Python",
"bytes": "8624"
},
{
"name": "QMake",
"bytes": "171210"
},
{
"name": "Shell",
"bytes": "1074"
},
{
"name": "XSLT",
"bytes": "34850"
}
],
"symlink_target": ""
} |
<div id="up-to-top" class="row">
<div class="small-12 columns" style="text-align: right;">
<a class="iconfont" href="#top-of-page"></a>
</div><!-- /.small-12.columns -->
</div><!-- /.row -->
<footer id="footer-content" class="bg-grau">
<div id="footer">
<div class="row">
<div class="medium-6 large-5 columns">
<h5 class="shadow-black">{{ site.data.language.info_website }}</h5>
<p class="shadow-black">
{{ site.description }}
<a href="{{ site.url }}{{ site.baseurl }}/info/">{{ site.data.language.more }}</a>
</p>
</div><!-- /.large-6.columns -->
<div class="small-6 medium-3 large-3 large-offset-1 columns">
{% for service_item in site.data.services %}
{% if forloop.first == true %}
<h5 class="shadow-black">{{ service_item.menu_name }}</h5>
{% endif %}
{% endfor %}
<ul class="no-bullet shadow-black">
{% for service_item in site.data.services %}
{% if service_item.url contains 'http' %}{% assign domain = '' %}{% else %}{% assign domain = site.url + site.baseurl %}{% endif %}
<li {% if service_item.class %}class="{{ service_item.class }}" {% endif %}>
<a href="{{ domain }}{{ service_item.url }}" {% if service_item.url contains 'http' %}target="_blank" {% endif %} title="{{ service_item.title }}">{{ service_item.name }}</a>
</li>
{% endfor %}
</ul>
</div><!-- /.large-4.columns -->
<div class="small-6 medium-3 large-3 columns">
{% for network_item in site.data.network %}
{% if forloop.first == true %}
<h5 class="shadow-black">{{ network_item.menu_name }}</h5>
{% endif %}
{% endfor %}
<ul class="no-bullet shadow-black">
{% for network_item in site.data.network %}
{% if network_item.url contains 'http' %}{% assign domain = '' %}{% else %}{% assign domain = site.url + site.baseurl %}{% endif %}
<li {% if network_item.class %}class="{{ network_item.class }}" {% endif %}>
<a href="{{ domain }}{{ network_item.url }}" {% if network_item.url contains 'http' %}target="_blank" {% endif %} title="{{ network_item.title }}">{{ network_item.name }}</a>
</li>
{% endfor %}
</ul>
</div><!-- /.large-3.columns -->
</div><!-- /.row -->
</div><!-- /#footer -->
<div id="subfooter">
<nav class="row">
<section id="subfooter-left" class="small-12 medium-6 columns credits">
<p>
Created with
with <a href="http://jekyllrb.com/" target="_blank">Jekyll</a>
based on <a href="http://phlow.github.io/feeling-responsive/">Feeling Responsive</a>.
</p>
</section>
<section id="subfooter-right" class="small-12 medium-6 columns">
<ul class="inline-list social-icons">
{% for social_item in site.data.socialmedia %}
<li><a href="{{ social_item.url }}" target="_blank" class="{{ social_item.class }}" title="{{ social_item.title }}"></a></li>
{% endfor %}
</ul>
</section>
</nav>
</div><!-- /#subfooter -->
</footer>
| {
"content_hash": "1d63a36463cb06f8875c41a158da725e",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 194,
"avg_line_length": 44.18987341772152,
"alnum_prop": 0.48496132913205386,
"repo_name": "praetorianprefect/praetorianprefect.github.io",
"id": "fa2503dc67747da314049bd6adda331395b21e33",
"size": "3491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/_footer.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "396393"
},
{
"name": "HTML",
"bytes": "154614"
},
{
"name": "JavaScript",
"bytes": "576749"
},
{
"name": "Ruby",
"bytes": "1166"
},
{
"name": "XSLT",
"bytes": "5064"
}
],
"symlink_target": ""
} |
import Vue from 'vue';
import monitoringComp from '~/environments/components/environment_monitoring.vue';
describe('Monitoring Component', () => {
let MonitoringComponent;
beforeEach(() => {
MonitoringComponent = Vue.extend(monitoringComp);
});
it('should render a link to environment monitoring page', () => {
const monitoringUrl = 'https://gitlab.com';
const component = new MonitoringComponent({
propsData: {
monitoringUrl,
},
}).$mount();
expect(component.$el.getAttribute('href')).toEqual(monitoringUrl);
expect(component.$el.querySelector('.fa-area-chart')).toBeDefined();
expect(component.$el.getAttribute('title')).toEqual('Monitoring');
});
});
| {
"content_hash": "2122dda0bae0c210dbbb9734156c02a8",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 82,
"avg_line_length": 31.130434782608695,
"alnum_prop": 0.6759776536312849,
"repo_name": "htve/GitlabForChinese",
"id": "0f3dba662303a8b2cc801e8a0fe972fd24f6b455",
"size": "716",
"binary": false,
"copies": "2",
"ref": "refs/heads/9-2-zh",
"path": "spec/javascripts/environments/environment_monitoring_spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "499575"
},
{
"name": "Gherkin",
"bytes": "140955"
},
{
"name": "HTML",
"bytes": "979335"
},
{
"name": "JavaScript",
"bytes": "1909827"
},
{
"name": "Ruby",
"bytes": "10590735"
},
{
"name": "Shell",
"bytes": "26903"
},
{
"name": "Vue",
"bytes": "81150"
}
],
"symlink_target": ""
} |
package com.opengamma.analytics.financial.equity.future;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import org.testng.annotations.Test;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.equity.future.derivative.EquityIndexDividendFuture;
import com.opengamma.timeseries.DoubleTimeSeries;
import com.opengamma.timeseries.precise.zdt.ImmutableZonedDateTimeDoubleTimeSeries;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT)
public class EquityIndexDividendFutureTest {
private static final double PRICE = 95.0;
private static final double TIME_TO_SETTLEMENT = 1.45;
private static final double TIME_TO_FIXING = 1.44;
private static final ZonedDateTime FIXING_DATE = DateUtils.getUTCDate(2011, 1, 3);
private static final ZonedDateTime[] FIXING_DATES = {FIXING_DATE, FIXING_DATE.plusYears(1), DateUtils.getDateOffsetWithYearFraction(FIXING_DATE, 1.0) };
private static final double[] FIXINGS = {98d, 99., 100.0 };
private static final DoubleTimeSeries<ZonedDateTime> FIXING_TS = ImmutableZonedDateTimeDoubleTimeSeries.of(FIXING_DATES, FIXINGS, ZoneOffset.UTC);
@Test
public void test() {
final EquityIndexDividendFuture theFuture = new EquityIndexDividendFuture(TIME_TO_FIXING, TIME_TO_SETTLEMENT, PRICE, Currency.CAD, 10.);
assertEquals(theFuture.getTimeToSettlement(), TIME_TO_SETTLEMENT, 0);
assertFalse(Double.compare(theFuture.getTimeToExpiry(), TIME_TO_SETTLEMENT) == 0);
}
@Test
public void testTimeSeries() {
final ZonedDateTime lastCloseDate = FIXING_DATE;
final double lastClose = FIXING_TS.getValue(lastCloseDate);
assertEquals(lastClose, 98, 0);
final double latestFixing = FIXING_TS.getLatestValue();
assertEquals(latestFixing, 100, 0);
final ZonedDateTime HighNoon = lastCloseDate.plusHours(12);
assertNull("ArrayZonedDateTimeDoubleTimeSeries.getValue has not returned a null value for a time missing from the series", FIXING_TS.getValue(HighNoon));
// BLOOMBERG_TICKER~Z H1 Index
}
}
| {
"content_hash": "d317800718e3a824a9944f9626a36f6c",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 157,
"avg_line_length": 37.96666666666667,
"alnum_prop": 0.7818261633011413,
"repo_name": "McLeodMoores/starling",
"id": "77a4f0a6666c74b0a78f1559eb947522949b5753",
"size": "2416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/analytics/src/test/java/com/opengamma/analytics/financial/equity/future/EquityIndexDividendFutureTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2505"
},
{
"name": "CSS",
"bytes": "213501"
},
{
"name": "FreeMarker",
"bytes": "310184"
},
{
"name": "GAP",
"bytes": "1490"
},
{
"name": "Groovy",
"bytes": "11518"
},
{
"name": "HTML",
"bytes": "318295"
},
{
"name": "Java",
"bytes": "79541905"
},
{
"name": "JavaScript",
"bytes": "1511230"
},
{
"name": "PLSQL",
"bytes": "398"
},
{
"name": "PLpgSQL",
"bytes": "26901"
},
{
"name": "Shell",
"bytes": "11481"
},
{
"name": "TSQL",
"bytes": "604117"
}
],
"symlink_target": ""
} |
import tensorflow as tf
import numpy as np
class SOM(object):
"""
2-D Self-Organizing Map with Gaussian Neighbourhood function
and linearly decreasing learning rate.
"""
#To check if the SOM has been trained
_trained = False
def __init__(self, m, n, dim, n_iterations=100, alpha=None, sigma=None):
"""
Initializes all necessary components of the TensorFlow
Graph.
m X n are the dimensions of the SOM. 'n_iterations' should
should be an integer denoting the number of iterations undergone
while training.
'dim' is the dimensionality of the training inputs.
'alpha' is a number denoting the initial time(iteration no)-based
learning rate. Default value is 0.3
'sigma' is the the initial neighbourhood value, denoting
the radius of influence of the BMU while training. By default, its
taken to be half of max(m, n).
"""
#Assign required variables first
self._m = m
self._n = n
if alpha is None:
alpha = 0.3
else:
alpha = float(alpha)
if sigma is None:
sigma = max(m, n) / 2.0
else:
sigma = float(sigma)
self._n_iterations = abs(int(n_iterations))
##INITIALIZE GRAPH
self._graph = tf.Graph()
##POPULATE GRAPH WITH NECESSARY COMPONENTS
with self._graph.as_default():
##VARIABLES AND CONSTANT OPS FOR DATA STORAGE
#Randomly initialized weightage vectors for all neurons,
#stored together as a matrix Variable of size [m*n, dim]
self._weightage_vects = tf.Variable(tf.random_normal(
[m*n, dim]))
#Matrix of size [m*n, 2] for SOM grid locations
#of neurons
self._location_vects = tf.constant(np.array(
list(self._neuron_locations(m, n))))
##PLACEHOLDERS FOR TRAINING INPUTS
#We need to assign them as attributes to self, since they
#will be fed in during training
#The training vector
self._vect_input = tf.placeholder(tf.float32, [dim])
#Iteration number
self._iter_input = tf.placeholder(tf.float32)
##CONSTRUCT TRAINING OP PIECE BY PIECE
#Only the final, 'root' training op needs to be assigned as
#an attribute to self, since all the rest will be executed
#automatically during training
#To compute the Best Matching Unit given a vector
#Basically calculates the Euclidean distance between every
#neuron's weightage vector and the input, and returns the
#index of the neuron which gives the least value
bmu_index = tf.argmin(tf.sqrt(tf.reduce_sum(
tf.pow(tf.subtract(self._weightage_vects, tf.stack(
[self._vect_input for i in range(m*n)])), 2), 1)),
0)
#This will extract the location of the BMU based on the BMU's
#index
slice_input = tf.pad(tf.reshape(bmu_index, [1]),
np.array([[0, 1]]))
bmu_loc = tf.reshape(tf.slice(self._location_vects, slice_input,
tf.constant(np.array([1, 2]))),
[2])
#To compute the alpha and sigma values based on iteration
#number
learning_rate_op = tf.subtract(1.0, tf.div(self._iter_input,
self._n_iterations))
_alpha_op = tf.multiply(alpha, learning_rate_op)
_sigma_op = tf.multiply(sigma, learning_rate_op)
#Construct the op that will generate a vector with learning
#rates for all neurons, based on iteration number and location
#wrt BMU.
bmu_distance_squares = tf.reduce_sum(tf.pow(tf.subtract(
self._location_vects, tf.stack(
[bmu_loc for i in range(m*n)])), 2), 1)
neighbourhood_func = tf.exp(tf.negative(tf.div(tf.cast(
bmu_distance_squares, "float32"), tf.pow(_sigma_op, 2))))
learning_rate_op = tf.multiply(_alpha_op, neighbourhood_func)
#Finally, the op that will use learning_rate_op to update
#the weightage vectors of all neurons based on a particular
#input
learning_rate_multiplier = tf.stack([tf.tile(tf.slice(
learning_rate_op, np.array([i]), np.array([1])), [dim])
for i in range(m*n)])
weightage_delta = tf.multiply(
learning_rate_multiplier,
tf.subtract(tf.stack([self._vect_input for i in range(m*n)]),
self._weightage_vects))
new_weightages_op = tf.add(self._weightage_vects,
weightage_delta)
self._training_op = tf.assign(self._weightage_vects,
new_weightages_op)
##INITIALIZE SESSION
self._sess = tf.Session()
##INITIALIZE VARIABLES
#init_op = tf.initialize_all_variables()
init_op = tf.global_variables_initializer()
self._sess.run(init_op)
def _neuron_locations(self, m, n):
"""
Yields one by one the 2-D locations of the individual neurons
in the SOM.
"""
#Nested iterations over both dimensions
#to generate all 2-D locations in the map
for i in range(m):
for j in range(n):
yield np.array([i, j])
def train(self, input_vects):
"""
Trains the SOM.
'input_vects' should be an iterable of 1-D NumPy arrays with
dimensionality as provided during initialization of this SOM.
Current weightage vectors for all neurons(initially random) are
taken as starting conditions for training.
"""
#Training iterations
for iter_no in range(self._n_iterations):
#Train with each vector one by one
for input_vect in input_vects:
self._sess.run(self._training_op,
feed_dict={self._vect_input: input_vect,
self._iter_input: iter_no})
print(str(iter_no)+'/'+str(self._n_iterations))
#Store a centroid grid for easy retrieval later on
centroid_grid = [[] for i in range(self._m)]
self._weightages = list(self._sess.run(self._weightage_vects))
self._locations = list(self._sess.run(self._location_vects))
for i, loc in enumerate(self._locations):
centroid_grid[loc[0]].append(self._weightages[i])
self._centroid_grid = centroid_grid
self._trained = True
def get_centroids(self):
"""
Returns a list of 'm' lists, with each inner list containing
the 'n' corresponding centroid locations as 1-D NumPy arrays.
"""
if not self._trained:
raise ValueError("SOM not trained yet")
return self._centroid_grid
def map_vects(self, input_vects):
"""
Maps each input vector to the relevant neuron in the SOM
grid.
'input_vects' should be an iterable of 1-D NumPy arrays with
dimensionality as provided during initialization of this SOM.
Returns a list of 1-D NumPy arrays containing (row, column)
info for each input vector(in the same order), corresponding
to mapped neuron.
"""
if not self._trained:
raise ValueError("SOM not trained yet")
to_return = []
for vect in input_vects:
min_index = min([i for i in range(len(self._weightages))],
key=lambda x: np.linalg.norm(vect-
self._weightages[x]))
to_return.append(self._locations[min_index])
return to_return
#For plotting the images
from matplotlib import pyplot as plt
#Training inputs for RGBcolors
colors = np.array(
[[0., 0., 0.],
[0., 0., 1.],
[0., 0., 0.5],
[0.125, 0.529, 1.0],
[0.33, 0.4, 0.67],
[0.6, 0.5, 1.0],
[0., 1., 0.],
[1., 0., 0.],
[0., 1., 1.],
[1., 0., 1.],
[1., 1., 0.],
[1., 1., 1.],
[.33, .33, .33],
[.5, .5, .5],
[.66, .66, .66]])
color_names = \
['black', 'blue', 'darkblue', 'skyblue',
'greyblue', 'lilac', 'green', 'red',
'cyan', 'violet', 'yellow', 'white',
'darkgrey', 'mediumgrey', 'lightgrey']
#Train a 20x30 SOM with 400 iterations
som = SOM(20, 20, 3, 400)
som.train(colors)
#Get output grid
image_grid = som.get_centroids()
#Map colours to their closest neurons
mapped = som.map_vects(colors)
#Plot
plt.imshow(image_grid)
plt.title('Color SOM')
for i, m in enumerate(mapped):
plt.text(m[1], m[0], color_names[i], ha='center', va='center',
bbox=dict(facecolor='white', alpha=0.5, lw=0))
plt.show() | {
"content_hash": "f55ca3fde2eb0f40bab4fd4f7a77524c",
"timestamp": "",
"source": "github",
"line_count": 245,
"max_line_length": 78,
"avg_line_length": 37.59183673469388,
"alnum_prop": 0.5529858849077091,
"repo_name": "uqyge/combustionML",
"id": "70ebdfb5a5d7b54a381a38aeedd7a6180bcde05c",
"size": "9210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "som/som.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4525"
},
{
"name": "C++",
"bytes": "144009"
},
{
"name": "Dockerfile",
"bytes": "816"
},
{
"name": "Jupyter Notebook",
"bytes": "40959474"
},
{
"name": "Makefile",
"bytes": "1310"
},
{
"name": "Python",
"bytes": "276493"
},
{
"name": "Shell",
"bytes": "285"
}
],
"symlink_target": ""
} |
package aurelienribon.bodyeditor.canvas.rigidbodies.input;
import aurelienribon.bodyeditor.Ctx;
import aurelienribon.bodyeditor.canvas.Canvas;
import aurelienribon.bodyeditor.canvas.InputHelper;
import aurelienribon.bodyeditor.canvas.rigidbodies.RigidBodiesScreen;
import aurelienribon.bodyeditor.models.RigidBodyModel;
import aurelienribon.bodyeditor.models.ShapeModel;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Aurelien Ribon | http://www.aurelienribon.com/
*/
public class EditionInputProcessor extends InputAdapter {
private final Canvas canvas;
private final RigidBodiesScreen screen;
private boolean touchDown = false;
private Vector2 draggedPoint;
public EditionInputProcessor(Canvas canvas, RigidBodiesScreen screen) {
this.canvas = canvas;
this.screen = screen;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
touchDown = button == Buttons.LEFT;
if (!touchDown) return false;
RigidBodyModel model = Ctx.bodies.getSelectedModel();
if (model == null) return false;
draggedPoint = screen.nearestPoint;
if (draggedPoint == null) {
screen.mouseSelectionP1 = canvas.screenToWorld(x, y);
} else {
if (draggedPoint == model.getOrigin()) {
screen.selectedPoints.clear();
} else if (InputHelper.isCtrlDown()) {
if (screen.selectedPoints.contains(draggedPoint)) screen.selectedPoints.remove(draggedPoint);
else screen.selectedPoints.add(draggedPoint);
} else if (!screen.selectedPoints.contains(draggedPoint)) {
screen.selectedPoints.replaceBy(draggedPoint);
}
}
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
if (!touchDown) return false;
touchDown = false;
RigidBodyModel model = Ctx.bodies.getSelectedModel();
if (model == null) return false;
if (draggedPoint != null) {
draggedPoint = null;
model.computePhysics();
screen.buildBody();
} else if (screen.mouseSelectionP2 != null) {
if (InputHelper.isCtrlDown()) {
for (Vector2 p : getPointsInSelection()) {
if (screen.selectedPoints.contains(p)) screen.selectedPoints.remove(p);
else screen.selectedPoints.add(p);
}
} else {
screen.selectedPoints.replaceBy(getPointsInSelection());
}
} else {
screen.selectedPoints.clear();
}
screen.mouseSelectionP1 = null;
screen.mouseSelectionP2 = null;
return false;
}
@Override
public boolean touchDragged(int x, int y, int pointer) {
if (!touchDown) return false;
RigidBodyModel model = Ctx.bodies.getSelectedModel();
if (model == null) return false;
if (draggedPoint != null) {
Vector2 p = canvas.alignedScreenToWorld(x, y);
model.clearPhysics();
float dx = p.x - draggedPoint.x;
float dy = p.y - draggedPoint.y;
draggedPoint.add(dx, dy);
for (int i = 0; i < screen.selectedPoints.size(); i++) {
Vector2 sp = screen.selectedPoints.get(i);
if (sp != draggedPoint) sp.add(dx, dy);
}
} else {
screen.mouseSelectionP2 = canvas.screenToWorld(x, y);
}
return false;
}
@Override
public boolean mouseMoved(int x, int y) {
RigidBodyModel model = Ctx.bodies.getSelectedModel();
if (model == null) return false;
// Nearest point computation
Vector2 p = canvas.screenToWorld(x, y);
screen.nearestPoint = null;
float dist = 0.025f * canvas.worldCamera.zoom;
for (Vector2 v : getAllPoints()) {
if (v.dst(p) < dist) screen.nearestPoint = v;
}
return false;
}
@Override
public boolean keyDown(int keycode) {
switch (keycode) {
case Keys.ENTER:
screen.insertPointsBetweenSelected();
break;
case Keys.BACKSPACE:
screen.removeSelectedPoints();
break;
}
return false;
}
// -------------------------------------------------------------------------
private List<Vector2> getPointsInSelection() {
RigidBodyModel model = Ctx.bodies.getSelectedModel();
List<Vector2> points = new ArrayList<Vector2>();
Vector2 p1 = screen.mouseSelectionP1;
Vector2 p2 = screen.mouseSelectionP2;
if (p1 != null && p2 != null) {
Rectangle rect = new Rectangle(
Math.min(p1.x, p2.x),
Math.min(p1.y, p2.y),
Math.abs(p2.x - p1.x),
Math.abs(p2.y - p1.y)
);
for (Vector2 p : getAllPoints()) {
if (p == model.getOrigin()) continue;
if (rect.contains(p.x, p.y)) points.add(p);
}
}
return Collections.unmodifiableList(points);
}
private List<Vector2> getAllPoints() {
List<Vector2> points = new ArrayList<Vector2>();
RigidBodyModel model = Ctx.bodies.getSelectedModel();
for (ShapeModel shape : model.getShapes()) {
points.addAll(shape.getVertices());
}
points.add(model.getOrigin());
return Collections.unmodifiableList(points);
}
}
| {
"content_hash": "401655dae68eb39e25693404af7335b2",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 109,
"avg_line_length": 31.3475935828877,
"alnum_prop": 0.5861480723302627,
"repo_name": "MovingBlocks/box2d-editor",
"id": "783db87504015c4b32fe205c744e5d5172d4992c",
"size": "5862",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "editor/src/main/java/aurelienribon/bodyeditor/canvas/rigidbodies/input/EditionInputProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3800"
},
{
"name": "Java",
"bytes": "348916"
}
],
"symlink_target": ""
} |
namespace Nest
{
public abstract class LinearDecayFunction<TOrigin, TScale> : DecayFunctionBase<TOrigin, TScale>
{
protected override string DecayType => "linear";
}
public class LinearDecayFunctionDescriptor<TOrigin, TScale, T> : DecayFunctionBaseDescriptor<LinearDecayFunctionDescriptor<TOrigin, TScale, T>, TOrigin, TScale, T>
where T : class
{
protected override string DecayType => "linear";
}
public class LinearDecayFunction : LinearDecayFunction<double?, double?> { }
public class LinearDateDecayFunction : LinearDecayFunction<DateMath, Time> { }
public class LinearGeoDecayFunction : LinearDecayFunction<GeoLocation, Distance> { }
} | {
"content_hash": "bf2ce1487722b322af8ce0cbf6648093",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 164,
"avg_line_length": 41.0625,
"alnum_prop": 0.7853881278538812,
"repo_name": "KodrAus/elasticsearch-net",
"id": "a2522b592207f19d56e76fe74ddf8f14a5915e85",
"size": "657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Nest/QueryDsl/Compound/FunctionScore/Functions/Decay/LinearDecayFunction.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "676"
},
{
"name": "C#",
"bytes": "5459077"
},
{
"name": "F#",
"bytes": "27429"
},
{
"name": "HTML",
"bytes": "94008"
},
{
"name": "Shell",
"bytes": "698"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
namespace ExcelPlanarMechSimulator
{
public partial class Sheet3
{
private void Sheet3_Startup(object sender, System.EventArgs e)
{
}
private void Sheet3_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(Sheet3_Startup);
this.Shutdown += new System.EventHandler(Sheet3_Shutdown);
}
#endregion
}
}
| {
"content_hash": "e6bcd52d9d5463bd71139e353b47f36e",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 71,
"avg_line_length": 27.289473684210527,
"alnum_prop": 0.6335583413693346,
"repo_name": "DesignEngrLab/PMKS",
"id": "43f75d201e2d3c9cd54249d6d144d70b7ab29a26",
"size": "1039",
"binary": false,
"copies": "1",
"ref": "refs/heads/SilverlightFinal",
"path": "ExcelPlanarMechSimulator/Sheet3.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "803654"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
in de Candolle & Lamarck, Fl. franç. (Paris), Edn 3 5/6: 62 (1815)
#### Original name
Puccinia violae subsp. violae
### Remarks
null | {
"content_hash": "8744644ee1d04abce9c9037bab1487f4",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 66,
"avg_line_length": 15.076923076923077,
"alnum_prop": 0.6836734693877551,
"repo_name": "mdoering/backbone",
"id": "ec605d42d7f1a2c4037dea321db4ee1ece75fa1b",
"size": "253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia violae/Puccinia violae violae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.jsp.include_005fjsp.reponses;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class myMessageListenClin_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_bean_define_property_name_id_nobody;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_bean_define_property_name_id_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_bean_define_property_name_id_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write('\r');
out.write('\n');
response.setContentType("text/html;charset=UTF-8");
out.write("\r\n\r\n\r\n\r\n\r\n\r\n");
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_define_0 = (org.apache.struts.taglib.bean.DefineTag) _jspx_tagPool_bean_define_property_name_id_nobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_define_0.setPageContext(_jspx_page_context);
_jspx_th_bean_define_0.setParent(null);
_jspx_th_bean_define_0.setName("myMessagesSendClinForm");
_jspx_th_bean_define_0.setProperty("url");
_jspx_th_bean_define_0.setId("url");
int _jspx_eval_bean_define_0 = _jspx_th_bean_define_0.doStartTag();
if (_jspx_th_bean_define_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_bean_define_property_name_id_nobody.reuse(_jspx_th_bean_define_0);
return;
}
_jspx_tagPool_bean_define_property_name_id_nobody.reuse(_jspx_th_bean_define_0);
java.lang.Object url = null;
url = (java.lang.Object) _jspx_page_context.findAttribute("url");
out.write('\r');
out.write('\n');
out.print(url);
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| {
"content_hash": "e6c3d75a9204965711fefca160b933eb",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 214,
"avg_line_length": 38.31764705882353,
"alnum_prop": 0.6785385323917715,
"repo_name": "sebastienhouzet/nabaztag-source-code",
"id": "432cf6b437e7b1d7e625416cda130499e236f90e",
"size": "3257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/MyNabaztag/build/WEB-INF/src/org/apache/jsp/include_005fjsp/reponses/myMessageListenClin_jsp.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "20745"
},
{
"name": "Batchfile",
"bytes": "8750"
},
{
"name": "C",
"bytes": "4993666"
},
{
"name": "C++",
"bytes": "1334194"
},
{
"name": "CSS",
"bytes": "181849"
},
{
"name": "Dylan",
"bytes": "98"
},
{
"name": "HTML",
"bytes": "788676"
},
{
"name": "Inno Setup",
"bytes": "532"
},
{
"name": "Java",
"bytes": "13700728"
},
{
"name": "JavaScript",
"bytes": "710228"
},
{
"name": "Lex",
"bytes": "4485"
},
{
"name": "Makefile",
"bytes": "9861"
},
{
"name": "PHP",
"bytes": "44903"
},
{
"name": "Perl",
"bytes": "12017"
},
{
"name": "Ruby",
"bytes": "2935"
},
{
"name": "Shell",
"bytes": "40087"
},
{
"name": "SourcePawn",
"bytes": "21480"
},
{
"name": "TeX",
"bytes": "13161"
}
],
"symlink_target": ""
} |
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Mikael Lagerkvist <lagerkvist@gecode.org>
*
* Copyright:
* Mikael Lagerkvist, 2005
*
* Last modified:
* $Date: 2011-05-25 16:56:41 +0200 (Wed, 25 May 2011) $ by $Author: schulte $
* $Revision: 12022 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "test/int.hh"
#include <gecode/minimodel.hh>
#include <gecode/search.hh>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
namespace Test { namespace Int {
/// %Tests for scheduling constraints
namespace Cumulatives {
/**
* \defgroup TaskTestIntCumulatives Cumnulatives scheduling constraint
* \ingroup TaskTestInt
*/
//@{
/**
* \brief Script for generating assignments.
*
* We are only interested in assignments that represent tasks (s_i,
* d_i, e_i, h_i) such that the following hold:
* - The task starts at a positive time and has some extension.
* - The equation s_i + d_i = e_i holds.
* - The tasks are ordered to remove some symmetries, i.e.,
* s_i <= s_{i+1}
*/
class Ass : public Gecode::Space {
public:
/// Store task information
Gecode::IntVarArray x;
/// Initialize model for assignments
Ass(int n, const Gecode::IntSet& d) : x(*this, n, d) {
using namespace Gecode;
for (int i = 0; i < n; i += 4) {
rel(*this, x[i+0] >= 0);
rel(*this, x[i+1] >= 0);
rel(*this, x[i+2] >= 0);
rel(*this, x[i] + x[i+1] == x[i+2]);
branch(*this, x, INT_VAR_NONE, INT_VAL_MIN);
}
}
/// Constructor for cloning \a s
Ass(bool share, Ass& s) : Gecode::Space(share,s) {
x.update(*this, share, s.x);
}
/// Create copy during cloning
virtual Gecode::Space* copy(bool share) {
return new Ass(share,*this);
}
};
/// Class for generating reasonable assignments
class CumulativeAssignment : public Assignment {
/// Current assignment
Ass* cur;
/// Next assignment
Ass* nxt;
/// Search engine to find assignments
Gecode::DFS<Ass>* e;
public:
/// Initialize assignments for \a n0 variables and values \a d0
CumulativeAssignment(int n, const Gecode::IntSet& d) : Assignment(n,d) {
Ass* a = new Ass(n, d);
e = new Gecode::DFS<Ass>(a);
delete a;
nxt = cur = e->next();
if (cur != NULL)
nxt = e->next();
}
/// %Test whether all assignments have been iterated
virtual bool operator()(void) const {
return nxt != NULL;
}
/// Move to next assignment
virtual void operator++(void) {
delete cur;
cur = nxt;
if (cur != NULL) nxt = e->next();
}
/// Return value for variable \a i
virtual int operator[](int i) const {
assert((i>=0) && (i<n) && (cur != NULL));
return cur->x[i].val();
}
/// Destructor
virtual ~CumulativeAssignment(void) {
delete cur; delete nxt; delete e;
}
};
/// %Event to be scheduled
class Event {
public:
int p, h; ///< Position and height of event
bool start; ///< Whether event has just started
/// Initialize event
Event(int pos, int height, bool s) : p(pos), h(height), start(s) {}
/// %Test whether this event is before event \a e
bool operator<(const Event& e) const {
return p<e.p;
}
};
/// Describe that event is below a certain limit
class Below {
public:
int limit; ///< limit
/// Initialize
Below(int l) : limit(l) {}
/// %Test whether \a val is below limit
bool operator()(int val) {
return val <= limit;
}
};
/// Describe that event is above a certain limit
class Above {
public:
int limit; ///< limit
/// Initialize
Above(int l) : limit(l) {}
/// %Test whether \a val is above limit
bool operator()(int val) {
return val >= limit;
}
};
/// Check whether event \a e is valid
template<class C>
bool valid(std::vector<Event> e, C comp) {
std::sort(e.begin(), e.end());
unsigned int i = 0;
int p = 0;
int h = 0;
int n = 0;
while (i < e.size()) {
p = e[i].p;
while (i < e.size() && e[i].p == p) {
h += e[i].h;
n += (e[i].start ? +1 : -1);
++i;
}
if (n && !comp(h))
return false;
}
return true;
}
/// %Test for cumulatives constraint
class Cumulatives : public Test {
protected:
int ntasks; ///< Number of tasks
bool at_most; ///< Whether to use atmost reasoning
int limit; ///< Limit
public:
/// Create and register test
Cumulatives(const std::string& s, int nt, bool am, int l)
: Test("Cumulatives::"+s,nt*4,-1,2), ntasks(nt), at_most(am), limit(l) {
testsearch = false;
}
/// Create first assignment
virtual Assignment* assignment(void) const {
assert(arity == 4*ntasks);
return new CumulativeAssignment(arity, dom);
}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
std::vector<Event> e;
for (int i = 0; i < ntasks; ++i) {
int p = i*4;
// Positive start, duration and end
if (x[p+0] < 0 || x[p+1] < 1 || x[p+2] < 1) return false;
// Start + Duration == End
if (x[p+0] + x[p+1] != x[p+2]) {
return false;
}
}
for (int i = 0; i < ntasks; ++i) {
int p = i*4;
// Up at start, down at end.
e.push_back(Event(x[p+0], +x[p+3], true));
e.push_back(Event(x[p+2], -x[p+3], false));
}
if (at_most) {
return valid(e, Below(limit));
} else {
return valid(e, Above(limit));
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
IntArgs m(ntasks), l(1, limit);
IntVarArgs s(ntasks), d(ntasks), e(ntasks), h(ntasks);
for (int i = 0; i < ntasks; ++i) {
int p = i*4;
m[i] = 0;
s[i] = x[p+0]; rel(home, x[p+0], Gecode::IRT_GQ, 0);
d[i] = x[p+1]; rel(home, x[p+1], Gecode::IRT_GQ, 1);
e[i] = x[p+2]; rel(home, x[p+2], Gecode::IRT_GQ, 1);
h[i] = x[p+3];
}
cumulatives(home, m, s, d, e, h, l, at_most);
}
};
Cumulatives c1t1("1t1", 1, true, 1);
Cumulatives c1f1("1f1", 1, false, 1);
Cumulatives c1t2("1t2", 1, true, 2);
Cumulatives c1f2("1f2", 1, false, 2);
Cumulatives c1t3("1t3", 1, true, 3);
Cumulatives c1f3("1f3", 1, false, 3);
Cumulatives c2t1("2t1", 2, true, 1);
Cumulatives c2f1("2f1", 2, false, 1);
Cumulatives c2t2("2t2", 2, true, 2);
Cumulatives c2f2("2f2", 2, false, 2);
Cumulatives c2t3("2t3", 2, true, 3);
Cumulatives c2f3("2f3", 2, false, 3);
Cumulatives c3t1("3t1", 3, true, 1);
Cumulatives c3f1("3f1", 3, false, 1);
Cumulatives c3t2("3t2", 3, true, 2);
Cumulatives c3f2("3f2", 3, false, 2);
Cumulatives c3t3("3t3", 3, true, 3);
Cumulatives c3f3("3f3", 3, false, 3);
Cumulatives c3t_1("3t-1", 3, true, -1);
Cumulatives c3f_1("3f-1", 3, false, -1);
Cumulatives c3t_2("3t-2", 3, true, -2);
Cumulatives c3f_2("3f-2", 3, false, -2);
Cumulatives c3t_3("3t-3", 3, true, -3);
Cumulatives c3f_3("3f-3", 3, false, -3);
//@}
}
}}
// STATISTICS: test-int
| {
"content_hash": "3ea5db0a5e5382459b4549df9f355043",
"timestamp": "",
"source": "github",
"line_count": 276,
"max_line_length": 82,
"avg_line_length": 33.094202898550726,
"alnum_prop": 0.5403985110575871,
"repo_name": "racker/omnibus",
"id": "3ab797f2b6341c441e3e352d943fb7e4dca8fde0",
"size": "9134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/gecode-3.7.1/test/int/cumulatives.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "21896"
},
{
"name": "ActionScript",
"bytes": "7811"
},
{
"name": "Ada",
"bytes": "913692"
},
{
"name": "Assembly",
"bytes": "546596"
},
{
"name": "Awk",
"bytes": "147229"
},
{
"name": "C",
"bytes": "118056858"
},
{
"name": "C#",
"bytes": "1871806"
},
{
"name": "C++",
"bytes": "28581121"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "162089"
},
{
"name": "Clojure",
"bytes": "79070"
},
{
"name": "D",
"bytes": "4925"
},
{
"name": "DOT",
"bytes": "1898"
},
{
"name": "Emacs Lisp",
"bytes": "625560"
},
{
"name": "Erlang",
"bytes": "79712366"
},
{
"name": "FORTRAN",
"bytes": "3755"
},
{
"name": "Java",
"bytes": "5632652"
},
{
"name": "JavaScript",
"bytes": "1240931"
},
{
"name": "Logos",
"bytes": "119270"
},
{
"name": "Objective-C",
"bytes": "1088478"
},
{
"name": "PHP",
"bytes": "39064"
},
{
"name": "Pascal",
"bytes": "66389"
},
{
"name": "Perl",
"bytes": "4971637"
},
{
"name": "PowerShell",
"bytes": "1885"
},
{
"name": "Prolog",
"bytes": "5214"
},
{
"name": "Python",
"bytes": "912999"
},
{
"name": "R",
"bytes": "4009"
},
{
"name": "Racket",
"bytes": "2713"
},
{
"name": "Ragel in Ruby Host",
"bytes": "24585"
},
{
"name": "Rebol",
"bytes": "106436"
},
{
"name": "Ruby",
"bytes": "27360215"
},
{
"name": "Scala",
"bytes": "5487"
},
{
"name": "Scheme",
"bytes": "5036"
},
{
"name": "Scilab",
"bytes": "771"
},
{
"name": "Shell",
"bytes": "8793006"
},
{
"name": "Tcl",
"bytes": "3330919"
},
{
"name": "Visual Basic",
"bytes": "10926"
},
{
"name": "XQuery",
"bytes": "4276"
},
{
"name": "XSLT",
"bytes": "2003063"
},
{
"name": "eC",
"bytes": "4568"
}
],
"symlink_target": ""
} |
package org.opengts.dbtypes;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.io.*;
import java.sql.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
public class DTProfileMask
extends DBFieldType
{
// ------------------------------------------------------------------------
private byte profileMask[] = new byte[0];
public DTProfileMask(byte profileMask[])
{
this.profileMask = (profileMask != null)? profileMask : new byte[0];
}
public DTProfileMask(String val)
{
super(val);
this.profileMask = DBField.parseBlobString(val);
if (this.profileMask == null) {
// -- should not occur
this.profileMask = new byte[0];
}
}
public DTProfileMask(ResultSet rs, String fldName)
throws SQLException
{
super(rs, fldName);
// -- set to default value if 'rs' is null
this.profileMask = (rs != null)? rs.getBytes(fldName) : new byte[0];
if (this.profileMask == null) {
// -- should not occur
this.profileMask = new byte[0];
}
}
// ------------------------------------------------------------------------
public Object getObject()
{
//Print.logWarn("ProfileMask length = " + this.profileMask.length);
return this.profileMask;
}
public String toString()
{
return "0x" + StringTools.toHexString(this.profileMask);
}
// ------------------------------------------------------------------------
public void setLimitTimeInterval(int minutes)
{
int byteLen = (minutes + 7) / 8;
if (this.profileMask.length != byteLen) {
byte newMask[] = new byte[byteLen];
if (newMask.length > 0) {
int len = (this.profileMask.length < byteLen)? this.profileMask.length : byteLen;
System.arraycopy(this.profileMask, 0, newMask, 0, len);
}
this.profileMask = newMask;
}
}
// ------------------------------------------------------------------------
public byte[] getByteMask()
{
return this.profileMask;
}
}
| {
"content_hash": "2a5caa3253ad57d50729efa5a759a863",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 97,
"avg_line_length": 27.024390243902438,
"alnum_prop": 0.4891696750902527,
"repo_name": "paragp/GTS-PreUAT",
"id": "0beac527430bec85d50984f61b643bfc1aaa4ec8",
"size": "3305",
"binary": false,
"copies": "2",
"ref": "refs/heads/GTS-PreUAT",
"path": "src/org/opengts/dbtypes/DTProfileMask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17573"
},
{
"name": "CSS",
"bytes": "125062"
},
{
"name": "Java",
"bytes": "11912252"
},
{
"name": "JavaScript",
"bytes": "1642398"
},
{
"name": "Perl",
"bytes": "65030"
},
{
"name": "Shell",
"bytes": "69213"
}
],
"symlink_target": ""
} |
using NUnit.Framework;
using static Ghpr.NUnitExamples.ResultHelper;
namespace Ghpr.NUnitExamples.Cat3
{
[TestFixture]
public class TestClass12
{
[Test]
[Category("Cat3")]
public void RandomResultTest1()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest2()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest3()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest4()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest5()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest6()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest7()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest8()
{
RandomResultMethod();
}
[Test]
[Category("Cat3")]
public void RandomResultTest9()
{
RandomResultMethod();
}
}
} | {
"content_hash": "c3b8e48dc5cfd6632717e2cb6b0f1943",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 45,
"avg_line_length": 19.430555555555557,
"alnum_prop": 0.47962830593280914,
"repo_name": "GHPReporter/Ghpr.NUnit.Examples",
"id": "f1e65c67f4e5113d0a7ac4bee367888d990f8df8",
"size": "1401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghpr.NUnitExamples/Cat3/TestClass12.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "38138"
}
],
"symlink_target": ""
} |
package nl.knaw.dans.common.lang.collect;
/**
* Generic interface for decorating a {@link Collector}.
*
* @param <T> the type or container type for collected things.
*/
public interface CollectorDecorator<T> extends Collector<T>
{
}
| {
"content_hash": "be7b42f2bb230c5282b8dc39c1f1edaa",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 62,
"avg_line_length": 20,
"alnum_prop": 0.725,
"repo_name": "PaulBoon/dccd-legacy-libs",
"id": "5d75938febed487576df4a7713985f5ecfc108c0",
"size": "1023",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lang/src/main/java/nl/knaw/dans/common/lang/collect/CollectorDecorator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10948"
},
{
"name": "HTML",
"bytes": "20779"
},
{
"name": "Java",
"bytes": "2232276"
},
{
"name": "JavaScript",
"bytes": "47338"
},
{
"name": "Shell",
"bytes": "4282"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.06.01 at 06:36:07 PM UYT
//
package dgi.classes.recepcion;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for IdDoc_Resg complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="IdDoc_Resg">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TipoCFE">
* <simpleType>
* <restriction base="{http://cfe.dgi.gub.uy}CFEType">
* <enumeration value="182"/>
* <enumeration value="282"/>
* </restriction>
* </simpleType>
* </element>
* <element name="Serie" type="{http://cfe.dgi.gub.uy}SerieType"/>
* <element name="Nro" type="{http://cfe.dgi.gub.uy}NroCFEType"/>
* <element name="FchEmis" type="{http://cfe.dgi.gub.uy}FechaType"/>
* <element name="InfoAdicionalDoc" type="{http://cfe.dgi.gub.uy}InfoAdicionalType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IdDoc_Resg", namespace = "http://cfe.dgi.gub.uy", propOrder = {
"tipoCFE",
"serie",
"nro",
"fchEmis",
"infoAdicionalDoc"
})
public class IdDocResg {
@XmlElement(name = "TipoCFE", required = true)
protected BigInteger tipoCFE;
@XmlElement(name = "Serie", required = true)
protected String serie;
@XmlElement(name = "Nro", required = true)
protected BigInteger nro;
@XmlElement(name = "FchEmis", required = true)
protected XMLGregorianCalendar fchEmis;
@XmlElement(name = "InfoAdicionalDoc")
protected String infoAdicionalDoc;
/**
* Gets the value of the tipoCFE property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getTipoCFE() {
return tipoCFE;
}
/**
* Sets the value of the tipoCFE property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setTipoCFE(BigInteger value) {
this.tipoCFE = value;
}
/**
* Gets the value of the serie property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSerie() {
return serie;
}
/**
* Sets the value of the serie property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSerie(String value) {
this.serie = value;
}
/**
* Gets the value of the nro property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNro() {
return nro;
}
/**
* Sets the value of the nro property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNro(BigInteger value) {
this.nro = value;
}
/**
* Gets the value of the fchEmis property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFchEmis() {
return fchEmis;
}
/**
* Sets the value of the fchEmis property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFchEmis(XMLGregorianCalendar value) {
this.fchEmis = value;
}
/**
* Gets the value of the infoAdicionalDoc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInfoAdicionalDoc() {
return infoAdicionalDoc;
}
/**
* Sets the value of the infoAdicionalDoc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfoAdicionalDoc(String value) {
this.infoAdicionalDoc = value;
}
}
| {
"content_hash": "a235f78b1cfd3a3e2bf6988144111b82",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 111,
"avg_line_length": 25.026178010471206,
"alnum_prop": 0.5705020920502092,
"repo_name": "nicoribeiro/java_efactura_uy",
"id": "6b03371bce45ac4c592b509c7bdb583c7b6b6206",
"size": "4780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/dgi/classes/recepcion/IdDocResg.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "41"
},
{
"name": "HTML",
"bytes": "577"
},
{
"name": "Java",
"bytes": "3139352"
},
{
"name": "JavaScript",
"bytes": "88"
},
{
"name": "PLpgSQL",
"bytes": "2207"
},
{
"name": "Scala",
"bytes": "4184"
},
{
"name": "Shell",
"bytes": "14722"
}
],
"symlink_target": ""
} |
FROM balenalib/kitra520-debian:buster-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.9.4
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \
&& echo "fe3cb03bf50d2128ff7c98e16308c5c2c4363983c87e26e0ffe4b280bf78e070 Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.8
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.4, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "2337c7cc088107c0c9f1b77a8ff78a01",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 710,
"avg_line_length": 50.863157894736844,
"alnum_prop": 0.7036423841059603,
"repo_name": "nghiant2710/base-images",
"id": "16a707599573e3ddad7c96cd00aecce5ea0e7f42",
"size": "4853",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/python/kitra520/debian/buster/3.9.4/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
#ifndef _MITK_VTK_REPRESENTATION_PROPERTY__H_
#define _MITK_VTK_REPRESENTATION_PROPERTY__H_
#include "mitkEnumerationProperty.h"
namespace mitk
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4522)
#endif
/**
* Encapsulates the enumeration vtkRepresentation. Valid values are
* (VTK constant/Id/string representation):
* VTK_POINTS/0/Points, VTK_WIREFRAME/1/Wireframe, VTK_SURFACE/2/Surface
* Default is the Surface representation
*/
class MITKCORE_EXPORT VtkRepresentationProperty : public EnumerationProperty
{
public:
mitkClassMacro(VtkRepresentationProperty, EnumerationProperty);
itkFactorylessNewMacro(Self) itkCloneMacro(Self)
mitkNewMacro1Param(VtkRepresentationProperty, const IdType &);
mitkNewMacro1Param(VtkRepresentationProperty, const std::string &);
/**
* Returns the current representation value as defined by VTK constants.
* @returns the current representation as VTK constant.
*/
virtual int GetVtkRepresentation();
/**
* Sets the representation type to VTK_POINTS.
*/
virtual void SetRepresentationToPoints();
/**
* Sets the representation type to VTK_WIREFRAME.
*/
virtual void SetRepresentationToWireframe();
/**
* Sets the representation type to VTK_SURFACE.
*/
virtual void SetRepresentationToSurface();
using BaseProperty::operator=;
protected:
/**
* Constructor. Sets the representation to a default value of Surface(2)
*/
VtkRepresentationProperty();
/**
* Constructor. Sets the representation to the given value. If it is not
* valid, the representation is set to Surface(2)
* @param value the integer representation of the representation
*/
VtkRepresentationProperty(const IdType &value);
/**
* Constructor. Sets the representation to the given value. If it is not
* valid, the representation is set to Surface(2)
* @param value the string representation of the representation
*/
VtkRepresentationProperty(const std::string &value);
/**
* this function is overridden as protected, so that the user may not add
* additional invalid representation types.
*/
virtual bool AddEnum(const std::string &name, const IdType &id) override;
/**
* Adds the enumeration types as defined by vtk to the list of known
* enumeration values.
*/
virtual void AddRepresentationTypes();
private:
// purposely not implemented
VtkRepresentationProperty &operator=(const VtkRepresentationProperty &);
virtual itk::LightObject::Pointer InternalClone() const override;
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // end of namespace mitk
#endif
| {
"content_hash": "27cdcfe9bd0946a9a4faa4be9bf0ba59",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 78,
"avg_line_length": 27.80808080808081,
"alnum_prop": 0.705775517617145,
"repo_name": "iwegner/MITK",
"id": "dd0cb9de28bf4bc6d85a1c54fa7d6af507b6fe25",
"size": "3251",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Modules/Core/include/mitkVtkRepresentationProperty.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3340295"
},
{
"name": "C++",
"bytes": "31705331"
},
{
"name": "CMake",
"bytes": "985642"
},
{
"name": "CSS",
"bytes": "118558"
},
{
"name": "HTML",
"bytes": "102168"
},
{
"name": "JavaScript",
"bytes": "162600"
},
{
"name": "Jupyter Notebook",
"bytes": "228462"
},
{
"name": "Makefile",
"bytes": "25077"
},
{
"name": "Objective-C",
"bytes": "26578"
},
{
"name": "Python",
"bytes": "275885"
},
{
"name": "QML",
"bytes": "28009"
},
{
"name": "QMake",
"bytes": "5583"
},
{
"name": "Shell",
"bytes": "1261"
}
],
"symlink_target": ""
} |
<?php
namespace Rithis\Spriter;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use FilesystemIterator;
use CallbackFilterIterator;
use SplFileInfo;
use Imagine\Image\ImagineInterface;
class Spriter
{
private $imagine;
public function __construct(ImagineInterface $imagine)
{
$this->imagine = $imagine;
}
public function scan($directory, $recursive = true)
{
if ($recursive) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
} else {
$iterator = new FilesystemIterator($directory);
}
$iterator = new CallbackFilterIterator($iterator, function (SplFileInfo $file) {
return in_array($file->getExtension(), array('png', 'jpg', 'jpeg', 'gif'));
});
return new Sprite($iterator, $this->imagine);
}
}
| {
"content_hash": "cd614e6b596acbe32d9eeaa244a908ad",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 98,
"avg_line_length": 24.36111111111111,
"alnum_prop": 0.6556442417331813,
"repo_name": "vslinko-archive/spriter",
"id": "3e39d8ff3494580aeb62e07933c36f8c80fd365d",
"size": "981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Spriter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "19055"
},
{
"name": "Perl",
"bytes": "475"
}
],
"symlink_target": ""
} |
import type { CSeriesBasic, LegendPositions } from '../types';
export declare type CommonAxisConfig = {
/**
* Render grid lines in chart
*/
gridlines?: boolean;
/**
* Axis label content, disabled with `false`
*/
label?: string | false;
/**
* Render axis values
*/
values?: boolean;
};
export declare type XAxisConfig = CommonAxisConfig & {
/**
* Reverse data direction
*/
reversed?: boolean;
};
export declare type YAxisEndpoint = number | 'auto' | undefined;
export declare type YAxisConfig = CommonAxisConfig & {
/**
* Set min and max values for Y-Axis
*/
range?: [YAxisEndpoint, YAxisEndpoint];
};
export declare type CartesianLegend = {
/**
* Determines position of legend items
*/
position: LegendPositions;
/**
* Width in pixels when legend is left or right positioned
*/
width?: number;
};
export declare type CommonCartesianProperties = {
/**
* Toggle tooltips on hover
*/
tooltips?: boolean;
/**
* Configure legend properties, or disable it altogether by setting value to false.
*/
legend?: false | CartesianLegend;
/**
* Customize the series settings either by an ordered array or a named object.
* Can be used like series: [{color: '#000000'}] or series: { name: { color: '#000000' }}
*/
series?: CSeriesBasic[] | {
[key: string]: CSeriesBasic;
};
/**
* Configure an array of x-axis settings. Charts will only render a single x-axis for now.
*/
x_axis?: XAxisConfig[];
/**
* Configure an array of y-axis settings.
*/
y_axis?: YAxisConfig[];
};
| {
"content_hash": "f7f82cbb7a624dc7e7cd9f784358cdf0",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 94,
"avg_line_length": 26.793650793650794,
"alnum_prop": 0.6066350710900474,
"repo_name": "looker-open-source/components",
"id": "ea6dab9ea802c56436d9fce184333899a8dd82c2",
"size": "1688",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/visualizations-adapters/lib/types/cartesian.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10788"
},
{
"name": "HTML",
"bytes": "10602733"
},
{
"name": "JavaScript",
"bytes": "125821"
},
{
"name": "Shell",
"bytes": "5731"
},
{
"name": "TypeScript",
"bytes": "6564851"
}
],
"symlink_target": ""
} |
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import java.util.Iterator;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
public abstract class CordovaHttp {
protected static final String TAG = "CordovaHTTP";
protected static final String CHARSET = "UTF-8";
private static AtomicBoolean sslPinning = new AtomicBoolean(false);
private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false);
private static AtomicBoolean acceptAllHosts = new AtomicBoolean(false);
private String urlString;
private Map<?, ?> params;
private Map<String, String> headers;
private CallbackContext callbackContext;
public CordovaHttp(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.headers = headers;
this.callbackContext = callbackContext;
}
public static void enableSSLPinning(boolean enable) {
sslPinning.set(enable);
if (enable) {
acceptAllCerts.set(false);
}
}
public static void acceptAllCerts(boolean accept) {
acceptAllCerts.set(accept);
if (accept) {
sslPinning.set(false);
}
}
public static void acceptAllHosts(boolean accept) {
acceptAllHosts.set(accept);
}
protected String getUrlString() {
return this.urlString;
}
protected Map<?, ?> getParams() {
return this.params;
}
protected Map<String, String> getHeaders() {
return this.headers;
}
protected CallbackContext getCallbackContext() {
return this.callbackContext;
}
protected HttpRequest setupSecurity(HttpRequest request) {
if (acceptAllCerts.get()) {
request.trustAllCerts();
request.trustAllHosts(true);
}
if (sslPinning.get()) {
request.pinToCerts();
request.trustAllHosts(acceptAllHosts.get());
}
return request;
}
protected void respondWithError(int status, String msg) {
try {
JSONObject response = new JSONObject();
response.put("status", status);
response.put("error", msg);
this.callbackContext.error(response);
} catch (JSONException e) {
this.callbackContext.error(msg);
}
}
protected void respondWithError(String msg) {
this.respondWithError(500, msg);
}
}
| {
"content_hash": "893ba303b5d2ef77b5e0a2646d35e849",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 122,
"avg_line_length": 27.571428571428573,
"alnum_prop": 0.6596502590673575,
"repo_name": "jeremychild/cordova-HTTP",
"id": "c5196c9bedfd0ff093f818329e5dc8050dd038dd",
"size": "3088",
"binary": false,
"copies": "1",
"ref": "refs/heads/wymsee_master",
"path": "src/android/com/synconset/CordovaHTTP/CordovaHttp.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "111526"
},
{
"name": "Objective-C",
"bytes": "358729"
}
],
"symlink_target": ""
} |
package com.github.fakemongo.integration
import com.mongodb.BasicDBObject
import org.scalatest._
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import com.github.fakemongo.Fongo
@RunWith(classOf[JUnitRunner])
class FongoScalaTest extends FunSuite with BeforeAndAfter {
var fongo: Fongo = _
before {
fongo = new Fongo("InMemoryMongo")
}
test("Fongo should not throw npe") {
val db = fongo.getDB("myDB")
val col = db.createCollection("myCollection", new BasicDBObject())
val result = col.findOne()
assert(result == null)
}
test("Insert should work") {
val collection = fongo.getDB("myDB").createCollection("myCollection", new BasicDBObject())
collection.insert(new BasicDBObject("basic", "basic"))
assert(1 === collection.count())
}
}
| {
"content_hash": "5098047993c034971679593acb7aaf65",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 94,
"avg_line_length": 25.34375,
"alnum_prop": 0.717632552404439,
"repo_name": "fakemongo/fongo",
"id": "c720f9936f78398d5a1d8574d171fc12fb508e6a",
"size": "811",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/com/github/fakemongo/integration/FongoScalaTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1234087"
},
{
"name": "Scala",
"bytes": "5866"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Graphics.Shapes;
using osu.Game.Configuration;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Play.HUD.HitErrorMeters
{
[Cached]
public class ColourHitErrorMeter : HitErrorMeter
{
private const int animation_duration = 200;
private const int drawable_judgement_size = 8;
[SettingSource("Judgement count", "The number of displayed judgements")]
public BindableNumber<int> JudgementCount { get; } = new BindableNumber<int>(20)
{
MinValue = 1,
MaxValue = 50,
};
[SettingSource("Judgement spacing", "The space between each displayed judgement")]
public BindableNumber<float> JudgementSpacing { get; } = new BindableNumber<float>(2)
{
MinValue = 0,
MaxValue = 10,
};
[SettingSource("Judgement shape", "The shape of each displayed judgement")]
public Bindable<ShapeStyle> JudgementShape { get; } = new Bindable<ShapeStyle>();
private readonly JudgementFlow judgementsFlow;
public ColourHitErrorMeter()
{
AutoSizeAxes = Axes.Both;
InternalChild = judgementsFlow = new JudgementFlow
{
JudgementShape = { BindTarget = JudgementShape },
JudgementSpacing = { BindTarget = JudgementSpacing },
JudgementCount = { BindTarget = JudgementCount }
};
}
protected override void OnNewJudgement(JudgementResult judgement)
{
if (!judgement.Type.IsScorable() || judgement.Type.IsBonus())
return;
judgementsFlow.Push(GetColourForHitResult(judgement.Type));
}
public override void Clear() => judgementsFlow.Clear();
private class JudgementFlow : FillFlowContainer<HitErrorShape>
{
public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.Reverse();
public readonly Bindable<ShapeStyle> JudgementShape = new Bindable<ShapeStyle>();
public readonly Bindable<float> JudgementSpacing = new Bindable<float>();
public readonly Bindable<int> JudgementCount = new Bindable<int>();
public JudgementFlow()
{
Width = drawable_judgement_size;
Direction = FillDirection.Vertical;
LayoutDuration = animation_duration;
LayoutEasing = Easing.OutQuint;
}
protected override void LoadComplete()
{
base.LoadComplete();
JudgementCount.BindValueChanged(_ =>
{
removeExtraJudgements();
updateMetrics();
});
JudgementSpacing.BindValueChanged(_ => updateMetrics(), true);
}
private readonly DrawablePool<HitErrorShape> judgementLinePool = new DrawablePool<HitErrorShape>(50);
public void Push(Color4 colour)
{
judgementLinePool.Get(shape =>
{
shape.Colour = colour;
Add(shape);
removeExtraJudgements();
});
}
private void removeExtraJudgements()
{
var remainingChildren = Children.Where(c => !c.IsRemoved);
while (remainingChildren.Count() > JudgementCount.Value)
remainingChildren.First().Remove();
}
private void updateMetrics()
{
Height = JudgementCount.Value * (drawable_judgement_size + JudgementSpacing.Value) - JudgementSpacing.Value;
Spacing = new Vector2(0, JudgementSpacing.Value);
}
}
public class HitErrorShape : PoolableDrawable
{
public bool IsRemoved { get; private set; }
public readonly Bindable<ShapeStyle> Shape = new Bindable<ShapeStyle>();
[Resolved]
private ColourHitErrorMeter hitErrorMeter { get; set; } = null!;
private Container content = null!;
public HitErrorShape()
{
Size = new Vector2(drawable_judgement_size);
}
protected override void LoadComplete()
{
base.LoadComplete();
InternalChild = content = new Container
{
RelativeSizeAxes = Axes.Both,
};
Shape.BindTo(hitErrorMeter.JudgementShape);
Shape.BindValueChanged(shape =>
{
switch (shape.NewValue)
{
case ShapeStyle.Circle:
content.Child = new Circle { RelativeSizeAxes = Axes.Both };
break;
case ShapeStyle.Square:
content.Child = new Box { RelativeSizeAxes = Axes.Both };
break;
}
}, true);
}
protected override void PrepareForUse()
{
base.PrepareForUse();
this.FadeInFromZero(animation_duration, Easing.OutQuint)
// On pool re-use, start flow animation from (0,0).
.MoveTo(Vector2.Zero);
content.MoveToY(-DrawSize.Y)
.MoveToY(0, animation_duration, Easing.OutQuint);
}
protected override void FreeAfterUse()
{
base.FreeAfterUse();
IsRemoved = false;
}
public void Remove()
{
IsRemoved = true;
this.FadeOut(animation_duration, Easing.OutQuint)
.Expire();
}
}
public enum ShapeStyle
{
Circle,
Square
}
}
}
| {
"content_hash": "9ab7d39b37d4fc58b1ed7776db5c1168",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 124,
"avg_line_length": 32.26020408163265,
"alnum_prop": 0.5421477146923929,
"repo_name": "peppy/osu",
"id": "86ba85168f9ff6294c838a6c62e80c8e9f2a4d97",
"size": "6473",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "osu.Game/Screens/Play/HUD/HitErrorMeters/ColourHitErrorMeter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "14007692"
},
{
"name": "GLSL",
"bytes": "230"
},
{
"name": "PowerShell",
"bytes": "1988"
},
{
"name": "Ruby",
"bytes": "4185"
},
{
"name": "Shell",
"bytes": "1548"
}
],
"symlink_target": ""
} |
import assign from 'object-assign';
import fillObjectFromPath from './fillObjectFromPath';
import internalCombineNestedValidators from './internalCombineNestedValidators';
export default function ensureNestedValidators(
validators: Object,
options: CombineValidatorsOptions,
): Object {
const baseShape = Object.keys(validators).reduce(
(root, path) => assign(
{},
root,
fillObjectFromPath(root, path.split('.'), validators[path]),
),
{},
);
return internalCombineNestedValidators(baseShape, options);
}
| {
"content_hash": "867f28adca3238c218096d644c6c504f",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 80,
"avg_line_length": 28.736842105263158,
"alnum_prop": 0.7289377289377289,
"repo_name": "jfairbank/revalidate",
"id": "92c2204a23a980fd7bc58c11bc3713c3fc4541e5",
"size": "555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/internal/ensureNestedValidators.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "97874"
}
],
"symlink_target": ""
} |
/* This file left intentionally (almost) blank
Landslide always adds a print.css and a screen.css, but they
are not needed in impress.js, so this theme leaves them blank,
except for hiding some things you want to hide.
You can modify these files in your own fork, or you can add
css-files in the landslide configuration file.
See https://github.com/adamzap/landslide#presentation-configuration
*/
.impress-supported .fallback-message,
.step .notes {
display: none;
}
.step {
width: 1600px;
}
/* Help popup */
#hovercraft-help {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0.5);
color: #EEEEEE;
font-size: 50%;
left: 2em;
bottom: 2em;
width: 26em;
border-radius: 1em;
padding: 1em;
position: fixed;
right: 0;
text-align: center;
z-index: 100;
display: block;
font-family: Verdana, Arial, Sans;
}
.impress-enabled #hovercraft-help.hide {
display: none;
}
/*.impress-enabled #hovercraft-help.show {*/
/*display: block;*/
/*}*/
#hovercraft-help.disabled {
display: none;
}
| {
"content_hash": "43135d7bc81066b69935eebfdad94f03",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 70,
"avg_line_length": 20.884615384615383,
"alnum_prop": 0.6556169429097606,
"repo_name": "mrunge/openstack-overview",
"id": "b3ca6432543c4acd9e7b87958a7a124db87ba520",
"size": "1086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "css/hovercraft.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7002"
},
{
"name": "Makefile",
"bytes": "121"
}
],
"symlink_target": ""
} |
FundCoin Release
FundCoin is a cool new crypto currency that will feature a uniquely implemented anonymization feature that uses exchanges on the back end and a decoupled transaction flow architecture.
This wallet supports the staking=0 option in the FundCoin.conf file to disable the stake miner thread for pool and exchange operators.
| {
"content_hash": "a13e1ad6c3c7edecf9bc08ac77a60cea",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 184,
"avg_line_length": 56.833333333333336,
"alnum_prop": 0.8269794721407625,
"repo_name": "FundCoin/FundCoin",
"id": "f786c8132a1d6eef45700de935f95ee34b68cd22",
"size": "341",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "61562"
},
{
"name": "C",
"bytes": "3068141"
},
{
"name": "C++",
"bytes": "2388607"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "2451"
},
{
"name": "Python",
"bytes": "11646"
},
{
"name": "Shell",
"bytes": "1084"
},
{
"name": "TypeScript",
"bytes": "232200"
}
],
"symlink_target": ""
} |
<?php
/**
* ECSHOP Advertisement management language file
* ============================================================================
* All right reserved (C) 2005-2011 Beijing Yi Shang Interactive Technology
* Development Ltd.
* Web site: http://www.ecshop.com
* ----------------------------------------------------------------------------
* This is a free/open source software;it means that you can modify, use and
* republish the program code, on the premise of that your behavior is not for
* commercial purposes.
* ============================================================================
* $Author: liubo $
* $Id: ads.php 17217 2011-01-19 06:29:08Z liubo $
*/
/* AD-position field information */
$_LANG['position_name'] = 'Name';
$_LANG['ad_width'] = 'Width';
$_LANG['ad_height'] = 'Height';
$_LANG['position_desc'] = 'Description';
$_LANG['posit_width'] = 'Width';
$_LANG['posit_height'] = 'Height';
$_LANG['posit_style'] = 'AD-position ';
$_LANG['outside_posit'] = 'External AD';
$_LANG['outside_address'] = 'Web site name of AD:';
$_LANG['copy_js_code'] = 'Copy JS code';
$_LANG['adsense_code'] = 'External AD JS code';
$_LANG['label_charset'] = 'Select charset:';
$_LANG['no_position'] = 'No position';
$_LANG['no_ads'] = 'You do not have to add ads';
$_LANG['unit_px'] = 'Pixel';
$_LANG['ad_content'] = 'AD contents';
$_LANG['width_and_height'] = '(width*height)';
$_LANG['position_name_empty'] = 'Wrong, the name of AD-position is blank!';
$_LANG['ad_width_empty'] = 'Wrong, the width of AD-position is blank!';
$_LANG['ad_height_empty'] = 'Wrong, the height of AD-position is blank!';
$_LANG['position_desc_empty'] = 'Wrong, the description of AD-position is blank!';
$_LANG['view_static'] = 'View statistics information.';
$_LANG['add_js_code'] = 'Produce and copy the JS code.';
$_LANG['position_add'] = 'Add AD-position';
$_LANG['position_edit'] = 'Edit';
$_LANG['posit_name_exist'] = 'The AD-position has existed!';
$_LANG['download_ad_statistics'] = 'Download Advertisement statistics';
/* JS language item */
$_LANG['js_languages']['posit_name_empty'] = 'Wrong, the name of AD-position is blank!';
$_LANG['js_languages']['ad_width_empty'] = 'Please enter the width of AD-position!';
$_LANG['js_languages']['ad_height_empty'] = 'Please enter the height of AD-position!';
$_LANG['js_languages']['ad_width_number'] = 'The width of AD-position mush be a figure!';
$_LANG['js_languages']['ad_height_number'] = 'The height of AD-position mush be a figure!';
$_LANG['js_languages']['no_outside_address'] = 'We will suggest appoint the name of web site that the AD will be lay-asided,convenient for statistics AD source!';
$_LANG['js_languages']['width_value'] = 'The width of AD-position value must be set between 1 and 1024!';
$_LANG['js_languages']['height_value'] = 'The height of AD-position value must be set between 1 and 1024!';
$_LANG['width_number'] = 'The width of AD-position mush be a figure!';
$_LANG['height_number'] = 'The height of AD-position mush be a figure!';
$_LANG['width_value'] = 'The width of AD-position value must be set between 1 and 1024!';
$_LANG['not_del_adposit'] = 'Wrong, there is an AD, so the AD-position can\'t be deleted!';
/* Help language item */
$_LANG['position_name_notic'] = 'Enter a name of AD-position, for example: footer AD, LOGO AD, the right side AD and so on.';
$_LANG['ad_width_notic'] = 'The width of AD-position, and the height will be the width at the AD displaied , the unit is pixel.';
$_LANG['howto_js'] = 'How to invoke JS code to display AD?';
$_LANG['ja_adcode_notic'] = 'Description of invoked JS AD code.';
/*AD field information */
$_LANG['ad_id'] = 'ID';
$_LANG['position_id'] = 'Position';
$_LANG['media_type'] = 'Media type';
$_LANG['ad_name'] = 'Name';
$_LANG['ad_link'] = 'Link';
$_LANG['ad_code'] = 'Contents';
$_LANG['start_date'] = 'Start date';
$_LANG['end_date'] = 'Deadline';
$_LANG['link_man'] = 'Linkman';
$_LANG['link_email'] = 'Email';
$_LANG['link_phone'] = 'Phone';
$_LANG['click_count'] = 'Click counts';
$_LANG['ads_stats'] = 'Create order';
$_LANG['cleck_referer'] = 'Click source';
$_LANG['adsense_name'] = 'Name';
$_LANG['adsense_js_stats'] = 'External laid JS Statistics';
$_LANG['gen_order_amount'] = 'Total orders quantity';
$_LANG['confirm_order'] = 'Valid orders';
$_LANG['adsense_js_goods'] = 'External JS invoke product';
$_LANG['ad_name_empty'] = 'The AD name can\'t be blank!';
$_LANG['ads_stats_info'] = 'AD statistics information';
$_LANG['flag'] = 'Status';
$_LANG['enabled'] = 'Enabled';
$_LANG['is_enabled'] = 'Enabled';
$_LANG['no_enabled'] = 'Disabled';
$_LANG['back_ads_list'] = 'Return to ADs list.';
$_LANG['back_position_list'] = 'Return to AD position list.';
$_LANG['continue_add_ad'] = 'Continue add AD.';
$_LANG['continue_add_position'] = 'Continue add AD position.';
$_LANG['show_ads_template'] = 'Show AD in template';
$_LANG['ads_add'] = 'Add new advertisement';
$_LANG['ads_edit'] = 'Edit advertisement';
/* Description information */
$_LANG['ad_img'] = 'Image';
$_LANG['ad_flash'] = 'Flash';
$_LANG['ad_html'] = 'Code';
$_LANG['ad_text'] = 'Text';
$_LANG['upfile_flash'] = 'Upload Flash file';
$_LANG['flash_url'] = 'Or Flash website';
$_LANG['upfile_img'] = 'Upload AD image';
$_LANG['img_url'] = 'Or image URL';
$_LANG['enter_code'] = 'Please enter AD code.';
/* JS language item */
$_LANG['js_languages']['ad_name_empty'] = 'Please enter AD name!';
$_LANG['js_languages']['ad_link_empty'] = 'Please enter AD link URL!';
$_LANG['js_languages']['ad_text_empty'] = 'AD content can\'t be blank!';
$_LANG['js_languages']['ad_photo_empty'] = 'Advertising images can not be empty!';
$_LANG['js_languages']['ad_flash_empty'] = 'Flash ads can not be empty!';
$_LANG['js_languages']['ad_code_empty'] = 'Ad code can not be empty!';
$_LANG['js_languages']['empty_position_style'] = 'AD-position\'s template can\'t be blank!';
/* Prompting message */
$_LANG['upfile_flash_type'] = 'Upload Flash file type is invalid!';
$_LANG['ad_code_repeat'] = 'The AD image must be an uploaded file, or appoint a remote image.';
$_LANG['ad_flash_repeat'] = 'The AD Flash must be an uploaded file, or appoint a remote Flash.';
$_LANG['ad_name_exist'] = 'The AD name has existed!';
$_LANG['ad_name_notic'] = 'The AD name only discriminate other ADs, and conceal in the AD.';
$_LANG['ad_code_img'] = 'Upload the AD image file, or appoint a remote URL address.';
$_LANG['ad_code_flash'] = 'Upload the AD Flash file, or appoint a remote URL address.';
?> | {
"content_hash": "77219d0252597107fd3f3c02bbab9458",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 162,
"avg_line_length": 48.33576642335766,
"alnum_prop": 0.6197523406825732,
"repo_name": "lvguocai/ec",
"id": "43eb933df6bb4f55b1d0330c036c98d1460dd12d",
"size": "6624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "languages/en_us/admin/ads.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "144339"
},
{
"name": "ColdFusion",
"bytes": "14368"
},
{
"name": "HTML",
"bytes": "1276501"
},
{
"name": "JavaScript",
"bytes": "441569"
},
{
"name": "PHP",
"bytes": "5850512"
},
{
"name": "Perl",
"bytes": "4927"
}
],
"symlink_target": ""
} |
package eu.inn.binders.naming
class DashCaseParser extends IdentifierParser {
override def parse(identifier: String, builder: IdentifierBuilder): Unit = {
var prevIsDash = false
var dashConsumed = false
for (c <- identifier) {
if (prevIsDash) {
builder.divider()
builder.regular(c)
dashConsumed = true
prevIsDash = false
}
else {
if (c == '-') {
prevIsDash = true
dashConsumed = false
} else {
builder.regular(c)
prevIsDash = false
}
}
}
if (prevIsDash && !dashConsumed) {
builder.regular('-')
}
}
}
| {
"content_hash": "02eb313d763fac94857a2a4d385ec280",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 78,
"avg_line_length": 23.392857142857142,
"alnum_prop": 0.5511450381679389,
"repo_name": "InnovaCo/binders",
"id": "9959e8480f83de6f0bc2ada05fe5aa393caa9a37",
"size": "655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/eu/inn/binders/naming/DashCaseParser.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Scala",
"bytes": "123247"
},
{
"name": "Shell",
"bytes": "469"
}
],
"symlink_target": ""
} |
import webpack from 'webpack';
import path from 'path'; // Provided by Node
const projectRoot = path.join(__dirname, '..', '..');
const sourceRoot = path.join(projectRoot, 'src');
const scriptRoot = path.join(sourceRoot, 'scripts');
const hbsRoot = path.join(sourceRoot, 'handlebars');
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production')
};
export default {
debug: false,
devtool: 'source-map',
target: 'web',
entry: path.join(scriptRoot, "app"),
output: {
path: path.join(projectRoot, 'modules/DscStudio/engine/scripts'),
publicPath: '/scripts',
filename: 'bundle.js',
library: 'DscStudio',
libraryTarget: 'var'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin(GLOBALS),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
include: scriptRoot,
loaders: ['babel']
},
{
test: /\.hbs$/,
include: [hbsRoot],
loaders: ['raw-loader']
}
]
},
resolve: {
modulesDirectories: ['node_modules', 'src/scripts'],
fallback: path.join(__dirname, 'node_modules'),
alias: {
'handlebars': 'handlebars/dist/handlebars.min.js',
'office-ui-fabric-js': 'office-ui-fabric-js/dist/js/fabric.min.js'
}
},
resolveLoader: {
fallback: path.join(__dirname, 'node_modules'),
alias: {
'hbs': 'handlebars-loader'
}
}
};
| {
"content_hash": "35a6bf684ddd796f6ccfaf376d8f107a",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 78,
"avg_line_length": 28.779661016949152,
"alnum_prop": 0.5406360424028268,
"repo_name": "BrianFarnhill/DSCStudio",
"id": "3dfef8f661c0a6ade1ee182ec569b7c80d2fa99a",
"size": "1698",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "tools/build/webpack.config.dist.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16507"
},
{
"name": "HTML",
"bytes": "30605"
},
{
"name": "JavaScript",
"bytes": "289529"
},
{
"name": "PowerShell",
"bytes": "25303"
}
],
"symlink_target": ""
} |
package simulations
class Simulator {
type Action = () => Unit
protected type Agenda = List[WorkItem]
case class WorkItem(time: Int, action: Action)
protected[simulations] var agenda: Agenda = List()
protected var currentTime = 0
protected def afterDelay(delay: Int)(action: => Unit) {
val item = WorkItem(currentTime + delay, () => action)
def insert(ag: Agenda): Agenda =
if (ag.isEmpty || item.time < ag.head.time) item :: ag
else ag.head :: insert(ag.tail)
agenda = insert(agenda)
}
protected[simulations] def next {
agenda match {
case List() => {}
case WorkItem(time, action) :: rest =>
agenda = rest
currentTime = time
action()
}
}
def run {
println("*** New propagation ***")
while (!agenda.isEmpty) { next }
}
}
| {
"content_hash": "6d03080a884dc6213942064c326460cb",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 60,
"avg_line_length": 23.65714285714286,
"alnum_prop": 0.607487922705314,
"repo_name": "msulima/reactive",
"id": "c0c2e22b8dab4446c308dce60935951d31d0b4af",
"size": "828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "simulations/src/main/scala/simulations/Simulator.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "428356"
}
],
"symlink_target": ""
} |
/**
* \file string.hh
* \brief Various useful string functions.
*/
#ifndef CJ_UTILS_STRING_HH_
#define CJ_UTILS_STRING_HH_
#include <iostream>
#include <sstream>
#include <fstream>
#include <cctype>
#include "cj/common.hh"
namespace cj {
/**
* \brief Split a string given a deliminator, into a vector of strings.
*/
inline auto split(string const& s, char delim) -> vector<string> {
std::stringstream ss(s);
auto tks = vector<string>{};
auto item = string{};
while (std::getline(ss, item, delim)) {
tks.push_back(item);
}
return tks;
}
/**
* \brief Reads an entire file into a single string.
*/
inline auto read_file(char const* filename) -> std::optional<string> {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
auto contents = string{};
in.seekg(0, std::ios::end);
contents.resize((size_t)in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return contents;
}
return std::nullopt;
}
/**
* \brief Whether a string 's' starts with 'beginning'.
*/
inline auto begins_with(string const& s, string const& beginning) -> bool {
return s.compare(0, beginning.length(), beginning) == 0;
}
/**
* \brief Creates a lowercase copy of a string.
*/
inline auto to_lower_cpy(string const& s) -> string {
string cpy = s;
for (auto i = 0u; i < cpy.size(); ++i) {
cpy[i] = std::tolower(cpy[i]);
}
return cpy;
}
/**
* \brief Builds a string from a container, interspersing a string between all elements.
*
* \param first First element of the container.
* \param last Last element of the container.
* \param inter [Default = ", "] What to insert between the elements.
* \param before_each [Default = ""] What to add before each element.
* \param after_each [Default = ""] What to add after each element.
* \return A string with 'inter' interspersed between all elements of the container.
*/
template<typename Iterator>
inline auto intersperse(Iterator fst, Iterator lst, string const& inter = ", ",
string const& before_each = "", string const& after_each = "")
noexcept -> string {
if (fst == lst) {
return "";
}
auto oss = std::ostringstream{};
oss << before_each << *fst << after_each;
while (++fst != lst) {
oss << inter << before_each << *fst << after_each;
}
return oss.str();
}
/**
* \brief Builds a string from a container, interspersing a string between all elements and between
* pairs.
*
* \param fst First element of the container.
* \param lst Last element of the container.
* \param inter [Default = ", "] What to insert between the elements.
* \param pair_inter [Default = ", "] What to insert between the first and second element of the pairs.
* \param before_each [Default = "("] What to add before each element.
* \param after_each [Default = ")"] What to add after each element.
* \return A string with 'inter' interspersed between all elements of the container.
*/
template<typename Iterator>
inline auto intersperse_pairs(Iterator fst, Iterator lst, string const& inter = ", ",
string const& pair_inter = ", ", string const& before_each = "(",
string const& after_each = ")")
noexcept -> string {
if (fst == lst) {
return "";
}
auto oss = std::ostringstream{};
oss << before_each << fst->first << pair_inter << fst->second << after_each;
while (++fst != lst) {
oss << inter << before_each << fst->first << pair_inter << fst->second << after_each;
}
return oss.str();
}
/**
* \brief Builds a string from the keys of an associative container, interspersing a string between
* all elements.
*
* \param fst First element of the container.
* \param lst Last element of the container.
* \param inter [Default = ", "] What to insert between the elements.
* \param before_each [Default = "("] What to add before each element.
* \param after_each [Default = ")"] What to add after each element.
* \return A string with 'inter' interspersed between all elements of the container.
*/
template<typename Iterator>
inline auto intersperse_keys(Iterator fst, Iterator lst, string const& inter = ", ",
string const& before_each = "", string const& after_each = "")
noexcept -> string {
if (fst == lst) {
return "";
}
auto oss = std::ostringstream{};
oss << before_each << fst->first << after_each;
while (++fst != lst) {
oss << inter << before_each << fst->first << after_each;
}
return oss.str();
}
} /* end namespace cj */
#endif
| {
"content_hash": "27a21f05fa04a306be40ca0cf779e17d",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 107,
"avg_line_length": 33.26896551724138,
"alnum_prop": 0.6061359867330016,
"repo_name": "PhDP/Shedu",
"id": "3796b9e4b83f93e83c007fd5ade9798175309043",
"size": "4824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/cj/utils/string.hh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1359565"
},
{
"name": "CMake",
"bytes": "6351"
},
{
"name": "Shell",
"bytes": "779"
}
],
"symlink_target": ""
} |
//Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
using System.Collections;
using System.Collections.Generic;
using Fonet.Fo.Flow;
using Fonet.Fo.Pagination;
using Fonet.Fo.Properties;
namespace Fonet.Fo
{
internal class StandardElementMapping
{
public const string URI = "http://www.w3.org/1999/XSL/Format";
private static Hashtable foObjs;
static Dictionary<string, FObj.MakerBase> s_fObjMakers;
static StandardElementMapping()
{
foObjs = new Hashtable();
s_fObjMakers = new Dictionary<string, FObj.MakerBase>();
// Declarations and Pagination and Layout Formatting Objects
foObjs.Add("root", Root.GetMaker());
foObjs.Add("declarations", Declarations.GetMaker());
foObjs.Add("color-profile", ColorProfile.GetMaker());
foObjs.Add("page-sequence", PageSequence.GetMaker());
foObjs.Add("layout-master-set", LayoutMasterSet.GetMaker());
foObjs.Add("page-sequence-master", PageSequenceMaster.GetMaker());
foObjs.Add("single-page-master-reference", SinglePageMasterReference.GetMaker());
foObjs.Add("repeatable-page-master-reference", RepeatablePageMasterReference.GetMaker());
foObjs.Add("repeatable-page-master-alternatives", RepeatablePageMasterAlternatives.GetMaker());
foObjs.Add("conditional-page-master-reference", ConditionalPageMasterReference.GetMaker());
foObjs.Add("simple-page-master", SimplePageMaster.GetMaker());
foObjs.Add("region-body", RegionBody.GetMaker());
foObjs.Add("region-before", RegionBefore.GetMaker());
foObjs.Add("region-after", RegionAfter.GetMaker());
foObjs.Add("region-start", RegionStart.GetMaker());
foObjs.Add("region-end", RegionEnd.GetMaker());
foObjs.Add("flow", Flow.Flow.GetMaker());
foObjs.Add("static-content", StaticContent.GetMaker());
foObjs.Add("title", Title.GetMaker());
// Block-level Formatting Objects
foObjs.Add("block", Block.GetMaker());
foObjs.Add("block-container", BlockContainer.GetMaker());
// Inline-level Formatting Objects
foObjs.Add("bidi-override", BidiOverride.GetMaker());
foObjs.Add("character", Character.GetMaker());
foObjs.Add("initial-property-set", InitialPropertySet.GetMaker());
foObjs.Add("external-graphic", ExternalGraphic.GetMaker());
foObjs.Add("instream-foreign-object", InstreamForeignObject.GetMaker());
foObjs.Add("inline", Inline.GetMaker());
foObjs.Add("inline-container", InlineContainer.GetMaker());
foObjs.Add("leader", Leader.GetMaker());
foObjs.Add("page-number", PageNumber.GetMaker());
foObjs.Add("page-number-citation", PageNumberCitation.GetMaker());
// Formatting Objects for Tables
foObjs.Add("table-and-caption", TableAndCaption.GetMaker());
foObjs.Add("table", Table.GetMaker());
foObjs.Add("table-column", TableColumn.GetMaker());
foObjs.Add("table-caption", TableCaption.GetMaker());
foObjs.Add("table-header", TableHeader.GetMaker());
foObjs.Add("table-footer", TableFooter.GetMaker());
foObjs.Add("table-body", TableBody.GetMaker());
foObjs.Add("table-row", TableRow.GetMaker());
foObjs.Add("table-cell", TableCell.GetMaker());
// Formatting Objects for Lists
foObjs.Add("list-block", ListBlock.GetMaker());
foObjs.Add("list-item", ListItem.GetMaker());
foObjs.Add("list-item-body", ListItemBody.GetMaker());
foObjs.Add("list-item-label", ListItemLabel.GetMaker());
// Dynamic Effects: Link and Multi Formatting Objects
foObjs.Add("basic-link", BasicLink.GetMaker());
foObjs.Add("multi-switch", MultiSwitch.GetMaker());
foObjs.Add("multi-case", MultiCase.GetMaker());
foObjs.Add("multi-toggle", MultiToggle.GetMaker());
foObjs.Add("multi-properties", MultiProperties.GetMaker());
foObjs.Add("multi-property-set", MultiPropertySet.GetMaker());
// Out-of-Line Formatting Objects
foObjs.Add("float", Float.GetMaker());
foObjs.Add("footnote", Footnote.GetMaker());
foObjs.Add("footnote-body", FootnoteBody.GetMaker());
// Other Formatting Objects
foObjs.Add("wrapper", Wrapper.GetMaker());
foObjs.Add("marker", Marker.GetMaker());
foObjs.Add("retrieve-marker", RetrieveMarker.GetMaker());
}
public void AddToBuilder(FOTreeBuilder builder)
{
builder.AddElementMapping(URI, foObjs);
builder.AddPropertyMapping(URI, FOPropertyMapping.getGenericMappings());
}
}
} | {
"content_hash": "ea7d2b41b5b7a44b51e33d086ee25d8e",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 107,
"avg_line_length": 47.88461538461539,
"alnum_prop": 0.6273092369477912,
"repo_name": "PaintLab/SaveAsPdf",
"id": "269d24328f45a0fe7f1efc06ab616d86ad872742",
"size": "4982",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FoDom/Fo/StandardElementMapping.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1748780"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/iotsitewise/IoTSiteWiseRequest.h>
#include <aws/iotsitewise/model/EncryptionType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace IoTSiteWise
{
namespace Model
{
/**
*/
class AWS_IOTSITEWISE_API PutDefaultEncryptionConfigurationRequest : public IoTSiteWiseRequest
{
public:
PutDefaultEncryptionConfigurationRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "PutDefaultEncryptionConfiguration"; }
Aws::String SerializePayload() const override;
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline const EncryptionType& GetEncryptionType() const{ return m_encryptionType; }
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline bool EncryptionTypeHasBeenSet() const { return m_encryptionTypeHasBeenSet; }
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline void SetEncryptionType(const EncryptionType& value) { m_encryptionTypeHasBeenSet = true; m_encryptionType = value; }
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline void SetEncryptionType(EncryptionType&& value) { m_encryptionTypeHasBeenSet = true; m_encryptionType = std::move(value); }
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline PutDefaultEncryptionConfigurationRequest& WithEncryptionType(const EncryptionType& value) { SetEncryptionType(value); return *this;}
/**
* <p>The type of encryption used for the encryption configuration.</p>
*/
inline PutDefaultEncryptionConfigurationRequest& WithEncryptionType(EncryptionType&& value) { SetEncryptionType(std::move(value)); return *this;}
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; }
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline bool KmsKeyIdHasBeenSet() const { return m_kmsKeyIdHasBeenSet; }
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; }
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); }
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); }
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline PutDefaultEncryptionConfigurationRequest& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;}
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline PutDefaultEncryptionConfigurationRequest& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;}
/**
* <p>The Key ID of the customer managed customer master key (CMK) used for KMS
* encryption. This is required if you use <code>KMS_BASED_ENCRYPTION</code>.</p>
*/
inline PutDefaultEncryptionConfigurationRequest& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;}
private:
EncryptionType m_encryptionType;
bool m_encryptionTypeHasBeenSet;
Aws::String m_kmsKeyId;
bool m_kmsKeyIdHasBeenSet;
};
} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws
| {
"content_hash": "43fe85541748a487dff5c745486ef1a7",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 149,
"avg_line_length": 39.40650406504065,
"alnum_prop": 0.7016711367856406,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "dc2c2dce555a52787f9fd093bf4347cce9ee889f",
"size": "4966",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-iotsitewise/include/aws/iotsitewise/model/PutDefaultEncryptionConfigurationRequest.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"image/color"
"runtime"
"strings"
"sync"
"time"
"gopkg.in/fsnotify.v0"
"gopkg.in/qml.v1"
"github.com/limetext/lime/backend"
"github.com/limetext/lime/backend/keys"
"github.com/limetext/lime/backend/log"
"github.com/limetext/lime/backend/render"
_ "github.com/limetext/lime/backend/sublime"
"github.com/limetext/lime/backend/textmate"
"github.com/limetext/lime/backend/util"
. "github.com/limetext/text"
)
var limeViewComponent qml.Object
const (
batching_enabled = true
qmlMainFile = "main.qml"
qmlViewFile = "LimeView.qml"
// http://qt-project.org/doc/qt-5.1/qtcore/qt.html#KeyboardModifier-enum
shift_mod = 0x02000000
ctrl_mod = 0x04000000
alt_mod = 0x08000000
meta_mod = 0x10000000
keypad_mod = 0x20000000
)
// keeping track of frontend state
type qmlfrontend struct {
status_message string
lock sync.Mutex
windows map[*backend.Window]*frontendWindow
Console *frontendView
qmlDispatch chan qmlDispatch
}
// Used for batching qml.Changed calls
type qmlDispatch struct{ value, field interface{} }
func (t *qmlfrontend) Window(w *backend.Window) *frontendWindow {
return t.windows[w]
}
func (t *qmlfrontend) Show(v *backend.View, r Region) {
// TODO
}
func (t *qmlfrontend) VisibleRegion(v *backend.View) Region {
// TODO
return Region{0, v.Buffer().Size()}
}
func (t *qmlfrontend) StatusMessage(msg string) {
t.lock.Lock()
defer t.lock.Unlock()
t.status_message = msg
}
func (t *qmlfrontend) ErrorMessage(msg string) {
log.Error(msg)
var q qmlDialog
q.Show(msg, "StandardIcon.Critical")
}
func (t *qmlfrontend) MessageDialog(msg string) {
var q qmlDialog
q.Show(msg, "StandardIcon.Information")
}
func (t *qmlfrontend) OkCancelDialog(msg, ok string) bool {
var q qmlDialog
return q.Show(msg, "StandardIcon.Question") == 1
}
func (t *qmlfrontend) scroll(b Buffer) {
t.Show(backend.GetEditor().Console(), Region{b.Size(), b.Size()})
}
func (t *qmlfrontend) Erased(changed_buffer Buffer, region_removed Region, data_removed []rune) {
t.scroll(changed_buffer)
}
func (t *qmlfrontend) Inserted(changed_buffer Buffer, region_inserted Region, data_inserted []rune) {
t.scroll(changed_buffer)
}
// Apparently calling qml.Changed also triggers a re-draw, meaning that typed text is at the
// mercy of how quick Qt happens to be rendering.
// Try setting batching_enabled = false to see the effects of non-batching
func (t *qmlfrontend) qmlBatchLoop() {
queue := make(map[qmlDispatch]bool)
t.qmlDispatch = make(chan qmlDispatch, 1000)
for {
if len(queue) > 0 {
select {
case <-time.After(time.Millisecond * 20):
// Nothing happened for 20 milliseconds, so dispatch all queued changes
for k := range queue {
qml.Changed(k.value, k.field)
}
queue = make(map[qmlDispatch]bool)
case d := <-t.qmlDispatch:
queue[d] = true
}
} else {
queue[<-t.qmlDispatch] = true
}
}
}
func (t *qmlfrontend) qmlChanged(value, field interface{}) {
if !batching_enabled {
qml.Changed(value, field)
} else {
t.qmlDispatch <- qmlDispatch{value, field}
}
}
func (t *qmlfrontend) DefaultBg() color.RGBA {
c := scheme.Spice(&render.ViewRegions{})
c.Background.A = 0xff
return color.RGBA(c.Background)
}
func (t *qmlfrontend) DefaultFg() color.RGBA {
c := scheme.Spice(&render.ViewRegions{})
c.Foreground.A = 0xff
return color.RGBA(c.Foreground)
}
// Called when a new view is opened
func (t *qmlfrontend) onNew(v *backend.View) {
fv := &frontendView{bv: v}
v.Buffer().AddObserver(fv)
v.Settings().AddOnChange("blah", fv.onChange)
fv.Title.Text = v.Buffer().FileName()
if len(fv.Title.Text) == 0 {
fv.Title.Text = "untitled"
}
w2 := t.windows[v.Window()]
w2.views = append(w2.views, fv)
tabs := w2.window.ObjectByName("tabs")
tab := tabs.Call("addTab", "", limeViewComponent).(qml.Object)
try_now := func() {
item := tab.Property("item").(qml.Object)
if item.Addr() == 0 {
// Happens as the item isn't actually loaded until we switch to the tab.
// Hence connecting to the loaded signal
return
}
item.Set("myView", fv)
item.Set("fontSize", v.Settings().Get("font_size", 12).(float64))
item.Set("fontFace", v.Settings().Get("font_face", "Helvetica").(string))
}
tab.On("loaded", try_now)
try_now()
tabs.Set("currentIndex", tabs.Property("count").(int)-1)
}
// called when a view is closed
func (t *qmlfrontend) onClose(v *backend.View) {
w2 := t.windows[v.Window()]
for i := range w2.views {
if w2.views[i].bv == v {
w2.window.ObjectByName("tabs").Call("removeTab", i)
copy(w2.views[i:], w2.views[i+1:])
w2.views = w2.views[:len(w2.views)-1]
return
}
}
log.Error("Couldn't find closed view...")
}
// called when a view has loaded
func (t *qmlfrontend) onLoad(v *backend.View) {
w2 := t.windows[v.Window()]
i := 0
for i = range w2.views {
if w2.views[i].bv == v {
break
}
}
v2 := w2.views[i]
v2.Title.Text = v.Buffer().FileName()
tabs := w2.window.ObjectByName("tabs")
tabs.Set("currentIndex", w2.ActiveViewIndex())
tab := tabs.Call("getTab", i).(qml.Object)
tab.Set("title", v2.Title.Text)
}
func (t *qmlfrontend) onSelectionModified(v *backend.View) {
w2 := t.windows[v.Window()]
i := 0
for i = range w2.views {
if w2.views[i].bv == v {
break
}
}
v2 := w2.views[i]
v2.qv.Call("onSelectionModified")
}
// Launches the provided command in a new goroutine
// (to avoid locking up the GUI)
func (t *qmlfrontend) RunCommand(command string) {
t.RunCommandWithArgs(command, make(backend.Args))
}
func (t *qmlfrontend) RunCommandWithArgs(command string, args backend.Args) {
ed := backend.GetEditor()
go ed.RunCommand(command, args)
}
func (t *qmlfrontend) HandleInput(text string, keycode int, modifiers int) bool {
log.Debug("qmlfrontend.HandleInput: text=%v, key=%x, modifiers=%x", text, keycode, modifiers)
shift := false
alt := false
ctrl := false
super := false
if key, ok := lut[keycode]; ok {
ed := backend.GetEditor()
if (modifiers & shift_mod) != 0 {
shift = true
}
if (modifiers & alt_mod) != 0 {
alt = true
}
if (modifiers & ctrl_mod) != 0 {
if runtime.GOOS == "darwin" {
super = true
} else {
ctrl = true
}
}
if (modifiers & meta_mod) != 0 {
if runtime.GOOS == "darwin" {
ctrl = true
} else {
super = true
}
}
ed.HandleInput(keys.KeyPress{Text: text, Key: key, Shift: shift, Alt: alt, Ctrl: ctrl, Super: super})
return true
}
return false
}
// Quit closes all open windows to de-reference all qml objects
func (t *qmlfrontend) Quit() (err error) {
// todo: handle changed files that aren't saved.
for _, v := range t.windows {
if v.window != nil {
v.window.Hide()
v.window.Destroy()
v.window = nil
}
}
return
}
func (t *qmlfrontend) loop() (err error) {
backend.OnNew.Add(t.onNew)
backend.OnClose.Add(t.onClose)
backend.OnLoad.Add(t.onLoad)
backend.OnSelectionModified.Add(t.onSelectionModified)
ed := backend.GetEditor()
ed.SetFrontend(t)
ed.LogInput(false)
ed.LogCommands(false)
c := ed.Console()
t.Console = &frontendView{bv: c}
c.Buffer().AddObserver(t.Console)
c.Buffer().AddObserver(t)
go ed.Init()
var (
engine *qml.Engine
component qml.Object
// WaitGroup keeping track of open windows
wg sync.WaitGroup
)
// create and setup a new engine, destroying
// the old one if one exists.
//
// This is needed to re-load qml files to get
// the new file contents from disc as otherwise
// the old file would still be what is referenced.
newEngine := func() (err error) {
if engine != nil {
log.Debug("calling destroy")
// TODO(.): calling this appears to make the editor *very* crash-prone, just let it leak for now
// engine.Destroy()
engine = nil
}
log.Debug("calling newEngine")
engine = qml.NewEngine()
engine.On("quit", t.Quit)
log.Debug("setvar frontend")
engine.Context().SetVar("frontend", t)
log.Debug("setvar editor")
engine.Context().SetVar("editor", backend.GetEditor())
log.Debug("loadfile")
component, err = engine.LoadFile(qmlMainFile)
if err != nil {
return err
}
limeViewComponent, err = engine.LoadFile(qmlViewFile)
return
}
if err := newEngine(); err != nil {
log.Error(err)
}
backend.OnNewWindow.Add(func(w *backend.Window) {
fw := &frontendWindow{bw: w}
t.windows[w] = fw
if component != nil {
fw.launch(&wg, component)
}
})
// TODO: should be done backend side
if sc, err := textmate.LoadTheme("../../packages/themes/TextMate-Themes/Monokai.tmTheme"); err != nil {
log.Error(err)
} else {
scheme = sc
}
defer func() {
fmt.Println(util.Prof)
}()
w := ed.NewWindow()
v := w.OpenFile("main.go", 0)
// TODO: should be done backend side
v.SetSyntaxFile("../../packages/go.tmbundle/Syntaxes/Go.tmLanguage")
v = w.OpenFile("../../backend/editor.go", 0)
// TODO: should be done backend side
v.SetSyntaxFile("../../packages/go.tmbundle/Syntaxes/Go.tmLanguage")
watch, err := fsnotify.NewWatcher()
if err != nil {
log.Errorf("Unable to create file watcher: %s", err)
return
}
defer watch.Close()
watch.Watch(".")
defer watch.RemoveWatch(".")
reloadRequested := false
go func() {
for {
select {
case ev := <-watch.Event:
if ev != nil && strings.HasSuffix(ev.Name, ".qml") && ev.IsModify() && !ev.IsAttrib() {
reloadRequested = true
t.Quit()
}
}
}
}()
for {
// Reset reload status
reloadRequested = false
log.Debug("Waiting for all windows to close")
// wg would be the WaitGroup all windows belong to, so first we wait for
// all windows to close.
wg.Wait()
log.Debug("All windows closed. reloadRequest: %v", reloadRequested)
// then we check if there's a reload request in the pipe
if !reloadRequested || len(t.windows) == 0 {
// This would be a genuine exit; all windows closed by the user
break
}
// *We* closed all windows because we want to reload freshly changed qml
// files.
for {
log.Debug("Calling newEngine")
if err := newEngine(); err != nil {
// Reset reload status
reloadRequested = false
log.Error(err)
for !reloadRequested {
// This loop allows us to re-try reloading
// if there was an error in the file this time,
// we just loop around again when we receive the next
// reload request (ie on the next save of the file).
time.Sleep(time.Second)
}
continue
}
log.Debug("break")
break
}
log.Debug("re-launching all windows")
// Succeeded loading the file, re-launch all windows
for _, v := range t.windows {
v.launch(&wg, component)
}
}
return
}
| {
"content_hash": "9388971393deb3a588649a1043a623b7",
"timestamp": "",
"source": "github",
"line_count": 426,
"max_line_length": 104,
"avg_line_length": 24.934272300469484,
"alnum_prop": 0.6657879871963849,
"repo_name": "farhaanbukhsh/lime",
"id": "52ab380f678fd13f3b0fa89e0841f74f2b4a70ec",
"size": "10772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/qml/qml_frontend.go",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Go",
"bytes": "597411"
},
{
"name": "HTML",
"bytes": "8947"
},
{
"name": "JavaScript",
"bytes": "51088"
},
{
"name": "Python",
"bytes": "127345"
},
{
"name": "QML",
"bytes": "29231"
},
{
"name": "QMake",
"bytes": "71"
},
{
"name": "Shell",
"bytes": "4956"
},
{
"name": "VimL",
"bytes": "26798"
}
],
"symlink_target": ""
} |
import os
# configuration
DEBUG = True
SECRET_KEY='\xb1\x85s\xe7\xa9\xcc\xe9C\xabq+\xcb/Nf\xea\x18C>\xfe:\xf8QY',
USERNAME = 'admin'
PASSWORD = 'admin'
DATABASE_URI = 'sqlite:///' + os.getenv('DATABASE_PATH', None) + 'rottoscraper.db'
# Redis configuration
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
# You can also specify the Redis DB to use
REDIS_DB = 0
# REDIS_PASSWORD = 'very secret'
# Queues to listen on
QUEUES_LISTEN = ['high', 'normal', 'low']
# Mail Details
FROM = 'Rotto Links Scaper<noreply@rottoscraper.com>'
# SMTP Cerendentials
SMTP_USER = os.getenv('SMTP_USER', None)
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', None)
# Logs DIR Path
LOGS_DIR = os.getenv('LOGS_DIR', 'logs/')
| {
"content_hash": "00a2c791b4e9c2c838227dabc55c092a",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 82,
"avg_line_length": 23.3,
"alnum_prop": 0.698140200286123,
"repo_name": "KodeKracker/Rotto-Links-Scraper",
"id": "ffa9c9cf8d8b778303fde5276c15b2ba90db2a94",
"size": "747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rottoscraper/config.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8415"
},
{
"name": "JavaScript",
"bytes": "3120"
},
{
"name": "Python",
"bytes": "45361"
}
],
"symlink_target": ""
} |
package org.apache.spark.mllib.optimization.tfocs.fs.dvectordouble.double
import org.apache.spark.mllib.optimization.tfocs.{ Mode, SmoothFunction, Value }
import org.apache.spark.mllib.optimization.tfocs.VectorSpace._
/**
* A smooth function operating on (DVector, Double) pairs. Such pairs arise when two separate
* linear operators are applied to an input value. The value returned by SmoothCombine is equal to
* the value of the objective function evaluated on the first (DVector) element of the pair summed
* with the second (Double) element of the pair.
*
* NOTE In matlab tfocs this functionality is implemented in smooth_stack.m and smooth_linear.m.
* @see [[https://github.com/cvxr/TFOCS/blob/master/private/smooth_stack.m]]
* @see [[https://github.com/cvxr/TFOCS/blob/master/smooth_linear.m]]
*/
class SmoothCombine(objectiveF: SmoothFunction[DVector]) extends SmoothFunction[(DVector, Double)] {
override def apply(x: (DVector, Double), mode: Mode): Value[(DVector, Double)] = {
val (xVector, xAncillaryScalar) = x
val Value(f, g) = objectiveF(xVector, mode)
Value(f.map(_ + xAncillaryScalar), g.map((_, 1.0)))
}
}
| {
"content_hash": "bf1bc185b71b3ee7c4b3004540ada7a2",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 100,
"avg_line_length": 46.2,
"alnum_prop": 0.7411255411255411,
"repo_name": "databricks/spark-tfocs",
"id": "48cadbd41e95819aff0e6b88bc29c5fd0542de1f",
"size": "1955",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/org/apache/spark/mllib/optimization/tfocs/fs/dvectordouble/double/SmoothCombine.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "135713"
}
],
"symlink_target": ""
} |
//
// WFFitMessageActivity.h (previously WFFitActivityRecord.h)
// WFConnector
//
// Created by Michael Moore on 6/16/10.
// Copyright 2010 Wahoo Fitness. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <WFConnector/WFFitMessageBase.h>
#import <WFConnector/fit_sdk.h>
/**
* Represents a single activity record from a fitness device FIT file.
*/
@interface WFFitMessageActivity : WFFitMessageBase
{
/** \cond InterfaceDocs */
FIT_ACTIVITY_MESG stActivity;
NSDate* localTimestamp;
/** \endcond */
}
/**
* Gets a pointer to the <c>FIT_ACTIVITY_MESG</c> structure containing the data
* for this record.
*/
@property (nonatomic, readonly) FIT_ACTIVITY_MESG* pstActivity;
/**
* Gets the localized timestamp for the record.
*
* @note This property is device specific, and may not contain a valid time.
*/
@property (nonatomic, readonly) NSDate* localTimestamp;
/**
* Returns the localized timestamp as a string formatted in short date time
* (MM/DD/YY 12:00 AM).
*
* @note This method is device specific, and may not return a valid time.
*
* @return The formatted date string (MM/DD/YY 12:00 AM).
*/
- (NSString*)stringFromLocalTimestamp;
@end
| {
"content_hash": "b8ed24dba8a864de09a32d844075637b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 79,
"avg_line_length": 22.903846153846153,
"alnum_prop": 0.7170445004198153,
"repo_name": "simonmaddox/Hearty",
"id": "ebc8e7d1d42fc99f11dc51412477e4f5d82e587f",
"size": "1191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WFConnector.framework/Versions/A/Headers/WFFitMessageActivity.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "93141"
},
{
"name": "C++",
"bytes": "143678"
},
{
"name": "Objective-C",
"bytes": "312037"
},
{
"name": "Ruby",
"bytes": "74"
}
],
"symlink_target": ""
} |
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeInsertBGM(t *testing.T) {
convey.Convey("InsertBGM", t, func(ctx convey.C) {
var (
c = context.Background()
values = "(1,2,3,4,'2018-06-24','test')"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.InsertBGM(c, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetBGM(t *testing.T) {
convey.Convey("GetBGM", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
limit = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
bs, last, err := d.GetBGM(c, id, limit)
ctx.Convey("Then err should be nil.bs,last should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(last, convey.ShouldNotBeNil)
ctx.So(bs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeDelBGM(t *testing.T) {
convey.Convey("DelBGM", t, func(ctx convey.C) {
var (
c = context.Background()
limit = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.DelBGM(c, limit)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
| {
"content_hash": "ce348936e11aee5f3afbb52748067341",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 87,
"avg_line_length": 25.82758620689655,
"alnum_prop": 0.6428571428571429,
"repo_name": "LQJJ/demo",
"id": "02b1f15b0fe998b517726216379e97dd1322a743",
"size": "1498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "126-go-common-master/app/job/main/growup/dao/income/bgm_test.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5910716"
},
{
"name": "C++",
"bytes": "113072"
},
{
"name": "CSS",
"bytes": "10791"
},
{
"name": "Dockerfile",
"bytes": "934"
},
{
"name": "Go",
"bytes": "40121403"
},
{
"name": "Groovy",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "359263"
},
{
"name": "JavaScript",
"bytes": "545384"
},
{
"name": "Makefile",
"bytes": "6671"
},
{
"name": "Mathematica",
"bytes": "14565"
},
{
"name": "Objective-C",
"bytes": "14900720"
},
{
"name": "Objective-C++",
"bytes": "20070"
},
{
"name": "PureBasic",
"bytes": "4152"
},
{
"name": "Python",
"bytes": "4490569"
},
{
"name": "Ruby",
"bytes": "44850"
},
{
"name": "Shell",
"bytes": "33251"
},
{
"name": "Swift",
"bytes": "463286"
},
{
"name": "TSQL",
"bytes": "108861"
}
],
"symlink_target": ""
} |
function [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params)
% Multi-taper coherency,cross-spectral matrix - continuous process
%
% Usage:
%
% [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params)
% Input:
% Note units have to be consistent. See chronux.m for more information.
% data (in form samples x channels) -- required
% params: structure with fields tapers, pad, Fs, fpass, err
% - optional
% tapers : precalculated tapers from dpss or in the one of the following
% forms:
% (1) A numeric vector [TW K] where TW is the
% time-bandwidth product and K is the number of
% tapers to be used (less than or equal to
% 2TW-1).
% (2) A numeric vector [W T p] where W is the
% bandwidth, T is the duration of the data and p
% is an integer such that 2TW-p tapers are used. In
% this form there is no default i.e. to specify
% the bandwidth, you have to specify T and p as
% well. Note that the units of W and T have to be
% consistent: if W is in Hz, T must be in seconds
% and vice versa. Note that these units must also
% be consistent with the units of params.Fs: W can
% be in Hz if and only if params.Fs is in Hz.
% The default is to use form 1 with TW=3 and K=5
%
% pad (padding factor for the FFT) - optional (can take values -1,0,1,2...).
% -1 corresponds to no padding, 0 corresponds to padding
% to the next highest power of 2 etc.
% e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT
% to 512 points, if pad=1, we pad to 1024 points etc.
% Defaults to 0.
% Fs (sampling frequency) - optional. Default 1.
% fpass (frequency band to be used in the calculation in the form
% [fmin fmax])- optional.
% Default all frequencies between 0 and Fs/2
% err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars
% [0 p] or 0 - no error bars) - optional. Default 0.
% Output:
% C (magnitude of coherency frequency x channels x channels)
% phi (phase of coherency frequency x channels x channels)
% S12 (cross-spectral matrix frequency x channels x channels)
% f (frequencies)
% confC (confidence level for C at 1-p %) - only for err(1)>=1
% phistd - theoretical/jackknife (depending on err(1)=1/err(1)=2) standard deviation for phi
% Note that phi + 2 phistd and phi - 2 phistd will give 95% confidence
% bands for phi - only for err(1)>=1
% Cerr (Jackknife error bars for C - use only for Jackknife - err(1)=2)
if nargin < 1; error('need data'); end;
if nargin < 2; params=[]; end;
[N,Ch]=size(data);
if Ch==1; error('Need at least two channels of data'); end;
[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);
clear trialave params
if nargout > 6 && err(1)~=2;
error('Cerr computed only for Jackknife. Correct inputs and run again');
end;
if nargout >= 4 && err(1)==0;
% Errors computed only if err(1) is nonzero. Need to change params and run again.
error('When errors are desired, err(1) has to be non-zero.');
end;
nfft=max(2^(nextpow2(N)+pad),N);
[f,findx]=getfgrid(Fs,nfft,fpass);
tapers=dpsschk(tapers,N,Fs); % check tapers
J=mtfftc(data,tapers,nfft,Fs);
J=J(findx,:,:);
if err(1)==0;
[C,phi,S12]=cohmathelper(J,err);
elseif err(1)==1;
[C,phi,S12,confC,phistd]=cohmathelper(J,err);
elseif err(1)==2;
[C,phi,S12,confC,phistd,Cerr]=cohmathelper(J,err);
end
| {
"content_hash": "6915cb5e07afda835d0e45fbb078c60d",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 98,
"avg_line_length": 51.142857142857146,
"alnum_prop": 0.5792280345352971,
"repo_name": "arengela/AngelaUCSFCodeAll",
"id": "85ddbeca65308a0d756866c73fad38df82b347e3",
"size": "3938",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "CoreFunctions/chronux/spectral_analysis/continuous/cohmatrixc.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "853854"
},
{
"name": "C++",
"bytes": "649247"
},
{
"name": "CSS",
"bytes": "13181"
},
{
"name": "DOT",
"bytes": "20249"
},
{
"name": "Java",
"bytes": "98514"
},
{
"name": "M",
"bytes": "451367"
},
{
"name": "Matlab",
"bytes": "5445061"
},
{
"name": "Objective-C",
"bytes": "16676"
},
{
"name": "Python",
"bytes": "127452"
},
{
"name": "Shell",
"bytes": "5067"
},
{
"name": "XSLT",
"bytes": "9753"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace JsonLD.Entities.Converters
{
/// <summary>
/// Converter for JSON-LD @sets
/// </summary>
/// <typeparam name="T">collection element type</typeparam>
public class JsonLdArrayConverter<T> : JsonLdCollectionConverter<T>
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
public override bool CanConvert(Type objectType)
{
return typeof(T[]).IsAssignableFrom(objectType);
}
/// <summary>
/// Creates an array of <typeparamref name="T"/>
/// </summary>
protected override object CreateReturnedContainer(IEnumerable<T> elements)
{
return elements.ToArray();
}
}
}
| {
"content_hash": "8b0f41aed2063fd242929bd7c79dddf7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 83,
"avg_line_length": 28.933333333333334,
"alnum_prop": 0.618663594470046,
"repo_name": "wikibus/JsonLD.Entities",
"id": "308d8a310f53d6ae258891a98c67646137e454a8",
"size": "870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/JsonLD.Entities/Converters/JsonLdArrayConverter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "104299"
},
{
"name": "Gherkin",
"bytes": "12532"
},
{
"name": "PowerShell",
"bytes": "5141"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Compute.Models;
using Azure.Management.Resources;
using Azure.Management.Resources.Models;
using NUnit.Framework;
namespace Azure.ResourceManager.Compute.Tests.DiskRPTests
{
public class DiskRPTestsBase : VMTestBase
{
public DiskRPTestsBase(bool isAsync)
: base(isAsync)
{
}
[SetUp]
public void ClearChallengeCacheforRecord()
{
if (Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback)
{
InitializeBase();
}
}
[TearDown]
public async Task CleanupResourceGroup()
{
await CleanupResourceGroupsAsync();
}
protected const string DiskNamePrefix = "diskrp";
private string DiskRPLocation = "southeastasia";
#region Execution
protected async Task Disk_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, IList<string> zones = null)
{
EnsureClientsInitialized(DefaultLocation);
DiskRPLocation = location ?? DiskRPLocation;
// Data
var rgName = Recording.GenerateAssetName(TestPrefix);
var diskName = Recording.GenerateAssetName(DiskNamePrefix);
Disk disk = await GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB, zones, location);
// **********
// SETUP
// **********
// Create resource group, unless create option is import in which case resource group will be created with vm,
// or copy in which casethe resource group will be created with the original disk.
if (diskCreateOption != DiskCreateOption.Import && diskCreateOption != DiskCreateOption.Copy)
{
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(DiskRPLocation));
}
// **********
// TEST
// **********
// Put
Disk diskOut = await WaitForCompletionAsync((await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, disk)));
Validate(disk, diskOut, DiskRPLocation);
// Get
diskOut = await DisksOperations.GetAsync(rgName, diskName);
Validate(disk, diskOut, DiskRPLocation);
//string resourceGroupName, string diskName, AccessLevel access, int durationInSeconds, CancellationToken cancellationToken = default
// Get disk access
AccessUri accessUri = await WaitForCompletionAsync(await DisksOperations.StartGrantAccessAsync(rgName, diskName, new GrantAccessData(AccessDataDefault.Access, AccessDataDefault.DurationInSeconds)));
Assert.NotNull(accessUri.AccessSAS);
// Get
diskOut = await DisksOperations.GetAsync(rgName, diskName);
Validate(disk, diskOut, DiskRPLocation);
// Patch
// TODO: Bug 9865640 - DiskRP doesn't follow patch semantics for zones: skip this for zones
if (zones == null)
{
const string tagKey = "tageKey";
var updatedisk = new DiskUpdate();
updatedisk.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } };
diskOut = await WaitForCompletionAsync(await DisksOperations.StartUpdateAsync(rgName, diskName, updatedisk));
Validate(disk, diskOut, DiskRPLocation);
}
// Get
diskOut = await DisksOperations.GetAsync(rgName, diskName);
Validate(disk, diskOut, DiskRPLocation);
// End disk access
await WaitForCompletionAsync(await DisksOperations.StartRevokeAccessAsync(rgName, diskName));
// Delete
await WaitForCompletionAsync(await DisksOperations.StartDeleteAsync(rgName, diskName));
try
{
// Ensure it was really deleted
await DisksOperations.GetAsync(rgName, diskName);
Assert.False(true);
}
catch (Exception ex)
{
Assert.NotNull(ex);
//Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
}
}
protected async Task Snapshot_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, bool incremental = false)
{
EnsureClientsInitialized(DefaultLocation);
DiskRPLocation = location ?? DiskRPLocation;
// Data
var rgName = Recording.GenerateAssetName(TestPrefix);
var diskName = Recording.GenerateAssetName(DiskNamePrefix);
var snapshotName = Recording.GenerateAssetName(DiskNamePrefix);
Disk sourceDisk = await GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB);
// **********
// SETUP
// **********
// Create resource group
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(DiskRPLocation));
// Put disk
Disk diskOut = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, sourceDisk));
Validate(sourceDisk, diskOut, DiskRPLocation);
// Generate snapshot using disk info
Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id, incremental: incremental);
// **********
// TEST
// **********
// Put
Snapshot snapshotOut = await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName, snapshotName, snapshot));
Validate(snapshot, snapshotOut, incremental: incremental);
// Get
snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
Validate(snapshot, snapshotOut, incremental: incremental);
// Get access
AccessUri accessUri = await WaitForCompletionAsync((await SnapshotsOperations.StartGrantAccessAsync(rgName, snapshotName, new GrantAccessData(AccessDataDefault.Access, AccessDataDefault.DurationInSeconds))));
Assert.NotNull(accessUri.AccessSAS);
// Get
snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
Validate(snapshot, snapshotOut, incremental: incremental);
// Patch
var updatesnapshot = new SnapshotUpdate();
const string tagKey = "tageKey";
updatesnapshot.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } };
snapshotOut = await WaitForCompletionAsync(await SnapshotsOperations.StartUpdateAsync(rgName, snapshotName, updatesnapshot));
Validate(snapshot, snapshotOut, incremental: incremental);
// Get
snapshotOut = (await SnapshotsOperations.GetAsync(rgName, snapshotName)).Value;
Validate(snapshot, snapshotOut, incremental: incremental);
// End access
await WaitForCompletionAsync(await SnapshotsOperations.StartRevokeAccessAsync(rgName, snapshotName));
// Delete
await WaitForCompletionAsync(await SnapshotsOperations.StartDeleteAsync(rgName, snapshotName));
try
{
// Ensure it was really deleted
await SnapshotsOperations.GetAsync(rgName, snapshotName);
Assert.False(true);
}
catch (Exception ex)
{
Assert.NotNull(ex);
//Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
}
}
protected async Task DiskEncryptionSet_CRUD_Execute(string methodName, string location = null)
{
EnsureClientsInitialized(DefaultLocation);
DiskRPLocation = location ?? DiskRPLocation;
// Data
var rgName = Recording.GenerateAssetName(TestPrefix);
var desName = Recording.GenerateAssetName(DiskNamePrefix);
DiskEncryptionSet des = GenerateDefaultDiskEncryptionSet(DiskRPLocation);
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(DiskRPLocation));
// Put DiskEncryptionSet
DiskEncryptionSet desOut = await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartCreateOrUpdateAsync(rgName, desName, des));
Validate(des, desOut, desName);
// Get DiskEncryptionSet
desOut = await DiskEncryptionSetsOperations.GetAsync(rgName, desName);
Validate(des, desOut, desName);
// Patch DiskEncryptionSet
const string tagKey = "tageKey";
var updateDes = new DiskEncryptionSetUpdate();
updateDes.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } };
desOut = await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartUpdateAsync(rgName, desName, updateDes));
Validate(des, desOut, desName);
Assert.AreEqual(1, desOut.Tags.Count);
// Delete DiskEncryptionSet
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartDeleteAsync(rgName, desName));
try
{
// Ensure it was really deleted
await DiskEncryptionSetsOperations.GetAsync(rgName, desName);
Assert.False(true);
}
catch (Exception ex)
{
Assert.NotNull(ex);
//Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
}
}
protected async Task Disk_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null)
{
EnsureClientsInitialized(DefaultLocation);
DiskRPLocation = location ?? DiskRPLocation;
// Data
var rgName1 = Recording.GenerateAssetName(TestPrefix);
var rgName2 = Recording.GenerateAssetName(TestPrefix);
var diskName1 = Recording.GenerateAssetName(DiskNamePrefix);
var diskName2 = Recording.GenerateAssetName(DiskNamePrefix);
Disk disk1 = await GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB, location: location);
Disk disk2 = await GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB, location: location);
// **********
// SETUP
// **********
// Create resource groups, unless create option is import in which case resource group will be created with vm
if (diskCreateOption != DiskCreateOption.Import)
{
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName1, new ResourceGroup(DiskRPLocation));
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName2, new ResourceGroup(DiskRPLocation));
}
// Put 4 disks, 2 in each resource group
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName1, disk1));
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName2, disk2));
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName1, disk1));
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName2, disk2));
// **********
// TEST
// **********
// List disks under resource group
var disksOut = await DisksOperations.ListByResourceGroupAsync(rgName1).ToEnumerableAsync();
//Page<Disk> disksOut = (await DisksClient.ListByResourceGroupAsync(rgName1)).ToEnumerableAsync;
Assert.AreEqual(2, disksOut.Count());
//Assert.Null(disksOut.NextPageLink);
disksOut = await DisksOperations.ListByResourceGroupAsync(rgName2).ToEnumerableAsync();
Assert.AreEqual(2, disksOut.Count());
//Assert.Null(disksOut.NextPageLink);
// List disks under subscription
disksOut = await DisksOperations.ListAsync().ToEnumerableAsync();
Assert.True(disksOut.Count() >= 4);
//if (disksOut.NextPageLink != null)
//{
// disksOut = await DisksClient.ListNext(disksOut.NextPageLink);
// Assert.True(disksOut.Any());
//}
}
protected async Task Snapshot_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null)
{
EnsureClientsInitialized(DefaultLocation);
// Data
var rgName1 = Recording.GenerateAssetName(TestPrefix);
var rgName2 = Recording.GenerateAssetName(TestPrefix);
var diskName1 = Recording.GenerateAssetName(DiskNamePrefix);
var diskName2 = Recording.GenerateAssetName(DiskNamePrefix);
var snapshotName1 = Recording.GenerateAssetName(DiskNamePrefix);
var snapshotName2 = Recording.GenerateAssetName(DiskNamePrefix);
Disk disk1 = await GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB);
Disk disk2 = await GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB);
// **********
// SETUP
// **********
// Create resource groups
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName1, new ResourceGroup(DiskRPLocation));
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName2, new ResourceGroup(DiskRPLocation));
// Put 4 disks, 2 in each resource group
Disk diskOut11 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName1, disk1));
Disk diskOut12 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName1, diskName2, disk2));
Disk diskOut21 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName1, disk1));
Disk diskOut22 = await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName2, diskName2, disk2));
// Generate 4 snapshots using disks info
Snapshot snapshot11 = GenerateDefaultSnapshot(diskOut11.Id);
Snapshot snapshot12 = GenerateDefaultSnapshot(diskOut12.Id, SnapshotStorageAccountTypes.StandardZRS.ToString());
Snapshot snapshot21 = GenerateDefaultSnapshot(diskOut21.Id);
Snapshot snapshot22 = GenerateDefaultSnapshot(diskOut22.Id);
// Put 4 snapshots, 2 in each resource group
await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName1, snapshotName1, snapshot11));
await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName1, snapshotName2, snapshot12));
await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName2, snapshotName1, snapshot21));
await WaitForCompletionAsync(await SnapshotsOperations.StartCreateOrUpdateAsync(rgName2, snapshotName2, snapshot22));
// **********
// TEST
// **********
// List snapshots under resource group
//IPage<Snapshot> snapshotsOut = await SnapshotsClient.ListByResourceGroupAsync(rgName1);
var snapshotsOut = await SnapshotsOperations.ListByResourceGroupAsync(rgName1).ToEnumerableAsync();
Assert.AreEqual(2, snapshotsOut.Count());
//Assert.Null(snapshotsOut.NextPageLink);
snapshotsOut = await SnapshotsOperations.ListByResourceGroupAsync(rgName2).ToEnumerableAsync();
Assert.AreEqual(2, snapshotsOut.Count());
//Assert.Null(snapshotsOut.NextPageLink);
// List snapshots under subscription
snapshotsOut = await SnapshotsOperations.ListAsync().ToEnumerableAsync();
Assert.True(snapshotsOut.Count() >= 4);
//if (snapshotsOut.NextPageLink != null)
//{
// snapshotsOut = await SnapshotsClient.ListNext(snapshotsOut.NextPageLink);
// Assert.True(snapshotsOut.Any());
//}
}
protected async Task DiskEncryptionSet_List_Execute(string methodName, string location = null)
{
EnsureClientsInitialized(DefaultLocation);
DiskRPLocation = location ?? DiskRPLocation;
// Data
var rgName1 = Recording.GenerateAssetName(TestPrefix);
var rgName2 = Recording.GenerateAssetName(TestPrefix);
var desName1 = Recording.GenerateAssetName(DiskNamePrefix);
var desName2 = Recording.GenerateAssetName(DiskNamePrefix);
DiskEncryptionSet des1 = GenerateDefaultDiskEncryptionSet(DiskRPLocation);
DiskEncryptionSet des2 = GenerateDefaultDiskEncryptionSet(DiskRPLocation);
// **********
// SETUP
// **********
// Create resource groups
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName1, new ResourceGroup(DiskRPLocation));
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName2, new ResourceGroup(DiskRPLocation));
// Put 4 diskEncryptionSets, 2 in each resource group
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartCreateOrUpdateAsync(rgName1, desName1, des1));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartCreateOrUpdateAsync(rgName1, desName2, des2));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartCreateOrUpdateAsync(rgName2, desName1, des1));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartCreateOrUpdateAsync(rgName2, desName2, des2));
// **********
// TEST
// **********
// List diskEncryptionSets under resource group
//IPage<DiskEncryptionSet> dessOut = await DiskEncryptionSetsClient.ListByResourceGroupAsync(rgName1).ToEnumerableAsync();
var dessOut = await DiskEncryptionSetsOperations.ListByResourceGroupAsync(rgName1).ToEnumerableAsync();
Assert.AreEqual(2, dessOut.Count());
//Assert.Null(dessOut.NextPageLink);
dessOut = await DiskEncryptionSetsOperations.ListByResourceGroupAsync(rgName2).ToEnumerableAsync();
Assert.AreEqual(2, dessOut.Count());
//Assert.Null(dessOut.NextPageLink);
// List diskEncryptionSets under subscription
dessOut = await DiskEncryptionSetsOperations.ListAsync().ToEnumerableAsync();
Assert.True(dessOut.Count() >= 4);
//if (dessOut.NextPageLink != null)
//{
// dessOut = await DiskEncryptionSetsClient.ListNext(dessOut.NextPageLink);
// Assert.True(dessOut.Any());
//}
// Delete diskEncryptionSets
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartDeleteAsync(rgName1, desName1));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartDeleteAsync(rgName1, desName2));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartDeleteAsync(rgName2, desName1));
await WaitForCompletionAsync(await DiskEncryptionSetsOperations.StartDeleteAsync(rgName2, desName2));
}
protected async Task DiskEncryptionSet_CreateDisk_Execute(string methodName, string location = null)
{
EnsureClientsInitialized(DefaultLocation);
var rgName = Recording.GenerateAssetName(TestPrefix);
var diskName = Recording.GenerateAssetName(DiskNamePrefix);
var desName = "longlivedSwaggerDES";
Disk disk = await GenerateDefaultDisk(DiskCreateOption.Empty.ToString(), rgName, 10);
disk.Location = location;
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(location));
// Get DiskEncryptionSet
DiskEncryptionSet desOut = await DiskEncryptionSetsOperations.GetAsync("longrunningrg-southeastasia", desName);
Assert.NotNull(desOut);
disk.Encryption = new Encryption
{
Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(),
DiskEncryptionSetId = desOut.Id
};
//Put Disk
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, disk));
Disk diskOut = await DisksOperations.GetAsync(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.AreEqual(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower());
Assert.AreEqual(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type);
await WaitForCompletionAsync(await DisksOperations.StartDeleteAsync(rgName, diskName));
}
protected async Task DiskEncryptionSet_UpdateDisk_Execute(string methodName, string location = null)
{
EnsureClientsInitialized(DefaultLocation);
var rgName = Recording.GenerateAssetName(TestPrefix);
var diskName = Recording.GenerateAssetName(DiskNamePrefix);
var desName = "longlivedSwaggerDES";
Disk disk = await GenerateDefaultDisk(DiskCreateOption.Empty.ToString(), rgName, 10);
disk.Location = location;
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(location));
// Put Disk with PlatformManagedKey
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, disk));
Disk diskOut = await DisksOperations.GetAsync(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.Null(diskOut.Encryption.DiskEncryptionSetId);
Assert.AreEqual(EncryptionType.EncryptionAtRestWithPlatformKey, diskOut.Encryption.Type);
// Update Disk with CustomerManagedKey
DiskEncryptionSet desOut = await DiskEncryptionSetsOperations.GetAsync("longrunningrg-southeastasia", desName);
Assert.NotNull(desOut);
disk.Encryption = new Encryption
{
Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(),
DiskEncryptionSetId = desOut.Id
};
await WaitForCompletionAsync(await DisksOperations.StartCreateOrUpdateAsync(rgName, diskName, disk));
diskOut = await DisksOperations.GetAsync(rgName, diskName);
Assert.AreEqual(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower());
Assert.AreEqual(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type);
await WaitForCompletionAsync(await DisksOperations.StartDeleteAsync(rgName, diskName));
}
#endregion
#region Generation
public static readonly GrantAccessData AccessDataDefault = new GrantAccessData(AccessLevel.Read, 1000);
protected async Task<Disk> GenerateDefaultDisk(string diskCreateOption, string rgName, int? diskSizeGB = null, IList<string> zones = null, string location = null)
{
Disk disk;
switch (diskCreateOption)
{
case "Upload":
disk = GenerateBaseDisk(diskCreateOption);
disk.CreationData.UploadSizeBytes = (long)(diskSizeGB ?? 10) * 1024 * 1024 * 1024 + 512;
break;
case "Empty":
disk = GenerateBaseDisk(diskCreateOption);
disk.DiskSizeGB = diskSizeGB;
disk.Zones = zones;
break;
case "Import":
disk = await GenerateImportDisk(diskCreateOption, rgName, location);
disk.DiskSizeGB = diskSizeGB;
disk.Zones = zones;
break;
case "Copy":
disk = await GenerateCopyDisk(rgName, diskSizeGB ?? 10, location);
disk.Zones = zones;
break;
default:
throw new ArgumentOutOfRangeException("diskCreateOption", diskCreateOption, "Unsupported option provided.");
}
return disk;
}
/// <summary>
/// Generates a disk used when the DiskCreateOption is Import
/// </summary>
/// <returns></returns>
private async Task<Disk> GenerateImportDisk(string diskCreateOption, string rgName, string location)
{
// Create a VM, so we can use its OS disk for creating the image
string storageAccountName = Recording.GenerateAssetName(DiskNamePrefix);
string asName = Recording.GenerateAssetName("as");
ImageReference imageRef = await GetPlatformVMImage(useWindowsImage: true);
VirtualMachine inputVM = null;
m_location = location;
// Create Storage Account
var storageAccountOutput = await CreateStorageAccount(rgName, storageAccountName);
// Create the VM, whose OS disk will be used in creating the image
var returnTwovm = await CreateVM(rgName, asName, storageAccountOutput, imageRef);
var createdVM = returnTwovm.Item1;
inputVM = returnTwovm.Item2;
var listResponse = await VirtualMachinesOperations.ListAllAsync().ToEnumerableAsync();
Assert.True(listResponse.Count() >= 1);
string[] id = createdVM.Id.Split('/');
string subscription = id[2];
var uri = createdVM.StorageProfile.OsDisk.Vhd.Uri;
await WaitForCompletionAsync(await VirtualMachinesOperations.StartDeleteAsync(rgName, inputVM.Name));
await WaitForCompletionAsync(await VirtualMachinesOperations.StartDeleteAsync(rgName, createdVM.Name));
Disk disk = GenerateBaseDisk(diskCreateOption);
disk.CreationData.SourceUri = uri;
disk.CreationData.StorageAccountId = "/subscriptions/" + subscription + "/resourceGroups/" + rgName + "/providers/Microsoft.Storage/storageAccounts/" + storageAccountName;
return disk;
}
/// <summary>
/// Generates a disk used when the DiskCreateOption is Copy
/// </summary>
/// <returns></returns>
private async Task<Disk> GenerateCopyDisk(string rgName, int diskSizeGB, string location)
{
// Create an empty disk
Disk originalDisk = await GenerateDefaultDisk("Empty", rgName, diskSizeGB: diskSizeGB);
await ResourceGroupsOperations.CreateOrUpdateAsync(rgName, new ResourceGroup(location));
Disk diskOut = await WaitForCompletionAsync((await DisksOperations.StartCreateOrUpdateAsync(rgName, Recording.GenerateAssetName(DiskNamePrefix + "_original"), originalDisk)));
Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id);
Snapshot snapshotOut = await WaitForCompletionAsync((await SnapshotsOperations.StartCreateOrUpdateAsync(rgName, "snapshotswaaggertest", snapshot)));
Disk copyDisk = GenerateBaseDisk("Import");
copyDisk.CreationData.SourceResourceId = snapshotOut.Id;
return copyDisk;
}
protected DiskEncryptionSet GenerateDefaultDiskEncryptionSet(string location)
{
string testVaultId = @"/subscriptions/" + TestEnvironment.SubscriptionId + "/resourcegroups/swagger/providers/Microsoft.KeyVault/vaults/swaggervault";
string encryptionKeyUri = @"https://swaggervault.vault.azure.net/keys/diskRPSSEKey/4780bcaf12384596b75cf63731f2046c";
var des = new DiskEncryptionSet(
null, null, null, location, null,
new EncryptionSetIdentity
(ResourceIdentityType.SystemAssigned.ToString(), null, null),
new KeyVaultAndKeyReference
(new SourceVault(testVaultId), encryptionKeyUri), null, null);
return des;
}
public Disk GenerateBaseDisk(string diskCreateOption)
{
var disk = new Disk(DiskRPLocation)
{
Location = DiskRPLocation,
};
disk.Sku = new DiskSku()
{
Name = StorageAccountTypes.StandardLRS.ToString()
};
disk.CreationData = new CreationData(diskCreateOption);
disk.OsType = OperatingSystemTypes.Linux;
return disk;
}
protected Snapshot GenerateDefaultSnapshot(string sourceDiskId, string snapshotStorageAccountTypes = "Standard_LRS", bool incremental = false)
{
Snapshot snapshot = GenerateBaseSnapshot(sourceDiskId, snapshotStorageAccountTypes, incremental);
return snapshot;
}
private Snapshot GenerateBaseSnapshot(string sourceDiskId, string snapshotStorageAccountTypes, bool incremental = false)
{
var snapshot = new Snapshot(null, null, null, DiskRPLocation, null, null, null, null, null, null, null, null, null, null, null, null, incremental, null);
snapshot.Sku = new SnapshotSku()
{
Name = snapshotStorageAccountTypes ?? SnapshotStorageAccountTypes.StandardLRS
};
snapshot.CreationData = new CreationData(DiskCreateOption.Copy, null, null, null, null, sourceDiskId, null, null);
return snapshot;
}
#endregion
#region Validation
private void Validate(DiskEncryptionSet diskEncryptionSetExpected, DiskEncryptionSet diskEncryptionSetActual, string expectedDESName)
{
Assert.AreEqual(expectedDESName, diskEncryptionSetActual.Name);
Assert.AreEqual(diskEncryptionSetExpected.Location, diskEncryptionSetActual.Location);
Assert.AreEqual(diskEncryptionSetExpected.ActiveKey.SourceVault.Id, diskEncryptionSetActual.ActiveKey.SourceVault.Id);
Assert.AreEqual(diskEncryptionSetExpected.ActiveKey.KeyUrl, diskEncryptionSetActual.ActiveKey.KeyUrl);
Assert.NotNull(diskEncryptionSetActual.Identity);
Assert.AreEqual(ResourceIdentityType.SystemAssigned.ToString(), diskEncryptionSetActual.Identity.Type);
}
private void Validate(Snapshot snapshotExpected, Snapshot snapshotActual, bool diskHydrated = false, bool incremental = false)
{
// snapshot resource
Assert.AreEqual(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "snapshots"), snapshotActual.Type);
Assert.NotNull(snapshotActual.Name);
Assert.AreEqual(DiskRPLocation, snapshotActual.Location);
// snapshot properties
Assert.AreEqual(snapshotExpected.Sku.Name, snapshotActual.Sku.Name);
Assert.True(snapshotActual.ManagedBy == null);
Assert.NotNull(snapshotActual.ProvisioningState);
Assert.AreEqual(incremental, snapshotActual.Incremental);
Assert.NotNull(snapshotActual.CreationData.SourceUniqueId);
if (snapshotExpected.OsType != null) //these properties are not mandatory for the client
{
Assert.AreEqual(snapshotExpected.OsType, snapshotActual.OsType);
}
if (snapshotExpected.DiskSizeGB != null)
{
// Disk resizing
Assert.AreEqual(snapshotExpected.DiskSizeGB, snapshotActual.DiskSizeGB);
}
// Creation data
CreationData creationDataExp = snapshotExpected.CreationData;
CreationData creationDataAct = snapshotActual.CreationData;
Assert.AreEqual(creationDataExp.CreateOption, creationDataAct.CreateOption);
Assert.AreEqual(creationDataExp.SourceUri, creationDataAct.SourceUri);
Assert.AreEqual(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId);
Assert.AreEqual(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId);
// Image reference
ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference;
ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference;
if (imgRefExp != null)
{
Assert.AreEqual(imgRefExp.Id, imgRefAct.Id);
Assert.AreEqual(imgRefExp.Lun, imgRefAct.Lun);
}
else
{
Assert.Null(imgRefAct);
}
}
protected void Validate(Disk diskExpected, Disk diskActual, string location, bool diskHydrated = false, bool update = false)
{
// disk resource
Assert.AreEqual(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "disks"), diskActual.Type);
Assert.NotNull(diskActual.Name);
Assert.AreEqual(location, diskActual.Location);
// disk properties
Assert.AreEqual(diskExpected.Sku.Name, diskActual.Sku.Name);
Assert.NotNull(diskActual.ProvisioningState);
Assert.AreEqual(diskExpected.OsType, diskActual.OsType);
Assert.NotNull(diskActual.UniqueId);
if (diskExpected.DiskSizeGB != null)
{
// Disk resizing
Assert.AreEqual(diskExpected.DiskSizeGB, diskActual.DiskSizeGB);
Assert.NotNull(diskActual.DiskSizeBytes);
}
if (!update)
{
if (diskExpected.DiskIopsReadWrite != null)
{
Assert.AreEqual(diskExpected.DiskIopsReadWrite, diskActual.DiskIopsReadWrite);
}
if (diskExpected.DiskMBpsReadWrite != null)
{
Assert.AreEqual(diskExpected.DiskMBpsReadWrite, diskActual.DiskMBpsReadWrite);
}
if (diskExpected.DiskIopsReadOnly != null)
{
Assert.AreEqual(diskExpected.DiskIopsReadOnly, diskActual.DiskIopsReadOnly);
}
if (diskExpected.DiskMBpsReadOnly != null)
{
Assert.AreEqual(diskExpected.DiskMBpsReadOnly, diskActual.DiskMBpsReadOnly);
}
if (diskExpected.MaxShares != null)
{
Assert.AreEqual(diskExpected.MaxShares, diskActual.MaxShares);
}
}
// Creation data
CreationData creationDataExp = diskExpected.CreationData;
CreationData creationDataAct = diskActual.CreationData;
Assert.AreEqual(creationDataExp.CreateOption, creationDataAct.CreateOption);
Assert.AreEqual(creationDataExp.SourceUri, creationDataAct.SourceUri);
Assert.AreEqual(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId);
Assert.AreEqual(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId);
// Image reference
ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference;
ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference;
if (imgRefExp != null)
{
Assert.AreEqual(imgRefExp.Id, imgRefAct.Id);
Assert.AreEqual(imgRefExp.Lun, imgRefAct.Lun);
}
else
{
Assert.Null(imgRefAct);
}
// Zones
IList<string> zonesExp = diskExpected.Zones;
IList<string> zonesAct = diskActual.Zones;
if (zonesExp != null)
{
Assert.AreEqual(zonesExp.Count, zonesAct.Count);
foreach (string zone in zonesExp)
{
////TODO
//Assert.Contains(zone, zonesAct.First());
//Assert.Contains(zone, zonesAct, StringComparer.OrdinalIgnoreCase);
}
}
else
{
Assert.Null(zonesAct);
}
}
#endregion
}
}
| {
"content_hash": "bbe5412aeed964b2ab9dfedfc834d6da",
"timestamp": "",
"source": "github",
"line_count": 742,
"max_line_length": 220,
"avg_line_length": 49.83018867924528,
"alnum_prop": 0.6407205063017255,
"repo_name": "stankovski/azure-sdk-for-net",
"id": "6b94c6555fc95edb527d91042f8318d029adf3fb",
"size": "36976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/compute/Azure.ResourceManager.Compute/tests/DiskRPTests/DiskRPTestsBase.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "33972632"
},
{
"name": "Cucumber",
"bytes": "89597"
},
{
"name": "Shell",
"bytes": "675"
}
],
"symlink_target": ""
} |
/**
* `GooglePlusAPIError` error.
*
* References:
* - https://developers.google.com/+/web/api/rest/
*
* @constructor
* @param {string} [message]
* @param {number} [code]
* @access public
*/
function GooglePlusAPIError(message, code) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'GooglePlusAPIError';
this.message = message;
this.code = code;
}
// Inherit from `Error`.
GooglePlusAPIError.prototype.__proto__ = Error.prototype;
// Expose constructor.
module.exports = GooglePlusAPIError;
| {
"content_hash": "ad0be0cfbed5aaa532e376def2be9480",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 57,
"avg_line_length": 22.92,
"alnum_prop": 0.6631762652705061,
"repo_name": "sarataha/yalla-netlob",
"id": "f5ae513c508d03c032415863f93431bd576e7a11",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/passport-google-oauth20/lib/errors/googleplusapierror.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "46599"
},
{
"name": "HTML",
"bytes": "72331"
},
{
"name": "JavaScript",
"bytes": "337675"
}
],
"symlink_target": ""
} |
using std::shared_ptr;
namespace Annwvyn
{
AnnEngine* AnnGetEngine() { return AnnEngine::Instance(); }
AnnAudioEnginePtr AnnGetAudioEngine() { return AnnGetEngine()->getAudioEngine(); }
AnnPhysicsEnginePtr AnnGetPhysicsEngine() { return AnnGetEngine()->getPhysicsEngine(); }
AnnFilesystemManagerPtr AnnGetFileSystemManager() { return AnnGetEngine()->getFileSystemManager(); }
AnnLevelManagerPtr AnnGetLevelManager() { return AnnGetEngine()->getLevelManager(); }
AnnEventManagerPtr AnnGetEventManager() { return AnnGetEngine()->getEventManager(); }
AnnPlayerBodyPtr AnnGetPlayer() { return AnnGetEngine()->getPlayer(); };
AnnResourceManagerPtr AnnGetResourceManager() { return AnnGetEngine()->getResourceManager(); }
AnnSceneryManagerPtr AnnGetSceneryManager() { return AnnGetEngine()->getSceneryManager(); }
AnnOgreVRRendererPtr AnnGetVRRenderer() { return AnnGetEngine()->getVRRenderer(); }
AnnScriptManagerPtr AnnGetScriptManager() { return AnnGetEngine()->getScriptManager(); }
AnnGameObjectManagerPtr AnnGetGameObjectManager() { return AnnGetEngine()->getGameObjectManager(); }
AnnConsolePtr AnnGetOnScreenConsole() { return AnnGetEngine()->getOnScreenConsole(); }
AnnStringUtilityPtr AnnGetStringUtility() { return AnnGetEngine()->getStringUtility(); }
}
| {
"content_hash": "0ce448bd32eb00308cc75f9c060fe94f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 101,
"avg_line_length": 63.8,
"alnum_prop": 0.7915360501567398,
"repo_name": "Ybalrid/Annwvyn",
"id": "cc9456903f4e4c5ed00a20029513d5f063996689",
"size": "1463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AnnGetter.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6717"
},
{
"name": "C",
"bytes": "1891"
},
{
"name": "C++",
"bytes": "978781"
},
{
"name": "CMake",
"bytes": "19954"
},
{
"name": "GLSL",
"bytes": "36680"
},
{
"name": "Inno Setup",
"bytes": "1878"
},
{
"name": "Shell",
"bytes": "753"
}
],
"symlink_target": ""
} |
import {bindable, inject} from 'aurelia-framework';
import {Wizard} from './wizard';
@inject(Wizard)
export class Index{
showing = false;
wizardShowing = false;
constructor(wizard){
this.wizard = wizard;
this.steps = [
new Step(1, 'Step one', 'modal/wizard-step-one'),
new Step(2, 'Step two', 'modal/wizard-step-two'),
new Step(3, 'Step three', 'modal/wizard-step-three')
];
this.activeStep = this.steps[0];
}
showModal(){
this.showing = true;
}
closeModal(){
this.showing = false;
}
showWizard(){
this.wizardShowing = true;
}
nextStep(){
var self = this;
if (this.activeStep.id === this.steps.length) {
this.activeStep = this.steps[0];//jrt
self.wizardShowing = false;
} else {
this.activeStep = this.steps[this.activeStep.id];
}
}
closeWizard(){
// this.wizardShowing = false;
// added logic to close -- jrt
if (this.activeStep.id === this.steps.length) {
this.activeStep = this.steps[0];//jrt
self.wizardShowing = false;
} else {
this.wizardShowing = false;
}
}
}
class Step {
id = 0;
title = '';
path = '';
constructor(id, title, path){
this.id = id;
this.title = title;
this.path = path;
}
}
| {
"content_hash": "1080e666610289c13725662c8a81ccb7",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 58,
"avg_line_length": 22.714285714285715,
"alnum_prop": 0.5911949685534591,
"repo_name": "forsmyr/aurelia-samples",
"id": "78699f4610e107abd9ef4c48ca58046fc85747e4",
"size": "1272",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/modal/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6511"
},
{
"name": "HTML",
"bytes": "10431"
},
{
"name": "JavaScript",
"bytes": "63210"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>8. README.S390</title>
<link rel="stylesheet" type="text/css" href="vg_basic.css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="Valgrind Documentation">
<link rel="up" href="dist.html" title="Valgrind Distribution Documents">
<link rel="prev" href="dist.readme-packagers.html" title="7. README_PACKAGERS">
<link rel="next" href="dist.readme-android.html" title="9. README.android">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div><table class="nav" width="100%" cellspacing="3" cellpadding="3" border="0" summary="Navigation header"><tr>
<td width="22px" align="center" valign="middle"><a accesskey="p" href="dist.readme-packagers.html"><img src="images/prev.png" width="18" height="21" border="0" alt="Prev"></a></td>
<td width="25px" align="center" valign="middle"><a accesskey="u" href="dist.html"><img src="images/up.png" width="21" height="18" border="0" alt="Up"></a></td>
<td width="31px" align="center" valign="middle"><a accesskey="h" href="index.html"><img src="images/home.png" width="27" height="20" border="0" alt="Up"></a></td>
<th align="center" valign="middle">Valgrind Distribution Documents</th>
<td width="22px" align="center" valign="middle"><a accesskey="n" href="dist.readme-android.html"><img src="images/next.png" width="18" height="21" border="0" alt="Next"></a></td>
</tr></table></div>
<div class="chapter">
<div class="titlepage"><div><div><h1 class="title">
<a name="dist.readme-s390"></a>8. README.S390</h1></div></div></div>
<div class="literallayout"><p><br>
<br>
Requirements<br>
------------<br>
- You need GCC 3.4 or later to compile the s390 port.<br>
- To run valgrind a z10 machine or any later model is recommended.<br>
Older machine models down to and including z990 may work but have<br>
not been tested extensively.<br>
<br>
<br>
Limitations<br>
-----------<br>
- 31-bit client programs are not supported.<br>
- Hexadecimal floating point is not supported.<br>
- Transactional memory is not supported.<br>
- Instructions operating on vector registers are not supported.<br>
- memcheck, cachegrind, drd, helgrind, massif, lackey, and none are<br>
supported. <br>
- On machine models predating z10, cachegrind will assume a z10 cache<br>
architecture. Otherwise, cachegrind will query the hosts cache system<br>
and use those parameters.<br>
- callgrind and all experimental tools are currently not supported.<br>
- Some gcc versions use mvc to copy 4/8 byte values. This will affect<br>
certain debug messages. For example, memcheck will complain about<br>
4 one-byte reads/writes instead of just a single read/write.<br>
<br>
<br>
Hardware facilities<br>
-------------------<br>
Valgrind does not require that the host machine has the same hardware<br>
facilities as the machine for which the client program was compiled.<br>
This is convenient. If possible, the JIT compiler will translate the<br>
client instructions according to the facilities available on the host.<br>
This means, though, that probing for hardware facilities by issuing<br>
instructions from that facility and observing whether SIGILL is thrown<br>
may not work. As a consequence, programs that attempt to do so may<br>
behave differently. It is believed that this is a rare use case.<br>
<br>
<br>
Recommendations<br>
---------------<br>
Applications should be compiled with -fno-builtin to avoid<br>
false positives due to builtin string operations when running memcheck.<br>
<br>
<br>
Reading Material<br>
----------------<br>
(1) Linux for zSeries ELF ABI Supplement<br>
http://refspecs.linuxfoundation.org/ELF/zSeries/index.html<br>
(2) z/Architecture Principles of Operation<br>
http://publibfi.boulder.ibm.com/epubs/pdf/dz9zr010.pdf<br>
(3) z/Architecture Reference Summary<br>
http://publibfi.boulder.ibm.com/epubs/pdf/dz9zs008.pdf<br>
<br>
</p></div>
</div>
<div>
<br><table class="nav" width="100%" cellspacing="3" cellpadding="2" border="0" summary="Navigation footer">
<tr>
<td rowspan="2" width="40%" align="left">
<a accesskey="p" href="dist.readme-packagers.html"><< 7. README_PACKAGERS</a> </td>
<td width="20%" align="center"><a accesskey="u" href="dist.html">Up</a></td>
<td rowspan="2" width="40%" align="right"> <a accesskey="n" href="dist.readme-android.html">9. README.android >></a>
</td>
</tr>
<tr><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td></tr>
</table>
</div>
</body>
</html>
| {
"content_hash": "27afc9029df55fc44145bbf8f3aba68a",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 180,
"avg_line_length": 50.06521739130435,
"alnum_prop": 0.7077724706904038,
"repo_name": "hlzz/dotfiles",
"id": "5c028c2294c0375c79b53784cf09f46e03fdb121",
"size": "4606",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dev/valgrind-3.11.0/docs/html/dist.readme-s390.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "1240"
},
{
"name": "Arc",
"bytes": "38"
},
{
"name": "Assembly",
"bytes": "449468"
},
{
"name": "Batchfile",
"bytes": "16152"
},
{
"name": "C",
"bytes": "102303195"
},
{
"name": "C++",
"bytes": "155056606"
},
{
"name": "CMake",
"bytes": "7200627"
},
{
"name": "CSS",
"bytes": "179330"
},
{
"name": "Cuda",
"bytes": "30026"
},
{
"name": "D",
"bytes": "2152"
},
{
"name": "Emacs Lisp",
"bytes": "14892"
},
{
"name": "FORTRAN",
"bytes": "5276"
},
{
"name": "Forth",
"bytes": "3637"
},
{
"name": "GAP",
"bytes": "14495"
},
{
"name": "GLSL",
"bytes": "438205"
},
{
"name": "Gnuplot",
"bytes": "327"
},
{
"name": "Groff",
"bytes": "518260"
},
{
"name": "HLSL",
"bytes": "965"
},
{
"name": "HTML",
"bytes": "2003175"
},
{
"name": "Haskell",
"bytes": "10370"
},
{
"name": "IDL",
"bytes": "2466"
},
{
"name": "Java",
"bytes": "219109"
},
{
"name": "JavaScript",
"bytes": "1618007"
},
{
"name": "Lex",
"bytes": "119058"
},
{
"name": "Lua",
"bytes": "23167"
},
{
"name": "M",
"bytes": "1080"
},
{
"name": "M4",
"bytes": "292475"
},
{
"name": "Makefile",
"bytes": "7112810"
},
{
"name": "Matlab",
"bytes": "1582"
},
{
"name": "NSIS",
"bytes": "34176"
},
{
"name": "Objective-C",
"bytes": "65312"
},
{
"name": "Objective-C++",
"bytes": "269995"
},
{
"name": "PAWN",
"bytes": "4107117"
},
{
"name": "PHP",
"bytes": "2690"
},
{
"name": "Pascal",
"bytes": "5054"
},
{
"name": "Perl",
"bytes": "485508"
},
{
"name": "Pike",
"bytes": "1338"
},
{
"name": "Prolog",
"bytes": "5284"
},
{
"name": "Python",
"bytes": "16799659"
},
{
"name": "QMake",
"bytes": "89858"
},
{
"name": "Rebol",
"bytes": "291"
},
{
"name": "Ruby",
"bytes": "21590"
},
{
"name": "Scilab",
"bytes": "120244"
},
{
"name": "Shell",
"bytes": "2266191"
},
{
"name": "Slash",
"bytes": "1536"
},
{
"name": "Smarty",
"bytes": "1368"
},
{
"name": "Swift",
"bytes": "331"
},
{
"name": "Tcl",
"bytes": "1911873"
},
{
"name": "TeX",
"bytes": "11981"
},
{
"name": "Verilog",
"bytes": "3893"
},
{
"name": "VimL",
"bytes": "595114"
},
{
"name": "XSLT",
"bytes": "62675"
},
{
"name": "Yacc",
"bytes": "307000"
},
{
"name": "eC",
"bytes": "366863"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_05) on Thu Jul 10 12:59:58 PDT 2008 -->
<TITLE>
ReporterManagerControllerTest.MockAgent
</TITLE>
<META NAME="keywords" CONTENT="edu.sdsc.inca.agent.ReporterManagerControllerTest.MockAgent class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="ReporterManagerControllerTest.MockAgent";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.html" title="class in edu.sdsc.inca.agent"><B>PREV CLASS</B></A>
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerException.html" title="class in edu.sdsc.inca.agent"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html" target="_top"><B>FRAMES</B></A>
<A HREF="ReporterManagerControllerTest.MockAgent.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: <A HREF="#nested_classes_inherited_from_class_java.lang.Thread">NESTED</A> | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
edu.sdsc.inca.agent</FONT>
<BR>
Class ReporterManagerControllerTest.MockAgent</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.lang.Thread
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>edu.sdsc.inca.agent.ReporterManagerControllerTest.MockAgent</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.lang.Runnable</DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.html" title="class in edu.sdsc.inca.agent">ReporterManagerControllerTest</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public static class <B>ReporterManagerControllerTest.MockAgent</B><DT>extends java.lang.Thread</DL>
</PRE>
<P>
Emulates the agent's tasks
<P>
<P>
<HR>
<P>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<A NAME="nested_class_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Nested Class Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="nested_classes_inherited_from_class_java.lang.Thread"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Nested classes/interfaces inherited from class java.lang.Thread</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler</CODE></TD>
</TR>
</TABLE>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#numConnections">numConnections</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#numConnectionsReceived">numConnectionsReceived</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#port">port</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> edu.sdsc.inca.protocol.ProtocolReader</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#reader">reader</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> edu.sdsc.inca.protocol.ProtocolWriter</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#writer">writer</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_java.lang.Thread"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Fields inherited from class java.lang.Thread</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY</CODE></TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#ReporterManagerControllerTest.MockAgent(boolean, edu.sdsc.inca.agent.ReporterManagerController)">ReporterManagerControllerTest.MockAgent</A></B>(boolean auth,
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerController.html" title="class in edu.sdsc.inca.agent">ReporterManagerController</A> rmc)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#cleanup()">cleanup</A></B>()</CODE>
<BR>
Ensure's correct cleanup.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#mockAgentRegister()">mockAgentRegister</A></B>()</CODE>
<BR>
Mimics the agent's register task</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html#run()">run</A></B>()</CODE>
<BR>
Allows this mock agent to be run as a thread</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Thread"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Thread</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="writer"><!-- --></A><H3>
writer</H3>
<PRE>
public edu.sdsc.inca.protocol.ProtocolWriter <B>writer</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="reader"><!-- --></A><H3>
reader</H3>
<PRE>
public edu.sdsc.inca.protocol.ProtocolReader <B>reader</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="port"><!-- --></A><H3>
port</H3>
<PRE>
public int <B>port</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="numConnections"><!-- --></A><H3>
numConnections</H3>
<PRE>
public int <B>numConnections</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="numConnectionsReceived"><!-- --></A><H3>
numConnectionsReceived</H3>
<PRE>
public int <B>numConnectionsReceived</B></PRE>
<DL>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="ReporterManagerControllerTest.MockAgent(boolean, edu.sdsc.inca.agent.ReporterManagerController)"><!-- --></A><H3>
ReporterManagerControllerTest.MockAgent</H3>
<PRE>
public <B>ReporterManagerControllerTest.MockAgent</B>(boolean auth,
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerController.html" title="class in edu.sdsc.inca.agent">ReporterManagerController</A> rmc)
throws java.lang.Exception</PRE>
<DL>
<DL>
<DT><B>Throws:</B>
<DD><CODE>java.lang.Exception</CODE></DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="run()"><!-- --></A><H3>
run</H3>
<PRE>
public void <B>run</B>()</PRE>
<DL>
<DD>Allows this mock agent to be run as a thread
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>run</CODE> in interface <CODE>java.lang.Runnable</CODE><DT><B>Overrides:</B><DD><CODE>run</CODE> in class <CODE>java.lang.Thread</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="mockAgentRegister()"><!-- --></A><H3>
mockAgentRegister</H3>
<PRE>
public java.lang.String <B>mockAgentRegister</B>()
throws java.lang.Exception</PRE>
<DL>
<DD>Mimics the agent's register task
<P>
<DD><DL>
<DT><B>Returns:</B><DD>The name of the resource that registered.
<DT><B>Throws:</B>
<DD><CODE>java.lang.Exception</CODE> - if test fails</DL>
</DD>
</DL>
<HR>
<A NAME="cleanup()"><!-- --></A><H3>
cleanup</H3>
<PRE>
public void <B>cleanup</B>()
throws java.io.IOException</PRE>
<DL>
<DD>Ensure's correct cleanup. Shutdown the reporter manager and close the
streams and sockets.
<P>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE> - if problem cleaning up</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerControllerTest.html" title="class in edu.sdsc.inca.agent"><B>PREV CLASS</B></A>
<A HREF="../../../../edu/sdsc/inca/agent/ReporterManagerException.html" title="class in edu.sdsc.inca.agent"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html" target="_top"><B>FRAMES</B></A>
<A HREF="ReporterManagerControllerTest.MockAgent.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: <A HREF="#nested_classes_inherited_from_class_java.lang.Thread">NESTED</A> | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "73148dea7ba6a26e10b1a14e3ba9960d",
"timestamp": "",
"source": "github",
"line_count": 465,
"max_line_length": 562,
"avg_line_length": 39.12903225806452,
"alnum_prop": 0.6461115691123935,
"repo_name": "IncaProject/IncaProject.github.io",
"id": "c5f55f88edec662eb04d7d27fe889736a0c8042c",
"size": "18195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "releases/2.5/docs/javadocs/inca-agent/edu/sdsc/inca/agent/ReporterManagerControllerTest.MockAgent.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1063094"
},
{
"name": "HTML",
"bytes": "42399883"
},
{
"name": "JavaScript",
"bytes": "130123"
},
{
"name": "Ruby",
"bytes": "157"
},
{
"name": "Shell",
"bytes": "117129"
}
],
"symlink_target": ""
} |
<div>
<ProgressBar striped variant="success" now={40} />
<ProgressBar striped variant="info" now={20} />
<ProgressBar striped variant="warning" now={60} />
<ProgressBar striped variant="danger" now={80} />
</div>;
| {
"content_hash": "47552a76ba3a3891c11012734c96ad02",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 52,
"avg_line_length": 37,
"alnum_prop": 0.6756756756756757,
"repo_name": "glenjamin/react-bootstrap",
"id": "6abc7a0698da3affec4d865fe508cbd06fb55b8c",
"size": "222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/src/examples/ProgressBar/Striped.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19124"
},
{
"name": "JavaScript",
"bytes": "571814"
},
{
"name": "TypeScript",
"bytes": "8724"
}
],
"symlink_target": ""
} |
Templates are what they sound like they should be: files into which we pass data to form complete HTTP responses. For a web application these responses would typically be full HTML documents. For an API, they would most often be JSON or possibly XML. The majority of the code in template files is often markup, but there will also be sections of Elixir code for Phoenix to compile and evaluate. The fact that Phoenix templates are pre-compiled makes them extremely fast.
EEx is the default template system in Phoenix, and it is quite similar to ERB in Ruby. It is actually part of Elixir itself, and Phoenix uses EEx templates to create files like the router and the main application view while generating a new application.
As we learned in the [View Guide](views.html), by default, templates live in the `lib/hello_web/templates` directory, organized into directories named after a view. Each directory has its own view module to render the templates in it.
### Examples
We've already seen several ways in which templates are used, notably in the [Adding Pages Guide](adding_pages.html) and the [Views Guide](views.html). We may cover some of the same territory here, but we will certainly add some new information.
##### hello_web.ex
Phoenix generates a `lib/hello_web.ex` file that serves as place to group common imports and aliases. All declarations here within the `view` block apply to all your templates.
Let's make some additions to our application so we can experiment a little.
First, let's define a new route in `lib/hello_web/router.ex`.
```elixir
defmodule HelloWeb.Router do
...
scope "/", HelloWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
get "/test", PageController, :test
end
# Other scopes may use custom stacks.
# scope "/api", Hello do
# pipe_through :api
# end
end
```
Now, let's define the controller action we specified in the route. We'll add a `test/2` action in the `lib/hello_web/controllers/page_controller.ex` file.
```elixir
defmodule HelloWeb.PageController do
...
def test(conn, _params) do
render conn, "test.html"
end
end
```
We're going to create a function that tells us which controller and action are handling our request.
To do that, we need to import the `action_name/1` and `controller_module/1` functions from `Phoenix.Controller` in `lib/hello_web.ex`.
```elixir
def view do
quote do
use Phoenix.View, root: "lib/hello_web/templates",
namespace: HelloWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1,
action_name: 1, controller_module: 1]
...
end
end
```
Next, let's define a `handler_info/1` function at the bottom of the ` lib/hello_web/views/page_view.ex` which makes use of the `controller_module/1` and `action_name/1` functions we just imported. We'll also define a `connection_keys/1` function that we'll use in a moment.
```elixir
defmodule HelloWeb.PageView do
use HelloWeb, :view
def handler_info(conn) do
"Request Handled By: #{controller_module conn}.#{action_name conn}"
end
def connection_keys(conn) do
conn
|> Map.from_struct()
|> Map.keys()
end
end
```
We have a route. We created a new controller action. We have made modifications to the main application view. Now all we need is a new template to display the string we get from `handler_info/1`. Let's create a new one at `lib/hello_web/templates/page/test.html.eex`.
```html
<div class="jumbotron">
<p><%= handler_info @conn %></p>
</div>
```
Notice that `@conn` is available to us in the template for free via the `assigns` map.
If we visit [localhost:4000/test](http://localhost:4000/test), we will see that our page is brought to us by `Elixir.HelloWeb.PageController.test`.
We can define functions in any individual view in `lib/hello_web/views`. Functions defined in an individual view will only be available to templates which that view renders. For example, functions like our `handler_info` above, will only be available to templates in `lib/hello_web/templates/page`.
##### Displaying Lists
So far, we've only displayed singular values in our templates - strings here, and integers in other guides. How would we approach displaying all the elements of a list?
The answer is that we can use Elixir's list comprehensions.
Now that we have a function, visible to our template, that returns a list of keys in the `conn` struct, all we need to do is modify our `lib/hello_web/templates/page/test.html.eex` template a bit to display them.
We can add a header and a list comprehension like this.
```html
<div class="jumbotron">
<p><%= handler_info @conn %></p>
<h3>Keys for the conn Struct</h3>
<%= for key <- connection_keys @conn do %>
<p><%= key %></p>
<% end %>
</div>
```
We use the list of keys returned by the `connection_keys` function as the source list to iterate over. Note that we need the `=` in both `<%=` - one for the top line of the list comprehension and the other to display the key. Without them, nothing would actually be displayed.
When we visit [localhost:4000/test](http://localhost:4000/test) again, we see all the keys displayed.
##### Render templates within templates
In our list comprehension example above, the part that actually displays the values is quite simple.
```html
<p><%= key %></p>
```
We are probably fine with leaving this in place. Quite often, however, this display code is somewhat more complex, and putting it in the middle of a list comprehension makes our templates harder to read.
The simple solution is to use another template! Templates are just function calls, so like regular code, composing your greater template by small, purpose-built functions can lead to clearer design. This is simply a continuation of the rendering chain we have already seen. Layouts are templates into which regular templates are rendered. Regular templates may have other templates rendered into them.
Let's turn this display snippet into its own template. Let's create a new template file at `lib/hello_web/templates/page/key.html.eex`, like this.
```html
<p><%= @key %></p>
```
We need to change `key` to `@key` here because this is a new template, not part of a list comprehension. The way we pass data into a template is by the `assigns` map, and the way we get the values out of the `assigns` map is by referencing the keys with a preceding `@`. `@` is actually a macro that translates `@key` to `Map.get(assigns, :key)`.
Now that we have a template, we simply render it within our list comprehension in the `test.html.eex` template.
```html
<div class="jumbotron">
<p><%= handler_info @conn %></p>
<h3>Keys for the conn Struct</h3>
<%= for key <- connection_keys @conn do %>
<%= render "key.html", key: key %>
<% end %>
</div>
```
Let's take a look at [localhost:4000/test](http://localhost:4000/test) again. The page should look exactly as it did before.
##### Shared Templates Across Views
Often, we find that small pieces of data need to be rendered the same way in different parts of the application. It's a good practice to move these templates into their own shared directory to indicate that they ought to be available anywhere in the app.
Let's move our template into a shared view.
`key.html.eex` is currently rendered by the `HelloWeb.PageView` module, but we use a render call which assumes that the current schema is what we want to render with. We could make that explicit, and re-write it like this:
```html
<div class="jumbotron">
...
<%= for key <- connection_keys @conn do %>
<%= render HelloWeb.PageView, "key.html", key: key %>
<% end %>
</div>
```
Since we want this to live in a new `lib/hello_web/templates/shared` directory, we need a new individual view to render templates in that directory, `lib/hello_web/views/shared_view.ex`.
```elixir
defmodule HelloWeb.SharedView do
use HelloWeb, :view
end
```
Now we can move `key.html.eex` from the `lib/hello_web/templates/page` directory into the `lib/hello_web/templates/shared` directory. Once that happens, we can change the render call in `lib/hello_web/templates/page/test.html.eex` to use the new `HelloWeb.SharedView`.
```html
<%= for key <- connection_keys @conn do %>
<%= render HelloWeb.SharedView, "key.html", key: key %>
<% end %>
```
Going back to [localhost:4000/test](http://localhost:4000/test) again. The page should look exactly as it did before.
| {
"content_hash": "3d585cde95ac2be4eb7c8d1c23673261",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 470,
"avg_line_length": 44.15979381443299,
"alnum_prop": 0.7280261468425353,
"repo_name": "trarbr/phoenix",
"id": "ccfcf20864249c774d99e19c851cee4a1e5f9186",
"size": "8580",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "guides/docs/templates.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50"
},
{
"name": "Elixir",
"bytes": "921550"
},
{
"name": "HTML",
"bytes": "4578"
},
{
"name": "JavaScript",
"bytes": "134986"
}
],
"symlink_target": ""
} |
package org.modelmapper.internal;
import org.modelmapper.Condition;
import org.modelmapper.Converter;
import org.modelmapper.ExpressionMap;
import org.modelmapper.PropertyMap;
import org.modelmapper.Provider;
import org.modelmapper.TypeMap;
import org.modelmapper.internal.util.Assert;
import org.modelmapper.internal.util.Objects;
import org.modelmapper.internal.util.Types;
import org.modelmapper.spi.DestinationSetter;
import org.modelmapper.spi.Mapping;
import org.modelmapper.spi.PropertyInfo;
import org.modelmapper.spi.SourceGetter;
import org.modelmapper.spi.TypeSafeSourceGetter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
/**
* TypeMap implementation.
*
* @author Jonathan Halterman
*/
class TypeMapImpl<S, D> implements TypeMap<S, D> {
private final Class<S> sourceType;
private final Class<D> destinationType;
private final String name;
final InheritingConfiguration configuration;
private final MappingEngineImpl engine;
/** Guarded by "mappings" */
private final Map<String, InternalMapping> mappings = new TreeMap<String, InternalMapping>();
private Converter<S, D> converter;
private Converter<S, D> preConverter;
private Converter<S, D> postConverter;
private Condition<?, ?> condition;
private Provider<D> provider;
private Converter<?, ?> propertyConverter;
private Condition<?, ?> propertyCondition;
private Provider<?> propertyProvider;
TypeMapImpl(Class<S> sourceType, Class<D> destinationType, String name,
InheritingConfiguration configuration, MappingEngineImpl engine) {
this.sourceType = sourceType;
this.destinationType = destinationType;
this.name = name;
this.configuration = configuration;
this.engine = engine;
}
private TypeMapImpl(TypeMapImpl<? super S, ? super D> baseTypeMap, Class<S> sourceTYpe, Class<D> destinationType) {
this.sourceType = sourceTYpe;
this.destinationType = destinationType;
this.name = baseTypeMap.name;
this.configuration = baseTypeMap.configuration;
this.engine = baseTypeMap.engine;
synchronized (baseTypeMap.mappings) {
mappings.putAll(baseTypeMap.mappings);
}
}
@Override
public TypeMap<S, D> addMappings(PropertyMap<S, D> propertyMap) {
if (sourceType.isEnum() || destinationType.isEnum())
throw new Errors().mappingForEnum().toConfigurationException();
synchronized (mappings) {
for (InternalMapping mapping : ExplicitMappingBuilder.build(sourceType,
destinationType, configuration, propertyMap)) {
InternalMapping existingMapping = addMapping(mapping);
if (existingMapping != null && existingMapping.isExplicit())
throw new Errors().duplicateMapping(mapping.getLastDestinationProperty())
.toConfigurationException();
}
}
return this;
}
@Override
public Condition<?, ?> getCondition() {
return condition;
}
@Override
public Converter<S, D> getConverter() {
return converter;
}
@Override
public Class<D> getDestinationType() {
return destinationType;
}
@Override
public List<Mapping> getMappings() {
synchronized (mappings) {
return new ArrayList<Mapping>(mappings.values());
}
}
@Override
public String getName() {
return name;
}
@Override
public Converter<S, D> getPostConverter() {
return postConverter;
}
@Override
public Converter<S, D> getPreConverter() {
return preConverter;
}
@Override
public Condition<?, ?> getPropertyCondition() {
return propertyCondition;
}
@Override
public Converter<?, ?> getPropertyConverter() {
return propertyConverter;
}
@Override
public Provider<?> getPropertyProvider() {
return propertyProvider;
}
@Override
public Provider<D> getProvider() {
return provider;
}
@Override
public Class<S> getSourceType() {
return sourceType;
}
@Override
public List<PropertyInfo> getUnmappedProperties() {
PathProperties pathProperties = getDestinationProperties();
synchronized (mappings) {
for (Map.Entry<String, InternalMapping> entry : mappings.entrySet()) {
pathProperties.matchAndRemove(entry.getKey());
}
}
return pathProperties.get();
}
@Override
public D map(S source) {
Class<S> sourceType = Types.deProxy(source.getClass());
MappingContextImpl<S, D> context = new MappingContextImpl<S, D>(source, sourceType, null,
destinationType, null, name, engine);
D result = null;
try {
result = engine.typeMap(context, this);
} catch (Throwable t) {
context.errors.errorMapping(sourceType, destinationType, t);
}
context.errors.throwMappingExceptionIfErrorsExist();
return result;
}
@Override
public void map(S source, D destination) {
Class<S> sourceType = Types.deProxy(source.getClass());
MappingContextImpl<S, D> context = new MappingContextImpl<S, D>(source, sourceType,
destination, destinationType, null, name, engine);
try {
engine.typeMap(context, this);
} catch (Throwable t) {
context.errors.errorMapping(sourceType, destinationType, t);
}
context.errors.throwMappingExceptionIfErrorsExist();
}
@Override
public TypeMap<S, D> setCondition(Condition<?, ?> condition) {
this.condition = Assert.notNull(condition, "condition");
return this;
}
@Override
public TypeMap<S, D> setConverter(Converter<S, D> converter) {
this.converter = Assert.notNull(converter, "converter");
return this;
}
@Override
public TypeMap<S, D> setPostConverter(Converter<S, D> converter) {
this.postConverter = Assert.notNull(converter, "converter");
return this;
}
@Override
public TypeMap<S, D> setPreConverter(Converter<S, D> converter) {
this.preConverter = Assert.notNull(converter, "converter");
return this;
}
@Override
public TypeMap<S, D> setPropertyCondition(Condition<?, ?> condition) {
propertyCondition = Assert.notNull(condition, "condition");
return this;
}
@Override
public TypeMap<S, D> setPropertyConverter(Converter<?, ?> converter) {
propertyConverter = Assert.notNull(converter, "converter");
return this;
}
@Override
public TypeMap<S, D> setPropertyProvider(Provider<?> provider) {
propertyProvider = Assert.notNull(provider, "provider");
return this;
}
@Override
public TypeMap<S, D> setProvider(Provider<D> provider) {
this.provider = Assert.notNull(provider, "provider");
return this;
}
@Override
public <V> TypeMap<S, D> addMapping(SourceGetter<S> sourceGetter, DestinationSetter<D, V> destinationSetter) {
new ReferenceMapExpressionImpl<S, D>(this).map(sourceGetter, destinationSetter);
return this;
}
@Override
public TypeMap<S, D> addMappings(ExpressionMap<S, D> mapper) {
mapper.configure(new ConfigurableConditionExpressionImpl<S, D>(this));
return this;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("TypeMap[")
.append(sourceType.getSimpleName())
.append(" -> ")
.append(destinationType.getSimpleName());
if (name != null)
b.append(' ').append(name);
return b.append(']').toString();
}
@Override
public void validate() {
if (converter != null || preConverter != null || postConverter != null)
return;
Errors errors = new Errors();
List<PropertyInfo> unmappedProperties = getUnmappedProperties();
if (!unmappedProperties.isEmpty())
errors.errorUnmappedProperties(this, unmappedProperties);
errors.throwValidationExceptionIfErrorsExist();
}
@Override
public <DS extends S, DD extends D> TypeMap<S, D> include(Class<DS> sourceType, Class<DD> destinationType) {
TypeMapImpl<DS, DD> derivedTypeMap = new TypeMapImpl<DS, DD>(this, sourceType, destinationType);
configuration.typeMapStore.put(derivedTypeMap);
return this;
}
@Override
public TypeMap<S, D> include(Class<? super D> baseDestinationType) {
if (provider == null)
provider = new Provider<D>() {
@Override
public D get(ProvisionRequest<D> request) {
return Objects.instantiate(destinationType);
}
};
configuration.typeMapStore.put(sourceType, baseDestinationType, this);
return this;
}
@Override
public TypeMap<S, D> includeBase(Class<? super S> sourceType, Class<? super D> destinationType) {
@SuppressWarnings("unchecked")
TypeMapImpl<? super S, ? super D> baseTypeMap = (TypeMapImpl<? super S, ? super D>)
configuration.typeMapStore.get(sourceType, destinationType, name);
Assert.notNull(baseTypeMap, "Cannot find base TypeMap");
synchronized (baseTypeMap.mappings) {
for (Map.Entry<String, InternalMapping> entry : baseTypeMap.mappings.entrySet()) {
addMapping(entry.getValue());
}
}
return this;
}
@Override
public <P> TypeMap<S, D> include(TypeSafeSourceGetter<S, P> sourceGetter, Class<P> propertyType) {
@SuppressWarnings("unchecked")
TypeMapImpl<? super S, ? super D> childTypeMap = (TypeMapImpl<? super S, ? super D>)
configuration.typeMapStore.get(propertyType, destinationType, name);
Assert.notNull(childTypeMap, "Cannot find child TypeMap");
List<Accessor> accessors = PropertyReferenceCollector.collect(this, sourceGetter);
for (Mapping mapping : childTypeMap.getMappings()) {
InternalMapping internalMapping = (InternalMapping) mapping;
addMapping(internalMapping.createMergedCopy(accessors, Collections.<PropertyInfo>emptyList()));
}
return this;
}
@Override
public TypeMap<S, D> implicitMappings() {
ImplicitMappingBuilder.build(null, this, configuration.typeMapStore, configuration.converterStore);
return this;
}
void addMappingIfAbsent(InternalMapping mapping) {
synchronized (mappings) {
if (!mappings.containsKey(mapping.getPath()))
mappings.put(mapping.getPath(), mapping);
}
}
InternalMapping addMapping(InternalMapping mapping) {
synchronized (mappings) {
return mappings.put(mapping.getPath(), mapping);
}
}
/**
* Used by PropertyMapBuilder to determine if a skipped mapping exists for the {@code path}. No
* need to synchronize here since the TypeMap is not exposed publicly yet.
*/
boolean isSkipped(String path) {
Mapping mapping = mappings.get(path);
return mapping != null && mapping.isSkipped();
}
/**
* Used by ImplicitMappingBuilder to determine if a mapping for the {@code path} already exists.
* No need to synchronize here since the TypeMap is not exposed publicly yet.
*/
Mapping mappingFor(String path) {
return mappings.get(path);
}
boolean isFullMatching() {
return getUnmappedProperties().isEmpty()
|| configuration.valueAccessStore.getFirstSupportedReader(sourceType) == null;
}
private PathProperties getDestinationProperties() {
PathProperties pathProperties = new PathProperties();
Set<Class<?>> classes = new HashSet<Class<?>>();
Stack<Property> propertyStack = new Stack<Property>();
propertyStack.push(new Property("", TypeInfoRegistry.typeInfoFor(destinationType, configuration)));
while (!propertyStack.isEmpty()) {
Property property = propertyStack.pop();
classes.add(property.typeInfo.getType());
for (Map.Entry<String, Mutator> entry : property.typeInfo.getMutators().entrySet()) {
if (entry.getValue() instanceof PropertyInfoImpl.FieldPropertyInfo
&& !configuration.isFieldMatchingEnabled()) {
continue;
}
String path = property.prefix + entry.getKey() + ".";
Mutator mutator = entry.getValue();
pathProperties.pathProperties.add(new PathProperty(path, mutator));
if (!classes.contains(mutator.getType())
&& Types.mightContainsProperties(mutator.getType()))
propertyStack.push(new Property(path, TypeInfoRegistry.typeInfoFor(mutator.getType(), configuration)));
}
}
return pathProperties;
}
private static final class Property {
String prefix;
TypeInfo<?> typeInfo;
public Property(String prefix, TypeInfo<?> typeInfo) {
this.prefix = prefix;
this.typeInfo = typeInfo;
}
}
private static final class PathProperties {
List<PathProperty> pathProperties = new ArrayList<PathProperty>();
private void matchAndRemove(String path) {
int startIndex = 0;
int endIndex;
while ((endIndex = path.indexOf(".", startIndex)) != -1) {
String currentPath = path.substring(0, endIndex + 1);
Iterator<PathProperty> iterator = pathProperties.iterator();
while (iterator.hasNext())
if (iterator.next().path.equals(currentPath))
iterator.remove();
startIndex = endIndex + 1;
}
Iterator<PathProperty> iterator = pathProperties.iterator();
while (iterator.hasNext())
if (iterator.next().path.startsWith(path))
iterator.remove();
}
public List<PropertyInfo> get() {
List<PropertyInfo> mutators = new ArrayList<PropertyInfo>(pathProperties.size());
for (PathProperty pathProperty : pathProperties)
mutators.add(pathProperty.mutator);
return mutators;
}
}
private static final class PathProperty {
String path;
Mutator mutator;
private PathProperty(String path, Mutator mutator) {
this.path = path;
this.mutator = mutator;
}
}
}
| {
"content_hash": "ec606572fc22284be8c3d8aeb111f85d",
"timestamp": "",
"source": "github",
"line_count": 453,
"max_line_length": 117,
"avg_line_length": 31.23841059602649,
"alnum_prop": 0.6726026429227616,
"repo_name": "jhalterman/modelmapper",
"id": "24c8559c8400893358919cf1d967866710f2e313",
"size": "14780",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/modelmapper/internal/TypeMapImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "500"
},
{
"name": "Java",
"bytes": "772560"
},
{
"name": "Shell",
"bytes": "235"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.google.zxing.client.result.ProductResultParser (ZXing 3.5.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.google.zxing.client.result.ProductResultParser (ZXing 3.5.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/google/zxing/client/result/ProductResultParser.html" title="class in com.google.zxing.client.result">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/zxing/client/result/class-use/ProductResultParser.html" target="_top">Frames</a></li>
<li><a href="ProductResultParser.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.google.zxing.client.result.ProductResultParser" class="title">Uses of Class<br>com.google.zxing.client.result.ProductResultParser</h2>
</div>
<div class="classUseContainer">No usage of com.google.zxing.client.result.ProductResultParser</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/google/zxing/client/result/ProductResultParser.html" title="class in com.google.zxing.client.result">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/zxing/client/result/class-use/ProductResultParser.html" target="_top">Frames</a></li>
<li><a href="ProductResultParser.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2007–2022. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "1e3c8944b420eacc61ae5b7f032f5e97",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 163,
"avg_line_length": 37.4,
"alnum_prop": 0.6160427807486631,
"repo_name": "shixingxing/zxing",
"id": "cdb68a07c391b7e584b707a64b49236d9439a80b",
"size": "4675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/apidocs/com/google/zxing/client/result/class-use/ProductResultParser.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3419"
},
{
"name": "HTML",
"bytes": "98646"
},
{
"name": "Java",
"bytes": "2590363"
}
],
"symlink_target": ""
} |
/* global WebPDecoder */
import { memoize } from 'lodash';
function loadImage(src) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
} else {
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
}
xhr.addEventListener('error', reject);
xhr.addEventListener('load', function () {
var binary = xhr.responseText.split('').map(function (e) {
return String.fromCharCode(e.charCodeAt(0) & 0xff);
}).join('');
resolve(binary);
});
xhr.open('GET', src);
xhr.send();
});
}
function binaryToArray(binary) {
var result = new Array();
for (var i = 0; i < binary.length; i++) {
result.push(binary.charCodeAt(i));
}
return result;
}
function convertWebPText(data) {
var buff = binaryToArray(data);
var decoder = new WebPDecoder();
var config = decoder.WebPDecoderConfig;
var output_buffer = config.j;
var bitstream = config.input;
if (!decoder.WebPInitDecoderConfig(config)) {
throw new Error('Library version mismatch!');
}
var status = decoder.WebPGetFeatures(buff, buff.length, bitstream);
if (status !== 0) {
throw new Error('Unable to decode webp image!', status);
}
output_buffer.J = 4;
status = decoder.WebPDecode(buff, buff.length, config);
if (status != 0) {
throw new Error('WebP decoding failed.', status);
}
return {
bitmap: output_buffer.c.RGBA.ma,
height: output_buffer.height,
width: output_buffer.width
};
}
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
function convertWebPToPNG(src) {
return loadImage(src).then(function (data) {
const webp = convertWebPText(data);
canvas.height = webp.height;
canvas.width = webp.width;
var output = context.createImageData(canvas.width, canvas.height);
var outputData = output.data;
for (var h = 0; h < webp.height; h++) {
for (var w = 0; w < webp.width; w++) {
outputData[0 + w * 4 + webp.width * 4 * h] = webp.bitmap[1 + w * 4 + webp.width * 4 * h];
outputData[1 + w * 4 + webp.width * 4 * h] = webp.bitmap[2 + w * 4 + webp.width * 4 * h];
outputData[2 + w * 4 + webp.width * 4 * h] = webp.bitmap[3 + w * 4 + webp.width * 4 * h];
outputData[3 + w * 4 + webp.width * 4 * h] = webp.bitmap[0 + w * 4 + webp.width * 4 * h];
}
}
context.putImageData(output, 0, 0);
return canvas.toDataURL();
})
}
const isWebPSupported = new Promise((resolve) => {
var image = new Image();
image.onload = () => resolve(image.width === 2 && image.height === 1);
image.onerror = () => resolve(false);
image.src = 'data:image/webp;base64,UklGRjIAAABXRUJQVlA4ICYAAACyAgCdASoCAAEALmk0mk0iIiIiIgBoSygABc6zbAAA/v56QAAAAA==';
}).then((isSupported) => {
if (isSupported) {
return true;
}
return new Promise((resolve) => {
require.ensure(['../vendor/libwebp-0.2.0.min'], (require) => {
require('../vendor/libwebp-0.2.0.min');
resolve(false);
});
});
})
function convertImage(src) {
return isWebPSupported.then((isSupported) => {
if (isSupported || !/\.webp\?/.test(src)) {
return src;
}
return convertWebPToPNG(src);
});
}
export default memoize(convertImage);
| {
"content_hash": "56838cc38c7eafeba48de4fb313c760b",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 120,
"avg_line_length": 27.916666666666668,
"alnum_prop": 0.6235820895522388,
"repo_name": "EaglesoftZJ/iGem_Web",
"id": "60a501b6441d8afb69d0289d7b54b053510adfdf",
"size": "3350",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/utils/convertImage.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "175789"
},
{
"name": "HTML",
"bytes": "808"
},
{
"name": "JavaScript",
"bytes": "1965824"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using Mono.Math;
using MonoTorrent.BEncoding;
using System.Net;
using MonoTorrent.Dht.Messages;
using System.Text;
namespace MonoTorrent.Dht
{
internal class Node : IComparable<Node>, IEquatable<Node>
{
public static readonly int MaxFailures = 4;
IPEndPoint endpoint;
NodeId id;
int failedCount;
DateTime lastSeen;
BEncodedString token;
public IPEndPoint EndPoint
{
get { return endpoint; }
}
public int FailedCount
{
get { return failedCount; }
internal set { failedCount = value; }
}
public NodeId Id
{
get { return id; }
}
public DateTime LastSeen
{
get { return lastSeen; }
internal set { lastSeen = value; }
}
// FIXME: State should be set properly as per specification.
// i.e. it needs to take into account the 'LastSeen' property.
// and must take into account when a node does not send us messages etc
public NodeState State
{
get
{
if (failedCount >= MaxFailures)
return NodeState.Bad;
else if (lastSeen == DateTime.MinValue)
return NodeState.Unknown;
return (DateTime.UtcNow - lastSeen).TotalMinutes < 15 ? NodeState.Good : NodeState.Questionable;
}
}
public BEncodedString Token
{
get { return token; }
set { token = value; }
}
public Node(NodeId id, IPEndPoint endpoint)
{
this.endpoint = endpoint;
this.id = id;
}
internal void Seen()
{
failedCount = 0;
lastSeen = DateTime.UtcNow;
}
internal BEncodedString CompactPort()
{
byte[] buffer = new byte[6];
CompactPort(buffer, 0);
return buffer;
}
internal void CompactPort(byte[] buffer, int offset)
{
Message.Write(buffer, offset, endpoint.Address.GetAddressBytes());
Message.Write(buffer, offset + 4, (ushort)endpoint.Port);
}
internal static BEncodedString CompactPort(IList<Node> peers)
{
byte[] buffer = new byte[peers.Count * 6];
for (int i = 0; i < peers.Count; i++)
peers[i].CompactPort(buffer, i * 6);
return new BEncodedString(buffer);
}
internal BEncodedString CompactNode()
{
byte[] buffer = new byte[26];
CompactNode(buffer, 0);
return buffer;
}
private void CompactNode(byte[] buffer, int offset)
{
Message.Write(buffer, offset, id.Bytes);
CompactPort(buffer, offset + 20);
}
internal static BEncodedString CompactNode(IList<Node> nodes)
{
byte[] buffer = new byte[nodes.Count * 26];
for (int i = 0; i < nodes.Count; i++)
nodes[i].CompactNode(buffer, i * 26);
return new BEncodedString(buffer);
}
internal static Node FromCompactNode(byte[] buffer, int offset)
{
byte[] id = new byte[20];
Buffer.BlockCopy(buffer, offset, id, 0, 20);
IPAddress address = new IPAddress((uint)BitConverter.ToInt32(buffer, offset + 20));
int port = (int)(ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(buffer, offset + 24));
return new Node(new NodeId(id), new IPEndPoint(address, port));
}
internal static IEnumerable<Node> FromCompactNode(byte[] buffer)
{
for (int i = 0; (i + 26) <= buffer.Length; i += 26)
yield return FromCompactNode(buffer, i);
}
internal static IEnumerable<Node> FromCompactNode(BEncodedString nodes)
{
return FromCompactNode(nodes.TextBytes);
}
internal static IEnumerable<Node> FromCompactNode(BEncodedList nodes)
{
foreach(BEncodedValue node in nodes)
{
//bad format!
if (!(node is BEncodedList))
continue;
string host = string.Empty;
long port = 0;
foreach (BEncodedValue val in (BEncodedList)node)
{
if(val is BEncodedString)
host = ((BEncodedString)val).Text;
else if (val is BEncodedNumber)
port = ((BEncodedNumber)val).Number;
}
IPAddress address;
IPAddress.TryParse(host, out address);
//REM: bad design from bitcomet we do not have node id so create it...
//or use torrent infohash?
// Will messages from this node be discarded later on if the NodeId doesn't match?
if (address != null)
yield return new Node(NodeId.Create(), new IPEndPoint(address, (int)port));
}
}
//To order by last seen in bucket
public int CompareTo(Node other)
{
if (other == null)
return 1;
return lastSeen.CompareTo(other.lastSeen);
}
public override bool Equals(object obj)
{
return Equals(obj as Node);
}
public bool Equals(Node other)
{
if (other == null)
return false;
return id.Equals(other.id);
}
public override int GetHashCode()
{
return id.GetHashCode();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(48);
for (int i = 0; i < id.Bytes.Length; i++)
{
sb.Append(id.Bytes[i]);
sb.Append("-");
}
return sb.ToString(0, sb.Length - 1);
}
internal static IEnumerable<Node> CloserNodes(NodeId target, SortedList<NodeId, NodeId> currentNodes, IEnumerable<Node> newNodes, int maxNodes)
{
foreach (Node node in newNodes)
{
if (currentNodes.ContainsValue(node.Id))
continue;
NodeId distance = node.Id.Xor(target);
if (currentNodes.Count < maxNodes)
{
currentNodes.Add(distance, node.Id);
}
else if (distance < currentNodes.Keys[currentNodes.Count - 1])
{
currentNodes.RemoveAt(currentNodes.Count - 1);
currentNodes.Add(distance, node.Id);
}
else
{
continue;
}
yield return node;
}
}
}
}
#endif | {
"content_hash": "1061349fd98c5dd750cf923565073800",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 151,
"avg_line_length": 29.885593220338983,
"alnum_prop": 0.5146746065504041,
"repo_name": "dipeshc/BTDeploy",
"id": "be3905a77a571ef438632aeef966a67917970d1e",
"size": "8332",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "libs/monotorrent/src/MonoTorrent.Dht/Nodes/Node.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "250"
},
{
"name": "C#",
"bytes": "1714262"
}
],
"symlink_target": ""
} |
/**
* @author Yosuke Ota
* See LICENSE file in root directory for full license.
*/
'use strict'
module.exports = {
supported: '2.6.0',
createTemplateBodyVisitor (context) {
const sourceCode = context.getSourceCode()
/**
* Checks whether the given node can convert to the `slot`.
* @param {VAttribute} vSlotAttr node of `v-slot`
* @returns {boolean} `true` if the given node can convert to the `slot`
*/
function canConvertToSlot (vSlotAttr) {
if (vSlotAttr.parent.parent.name !== 'template') {
return false
}
return true
}
/**
* Convert to `slot` and `slot-scope`.
* @param {object} fixer fixer
* @param {VAttribute} vSlotAttr node of `v-slot`
* @returns {*} fix data
*/
function fixVSlotToSlot (fixer, vSlotAttr) {
const key = vSlotAttr.key
if (key.modifiers.length) {
// unknown modifiers
return null
}
const attrs = []
const argument = key.argument
if (argument) {
if (argument.type === 'VIdentifier') {
const name = argument.rawName
attrs.push(`slot="${name}"`)
} else if (argument.type === 'VExpressionContainer' && argument.expression) {
const expression = sourceCode.getText(argument.expression)
attrs.push(`:slot="${expression}"`)
} else {
// unknown or syntax error
return null
}
}
const scopedValueNode = vSlotAttr.value
if (scopedValueNode) {
attrs.push(
`slot-scope=${sourceCode.getText(scopedValueNode)}`
)
}
if (!attrs.length) {
attrs.push('slot') // useless
}
return fixer.replaceText(vSlotAttr, attrs.join(' '))
}
/**
* Reports `v-slot` node
* @param {VAttribute} vSlotAttr node of `v-slot`
* @returns {void}
*/
function reportVSlot (vSlotAttr) {
context.report({
node: vSlotAttr.key,
messageId: 'forbiddenVSlot',
// fix to use `slot` (downgrade)
fix: fixer => {
if (!canConvertToSlot(vSlotAttr)) {
return null
}
return fixVSlotToSlot(fixer, vSlotAttr)
}
})
}
return {
"VAttribute[directive=true][key.name.name='slot']": reportVSlot
}
}
}
| {
"content_hash": "36fc7a87ffd8d940cc7220a1f51d7377",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 85,
"avg_line_length": 28.02409638554217,
"alnum_prop": 0.5670679277730009,
"repo_name": "BigBoss424/portfolio",
"id": "17b1018a1fbbe8d36f775ed29a0c589ce3be2ec7",
"size": "2326",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v6/node_modules/eslint-plugin-vue/lib/rules/syntaxes/v-slot.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
'use strict';
var system = angular.module('service.utility', []);
system.factory('utilityService', function($http, $location, $rootScope, $modal, $timeout) {
return {
convertToHighChartDatePair : function(dates){
var result = [];
for(var i = 0; i < dates.length; i++){
var d = new Date(dates[i].date);
var d_utc = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
result.push([d_utc, dates[i].duration])
}
return result;
},
// Shows yes no modal box
yesNoModal : function(header, message, callback){
var modalInstance = $modal.open({
templateUrl: 'views/partial/modal.html',
controller: function ($scope, $modalInstance, header, message) {
$scope.header = header;
$scope.message = message;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
header: function () { return header; },
message: function () { return message; }
}
});
modalInstance.result.then(function () {
callback(true);
}, function () {
callback(false);
});
},
shuffle: function(array){
var shuffle = [];
// copy array
angular.copy(array, shuffle);
// shuffle elements
var i = shuffle.length;
while (--i) {
var j = Math.floor(Math.random() * (i + 1))
var temp = shuffle[i];
shuffle[i] = shuffle[j];
shuffle[j] = temp;
}
// return mixed array
return shuffle;
}
}
}); | {
"content_hash": "21aa07fa1bea4eab859778d85cbd0ff3",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 91,
"avg_line_length": 31.49230769230769,
"alnum_prop": 0.4396678065461651,
"repo_name": "Selmanh/smart-read",
"id": "a1022730c8ef5957f6c15581e35d04ebc28dcfbb",
"size": "2047",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "main-app/scripts/services/utility.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "204261"
},
{
"name": "HTML",
"bytes": "28370155"
},
{
"name": "JavaScript",
"bytes": "5549028"
},
{
"name": "PLSQL",
"bytes": "665"
}
],
"symlink_target": ""
} |
get '/contacts' do
user_contacts = user.contacts
if request.xhr?
request.xhr? erb :"contacts/_index", layout: false, locals: { contacts: user_contacts}
else
erb :"contacts/_index", locals: { contacts: user_contacts}
end
end
#----------- CREATE -----------
get '/contacts/new' do
erb :"contacts/_new"
end
post '/contacts' do
Contact.create(
name: params[:name],
phone_number: params[:phone_number],
user_id: user_id
)
redirect '/contacts'
end
#----------- SHOW -----------
get '/contacts/:id' do
@contact = Contact.find(params[:id])
erb :"contacts/_show", locals: { contact: @contact }
end
#----------- EDIT -----------
get '/contacts/:id/edit' do
@contact = Contact.find(params[:id])
erb :"contacts/_edit"
end
put '/contacts/:id' do
@contact = Contact.find(params[:id])
@contact.update_attributes(
name: params[:name],
phone_number: params[:phone_number]
)
redirect "/users/:user_id/contacts/#{@contact.id}"
end
#----------- DELETE -----------
delete '/contacts/:id' do
@contact = Contact.find(params[:id])
@contact.destroy
redirect "/contacts"
end
| {
"content_hash": "806904612c1197b3c8f1c775e1d67564",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 89,
"avg_line_length": 18.07936507936508,
"alnum_prop": 0.597892888498683,
"repo_name": "tisderek/cleansweep",
"id": "7c842a8757565f70e541ef9749ddbdabc5370369",
"size": "1178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/contacts_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1454151"
},
{
"name": "HTML",
"bytes": "27744"
},
{
"name": "JavaScript",
"bytes": "1457256"
},
{
"name": "Ruby",
"bytes": "28958"
}
],
"symlink_target": ""
} |
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::ifstream in(argv[i]);
in.seekg(0, in.end);
size_t length = in.tellg();
in.seekg (0, in.beg);
std::cout << "Reading " << length << " bytes from " << argv[i] << std::endl;
// Allocate exactly length bytes so that we reliably catch buffer overflows.
std::vector<char> bytes(length);
in.read(bytes.data(), bytes.size());
assert(in);
LLVMFuzzerTestOneInput(reinterpret_cast<const uint8_t *>(bytes.data()),
bytes.size());
std::cout << "Execution successful" << std::endl;
}
}
| {
"content_hash": "b8742e10be82c1906ef97a0fa05864cc",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 80,
"avg_line_length": 38.388888888888886,
"alnum_prop": 0.5962373371924746,
"repo_name": "frolv/bloaty",
"id": "2e286d47a49202cda1fff3c34f4112f7478a9c3b",
"size": "1378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/fuzz_driver.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "385141"
},
{
"name": "CMake",
"bytes": "10333"
},
{
"name": "Python",
"bytes": "695"
},
{
"name": "Shell",
"bytes": "1174"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.pentaho.di.plugins</groupId>
<artifactId>get-previous-row-field</artifactId>
<version>9.0.0.0-423</version>
</parent>
<artifactId>get-previous-row-field-core</artifactId>
<version>9.0.0.0-423</version>
<packaging>jar</packaging>
<name>PDI Get Previous Row Field Plugin Core</name>
<dependencies>
<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-engine</artifactId>
</dependency>
<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-core</artifactId>
</dependency>
<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-ui-swt</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>jface</artifactId>
<version>3.3.0-I20070606-0010</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
</project>
| {
"content_hash": "e874867c352a2515541de182d34aebf8",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 107,
"avg_line_length": 31.085106382978722,
"alnum_prop": 0.6625598904859685,
"repo_name": "HiromuHota/pentaho-kettle",
"id": "671677f5330592bb0abf9ca7053bafc9fb0f1b34",
"size": "1461",
"binary": false,
"copies": "1",
"ref": "refs/heads/webspoon-9.0",
"path": "plugins/get-previous-row-field/core/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "43059"
},
{
"name": "CSS",
"bytes": "100264"
},
{
"name": "Dockerfile",
"bytes": "1725"
},
{
"name": "GAP",
"bytes": "4005"
},
{
"name": "HTML",
"bytes": "91226"
},
{
"name": "Java",
"bytes": "44226693"
},
{
"name": "JavaScript",
"bytes": "939870"
},
{
"name": "Shell",
"bytes": "51612"
}
],
"symlink_target": ""
} |
package edu.uci.ics.asterix.runtime.aggregates.std;
import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
import edu.uci.ics.asterix.runtime.aggregates.base.AbstractAggregateFunctionDynamicDescriptor;
import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyAggregateFunction;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyAggregateFunctionFactory;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;
public class IntermediateAvgAggregateDescriptor extends AbstractAggregateFunctionDynamicDescriptor {
private static final long serialVersionUID = 1L;
public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
public IFunctionDescriptor createFunctionDescriptor() {
return new IntermediateAvgAggregateDescriptor();
}
};
@Override
public FunctionIdentifier getIdentifier() {
return AsterixBuiltinFunctions.INTERMEDIATE_AVG;
}
@Override
public ICopyAggregateFunctionFactory createAggregateFunctionFactory(final ICopyEvaluatorFactory[] args)
throws AlgebricksException {
return new ICopyAggregateFunctionFactory() {
private static final long serialVersionUID = 1L;
@Override
public ICopyAggregateFunction createAggregateFunction(final IDataOutputProvider provider)
throws AlgebricksException {
return new IntermediateAvgAggregateFunction(args, provider);
}
};
}
}
| {
"content_hash": "07a881a83b915a8934725bf6e28c26f0",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 107,
"avg_line_length": 41.733333333333334,
"alnum_prop": 0.7736954206602769,
"repo_name": "sjaco002/incubator-asterixdb",
"id": "5ec5c25df8c94c34ab5ff3f7fd5f3df34f1a37c9",
"size": "2513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/aggregates/std/IntermediateAvgAggregateDescriptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3954"
},
{
"name": "HTML",
"bytes": "69593"
},
{
"name": "Java",
"bytes": "7985438"
},
{
"name": "JavaScript",
"bytes": "232059"
},
{
"name": "Python",
"bytes": "264407"
},
{
"name": "Ruby",
"bytes": "1880"
},
{
"name": "Scheme",
"bytes": "1105"
},
{
"name": "Shell",
"bytes": "76117"
},
{
"name": "Smarty",
"bytes": "29789"
}
],
"symlink_target": ""
} |
struct AutocompleteMatch;
class OmniboxEditModel;
class OmniboxResultView;
class OmniboxView;
class Profile;
namespace views {
class BubbleBorder;
}
// A view representing the contents of the autocomplete popup.
class OmniboxPopupContentsView : public views::View,
public OmniboxResultViewModel,
public OmniboxPopupView,
public ui::AnimationDelegate {
public:
// Factory method for creating the AutocompletePopupView.
static OmniboxPopupView* Create(const gfx::Font& font,
OmniboxView* omnibox_view,
OmniboxEditModel* edit_model,
views::View* location_bar);
// Returns the bounds the popup should be shown at. This is the display bounds
// and includes offsets for the dropshadow which this view's border renders.
gfx::Rect GetPopupBounds() const;
virtual void LayoutChildren();
// Overridden from OmniboxPopupView:
virtual bool IsOpen() const OVERRIDE;
virtual void InvalidateLine(size_t line) OVERRIDE;
virtual void UpdatePopupAppearance() OVERRIDE;
virtual gfx::Rect GetTargetBounds() OVERRIDE;
virtual void PaintUpdatesNow() OVERRIDE;
virtual void OnDragCanceled() OVERRIDE;
// Overridden from OmniboxResultViewModel:
virtual bool IsSelectedIndex(size_t index) const OVERRIDE;
virtual bool IsHoveredIndex(size_t index) const OVERRIDE;
virtual gfx::Image GetIconIfExtensionMatch(size_t index) const OVERRIDE;
// Overridden from ui::AnimationDelegate:
virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE;
// Overridden from views::View:
virtual void Layout() OVERRIDE;
virtual views::View* GetEventHandlerForPoint(
const gfx::Point& point) OVERRIDE;
virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE;
virtual bool OnMouseDragged(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseCaptureLost() OVERRIDE;
virtual void OnMouseMoved(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE;
virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE;
// Overridden from ui::EventHandler:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
protected:
OmniboxPopupContentsView(const gfx::Font& font,
OmniboxView* omnibox_view,
OmniboxEditModel* edit_model,
views::View* location_bar);
virtual ~OmniboxPopupContentsView();
virtual void PaintResultViews(gfx::Canvas* canvas);
// Calculates the height needed to show all the results in the model.
virtual int CalculatePopupHeight();
virtual OmniboxResultView* CreateResultView(
OmniboxResultViewModel* model,
int model_index,
const gfx::Font& font,
const gfx::Font& bold_font);
// Overridden from views::View:
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
// This method should not be triggered directly as we paint our children
// in an un-conventional way inside OnPaint. We use a separate canvas to
// paint the children. Hence we override this method to a no-op so that
// the view hierarchy does not "accidentally" trigger this.
virtual void PaintChildren(gfx::Canvas* canvas) OVERRIDE;
scoped_ptr<OmniboxPopupModel> model_;
private:
class AutocompletePopupWidget;
// Call immediately after construction.
void Init();
// Returns true if the model has a match at the specified index.
bool HasMatchAt(size_t index) const;
// Returns the match at the specified index within the popup model.
const AutocompleteMatch& GetMatchAtIndex(size_t index) const;
// Fill a path for the contents' roundrect. |bounding_rect| is the rect that
// bounds the path.
void MakeContentsPath(gfx::Path* path, const gfx::Rect& bounding_rect);
// Updates the window's blur region for the current size.
void UpdateBlurRegion();
// Makes the contents of the canvas slightly transparent.
void MakeCanvasTransparent(gfx::Canvas* canvas);
// Called when the line at the specified index should be opened with the
// provided disposition.
void OpenIndex(size_t index, WindowOpenDisposition disposition);
// Find the index of the match under the given |point|, specified in window
// coordinates. Returns OmniboxPopupModel::kNoMatch if there isn't a match at
// the specified point.
size_t GetIndexForPoint(const gfx::Point& point);
// Processes a located event (e.g. mouse/gesture) and sets the selection/hover
// state of a line in the list.
void UpdateLineEvent(const ui::LocatedEvent& event,
bool should_set_selected_line);
// Opens an entry from the list depending on the event and the selected
// disposition.
void OpenSelectedLine(const ui::LocatedEvent& event,
WindowOpenDisposition disposition);
// Returns the target bounds given the specified content height.
gfx::Rect CalculateTargetBounds(int h);
OmniboxResultView* result_view_at(size_t i);
// The popup that contains this view. We create this, but it deletes itself
// when its window is destroyed. This is a WeakPtr because it's possible for
// the OS to destroy the window and thus delete this object before we're
// deleted, or without our knowledge.
base::WeakPtr<AutocompletePopupWidget> popup_;
// The edit view that invokes us.
OmniboxView* omnibox_view_;
Profile* profile_;
// An object that the popup positions itself against.
views::View* location_bar_;
// Our border, which can compute our desired bounds.
const views::BubbleBorder* bubble_border_;
// The font that we should use for result rows. This is based on the font used
// by the edit that created us.
gfx::Font result_font_;
// The font used for portions that match the input.
gfx::Font result_bold_font_;
// If the user cancels a dragging action (i.e. by pressing ESC), we don't have
// a convenient way to release mouse capture. Instead we use this flag to
// simply ignore all remaining drag events, and the eventual mouse release
// event. Since OnDragCanceled() can be called when we're not dragging, this
// flag is reset to false on a mouse pressed event, to make sure we don't
// erroneously ignore the next drag.
bool ignore_mouse_drag_;
// The popup sizes vertically using an animation when the popup is getting
// shorter (not larger, that makes it look "slow").
ui::SlideAnimation size_animation_;
gfx::Rect start_bounds_;
gfx::Rect target_bounds_;
DISALLOW_COPY_AND_ASSIGN(OmniboxPopupContentsView);
};
#endif // CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_POPUP_CONTENTS_VIEW_H_
| {
"content_hash": "507b93fd57e54712466f31dbd2542da5",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 80,
"avg_line_length": 39.304597701149426,
"alnum_prop": 0.7179412194765317,
"repo_name": "leiferikb/bitpop-private",
"id": "67d5018611f2fc86af0a774649311a9227387878",
"size": "7573",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1871"
},
{
"name": "C",
"bytes": "1800028"
},
{
"name": "C++",
"bytes": "76499582"
},
{
"name": "CSS",
"bytes": "803682"
},
{
"name": "Java",
"bytes": "1234788"
},
{
"name": "JavaScript",
"bytes": "21793252"
},
{
"name": "Objective-C",
"bytes": "5358744"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "64410"
},
{
"name": "Python",
"bytes": "3017857"
},
{
"name": "Ruby",
"bytes": "650"
},
{
"name": "Shell",
"bytes": "322362"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "12138"
}
],
"symlink_target": ""
} |
var express = require('express');
var copier = require('./vid-copier');
var cors = require('cors');
var app = express();
app.use(cors());
app.get('/video', function(req, res){
var info = req.query;
console.log('recieved POST VIDEO');
res.send('recieved Command')
copier.start(info);
});
app.listen(3000);
| {
"content_hash": "80aba052e74a625aa65dd91ac2e22692",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 37,
"avg_line_length": 18.705882352941178,
"alnum_prop": 0.6509433962264151,
"repo_name": "StefanWerW/y-make",
"id": "e90b1fde7607e4c7c622786aa0c716e5052bfb28",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21543"
}
],
"symlink_target": ""
} |
if [ -z "$1" ]; then
echo -e "\033[0;31mUsage:\033[0m $0 (major|minor|patch)\033[0m"
echo -e "\033[4;32mCurrent version\033[0m:\033[0m \033[33m`git describe master`\033[0m"
exit -1
fi
# increment version depending on passed parameter
case "$1" in
major)
currentVersion=`git describe master`
bumpedVersion=`echo $currentVersion | ( IFS=".$IFS" ; read a b c && echo $((a + 1)).0.0 )`
;;
minor)
currentVersion=`git describe master`
bumpedVersion=`echo $currentVersion | ( IFS=".$IFS" ; read a b c && echo $a.$((b + 1)).0 )`
;;
patch)
currentVersion=`git describe master`
bumpedVersion=`echo $currentVersion | ( IFS=".$IFS" ; read a b c && echo $a.$b.$((c + 1)) )`
;;
*)
echo -e "\033[0;31mUsage:\033[0m $0 (major|minor|patch)\033[0m"
echo -e "\033[4;32mCurrent version\033[0m:\033[0m \033[33m`git describe master`\033[0m"
exit -1
esac
# let's start a new release
git flow release start $bumpedVersion
# bump version in all files
for file in `find . -path ./coverage -prune -o -path ./.git -prune -o -type f`
do
filename=$(basename "$file")
ext="${filename##*.}"
if [ $ext != "png" -a $ext != "jpg" -a $ext != "jpeg" -a $ext != "gif" ]; then
if [ $ext != "DS_Store" -a $ext != "ttf" -a $ext != "node_modules" -a $ext != "git" ]; then
sed -i '' "s/GIT: $currentVersion/GIT: $bumpedVersion/g" $file
fi
fi
done
# bump version in package.json
sed -i '' "s/\"version\": \"$currentVersion\"/\"version\": \"$bumpedVersion\"/g" package.json
# add changed files to git
git add . && git commit -m "Bumped version from $currentVersion to $bumpedVersion"
# finish the release
git flow release finish -F -m "$bumpedVersion" $bumpedVersion
# publish develop branch
git checkout develop && git push origin develop
# publish master
git checkout master && git push origin master
# publish tags
git push origin --tags
# Announce the result
echo -e "\033[4;32mSuccessfully released\033[0m:\033[0m \033[33m$bumpedVersion\033[0m"
| {
"content_hash": "1a3cbe7a121c925aa1bc07107245da05",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 96,
"avg_line_length": 32.77049180327869,
"alnum_prop": 0.6413206603301651,
"repo_name": "yani-/mysqldump-factory",
"id": "2b8e72ada879debe821798d6e25dc00bffb2d844",
"size": "2012",
"binary": false,
"copies": "24",
"ref": "refs/heads/master",
"path": "bump_version.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "83139"
},
{
"name": "Shell",
"bytes": "2012"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b91f4f3ce475807e78aefeb4cd0293f4",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "971447da35548acafdd12f5e87dc6dd66dd5949d",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Acourtia moschata/ Syn. Acourtia thyrsoidea/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import re
import subprocess
import os
import sys
sys.path.append('/home/pi/www/py')
from genfunctions import *
availStorage = getAvailStorage()
wifistate = getWlanState()
imagecount = getImgCount()
movcount = getMovCount()
mailstatus = getMailstatus()
currentvolume= getVolume()
currentslideduration=getSlideduration()
wpassid=getWpaSSID()
wpapsk=getWpaPSK()
mailserver=getMailserver()
mailuname=getMailUsername()
mailpwd=getMailPassword()
mailretrieveinterval=getEmailInterval()
pmgtenabled=""
if getPowerMgtEnabled()=="enabled":
pmgtenabled="checked"
currentmailretrieveinterval=getEmailInterval()
shutdownmin=getShutdownMinute()
shutdownhour=getShutdownHour()
# Volume levels
volume = 0
volhtml=""
selected=""
while volume >= -60:
if volume == currentvolume:
volhtml = volhtml + "<option SELECTED value=\"" + str(volume) + "\">" + str(volume) + "dB</option>"
else:
volhtml = volhtml + "<option value=\"" + str(volume) + "\">" + str(volume) + "dB</option>"
volume=volume-5
# Slide interval duration
slideduration=5
slidehtml=""
while slideduration <= 60:
if slideduration == currentslideduration:
slidehtml = slidehtml + "<option SELECTED value=\"" + str(slideduration) + "\">" + str(slideduration) + " sec.</option>"
else:
slidehtml = slidehtml + "<option value=\"" + str(slideduration) + "\">" + str(slideduration) + " sec.</option>"
slideduration=slideduration+5
## get wifi adapter status
wifienabled=""
if wifistate != "down":
wifienabled = "checked"
## get wifi ssids
ssidset = set()
ssids = ""
df = subprocess.Popen(["sudo", "/sbin/iwlist", "wlan0", "scan"], stdout=subprocess.PIPE)
output = df.communicate()[0]
splitoutput=output.split("\n")
c=0
while c < len(splitoutput):
searchresult = re.search("^.*ESSID:\"(.*)\".*", splitoutput[c])
if searchresult:
ssidset.update([searchresult.group(1)])
c=c+1
for ssid in ssidset:
if ssid == wpassid:
ssids = ssids + "<option SELECTED value=\"" + ssid + "\">" + ssid + "</option>"
else:
ssids = ssids + "<option value=\"" + ssid + "\">" + ssid + "</option>"
## Mail retrieve intervals
mailretrieveintervals=""
mailint=5
while mailint <= 55:
if str(mailint) == currentmailretrieveinterval:
mailretrieveintervals= mailretrieveintervals + "<option SELECTED value=\"" + str(mailint) + "\">" + str(mailint) + " min.</option>"
else:
mailretrieveintervals = mailretrieveintervals + "<option value=\"" + str(mailint) + "\">" + str(mailint) + " min.</option>"
mailint = mailint + 5
## shutdown time minutes
shutmin=0
shutdownminoption=""
while shutmin <= 55:
if shutmin == int(shutdownmin):
shutdownminoption = shutdownminoption+ "<option SELECTED value=\"" + str(shutmin) + "\">" + str(shutmin) + "</option>"
else:
shutdownminoption= shutdownminoption+ "<option value=\"" + str(shutmin) + "\">" + str(shutmin) + "</option>"
shutmin=shutmin+5
## shudown time hours
shuthour=0
shutdownhouroption=""
while shuthour <= 23:
if shuthour == int(shutdownhour):
shutdownhouroption = shutdownhouroption+ "<option SELECTED value=\"" + str(shuthour) + "\">" + str(shuthour) + "</option>"
else:
shutdownhouroption= shutdownhouroption+ "<option value=\"" + str(shuthour) + "\">" + str(shuthour) + "</option>"
shuthour=shuthour+1
## Generate HTML
f = open('../stz/index.stz', 'r')
for line in f:
line = re.sub(r'\[\[-STORAGE-\]\]', availStorage, line)
line = re.sub(r'\[\[-WIFISTATE-\]\]', wifistate, line)
line = re.sub(r'\[\[-IMGCOUNT-\]\]', str(imagecount), line)
line = re.sub(r'\[\[-MOVCOUNT-\]\]', str(movcount), line)
line = re.sub(r'\[\[-AUDIOVOLUME-\]\]', volhtml, line)
line = re.sub(r'\[\[-SLIDEDURATION-\]\]', slidehtml, line)
line = re.sub(r'\[\[-SSIDS-\]\]', ssids, line)
line = re.sub(r'\[\[-WPAPSK-\]\]', wpapsk, line)
line = re.sub(r'\[\[-WIFIENABLED-\]\]', wifienabled, line)
line = re.sub(r'\[\[-MAILINTERVAL-\]\]', mailretrieveintervals, line)
line = re.sub(r'\[\[-MAILSERVER-\]\]', mailserver, line)
line = re.sub(r'\[\[-MAILUNAME-\]\]', mailuname, line)
line = re.sub(r'\[\[-MAILPWD-\]\]', mailpwd, line)
line = re.sub(r'\[\[-MAILSTATUS-\]\]', mailstatus, line)
line = re.sub(r'\[\[-PMENABLED-\]\]', pmgtenabled, line)
line = re.sub(r'\[\[-SHUTDOWNH-\]\]', shutdownhouroption, line)
line = re.sub(r'\[\[-SHUTDOWNM-\]\]', shutdownminoption, line)
print line
f.close()
| {
"content_hash": "9d8b5de75296b8785a6171c0892a0f30",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 139,
"avg_line_length": 33.553030303030305,
"alnum_prop": 0.6477760216753218,
"repo_name": "reddipped/PIChannel",
"id": "727c1fed767ee0d39b0df28ab9344f7b93f17480",
"size": "4453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/www/http/index.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1135"
},
{
"name": "JavaScript",
"bytes": "10026"
},
{
"name": "Python",
"bytes": "17218"
},
{
"name": "Shell",
"bytes": "21487"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>archives: 2016/6 | DreamOps Success Group</title>
<meta name="author" content="DreamOps Crew">
<meta name="description" content="Force.com is a remarkable platform, and we want to help take it to the next level. We have a dream. We want Salesforce DX to be the most scalable, most agile, most developer-friendly platform on the planet -- or in the cloud -- bar none.">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta property="og:site_name" content="DreamOps Success Group"/>
<meta property="og:image" content="undefined"/>
<link rel="alternative" href="/atom.xml" title="DreamOps Success Group" type="application/atom+xml">
<link href="/favicon.ico" rel="icon">
<!-- CSS -->
<link rel="stylesheet" href="/css/themes/bootstrap.css" media="screen" type="text/css">
<link rel="stylesheet" href="/css/font-awesome.css" media="screen" type="text/css">
<link rel="stylesheet" href="/css/style.css" media="screen" type="text/css">
<link rel="stylesheet" href="/css/responsive.css" media="screen" type="text/css">
<link rel="stylesheet" href="/css/highlight.css" media="screen" type="text/css">
<link rel="stylesheet" href="/css/google-fonts.css" media="screen" type="text/css">
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script src="/js/jquery-2.0.3.min.js"></script>
<!-- analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-92989768-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<nav id="main-nav" class="navbar navbar-inverse navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<button type="button" class="navbar-header navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">DreamOps Success Group</a>
<div class="collapse navbar-collapse nav-menu">
<ul class="nav navbar-nav">
<li>
<a href="/archives" title="All the articles.">
<i class="fa fa-archive"></i>archives
</a>
</li>
<li>
<a href="/categories" title="All the categories.">
<i class="fa fa-folder"></i>categories
</a>
</li>
<li>
<a href="/tags" title="All the tags.">
<i class="fa fa-tags"></i>tags
</a>
</li>
<li>
<a href="/about" title="More about DreamOps.">
<i class="fa fa-user"></i>about
</a>
</li>
</ul>
</div>
</div> <!-- container -->
</nav>
<div class="clearfix"></div>
<div class="container">
<div class="content">
<!-- title -->
<div class="page-header page-header-inverse ">
<h1 class="archive-title title title-inverse ">2016/6</h1>
</div>
<div class="row page">
<!-- cols -->
<div class="col-md-9">
<div id="top_search"></div>
<div class="archive">
<h4 class="archive-ul" data-toggle="collapse" data-target="#2017">2017<b class="caret"></b></h4>
<ul id="2017" class="collapse in">
<li class="listing-item">
<span class="date_class"> 2017-05-28 </span> »
<span class="title"><a href="/2017/05/28/lightning-component-dev-tips/" >Lightning Component Dev Tips</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-27 </span> »
<span class="title"><a href="/2017/05/27/creating-a-jira-change-log-in-confluence/" >Creating a JIRA Change Log in Confluence</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-23 </span> »
<span class="title"><a href="/2017/05/23/introducing-slackforce-a-salesforce-slack-community/" >Introducing Slackforce: A Salesforce Slack Community</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-22 </span> »
<span class="title"><a href="/2017/05/22/updating-multiple-sites-from-jenkins/" >Updating Multiple Sites from Jenkins</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-17 </span> »
<span class="title"><a href="/2017/05/17/free-debugger-for-unlimited-edition/" >Free Debugger for Unlimited Edition</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-16 </span> »
<span class="title"><a href="/2017/05/16/build-better-communities-with-lightning/" >Build Better Communities with Lightning</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-05-06 </span> »
<span class="title"><a href="/2017/05/06/selenium-and-salesforcedx-scratch-orgs/" >Selenium and SalesforceDX Scratch Orgs</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-29 </span> »
<span class="title"><a href="/2017/04/29/locker-service-in-summer-17/" >Locker Service in Summer 17</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-28 </span> »
<span class="title"><a href="/2017/04/28/leveraging-use-case-diagrams-in-smoke-testing/" >Leveraging Use Case Diagrams in Smoke Testing</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-13 </span> »
<span class="title"><a href="/2017/04/13/introducing-the-nimbleuser-salesforce-apex-style-guide/" >Introducing the NimbleUser Salesforce Apex Style Guide</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-12 </span> »
<span class="title"><a href="/2017/04/12/machine-to-machine-salesforce-integrations-in-java-with-rest-and-soap/" >Machine-to-Machine Salesforce Integrations in Java with REST and SOAP</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-06 </span> »
<span class="title"><a href="/2017/04/06/salesforce-expands-partnership-with-girl-develop-it—get-involved/" >Salesforce Expands Partnership with Girl Develop It—Get Involved!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-04-01 </span> »
<span class="title"><a href="/2017/04/01/now-salesforce-can-even-read-your-mind/" >Now, Salesforce can even read your mind</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-27 </span> »
<span class="title"><a href="/2017/03/27/ultimate-salesforce-chrome-extensions-2017/" >Ultimate Salesforce Chrome Extensions 2017</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-15 </span> »
<span class="title"><a href="/2017/03/15/building-lightning-components-with-chart-js/" >Building Lightning Components with Chart.js</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-13 </span> »
<span class="title"><a href="/2017/03/13/using-vlookup-validation-rules-in-salesforce/" >Using VLOOKUP Validation Rules in Salesforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-11 </span> »
<span class="title"><a href="/2017/03/11/top-open-source-projects/" >Top Open Source Projects</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-10 </span> »
<span class="title"><a href="/2017/03/10/design-build-publish-lighting-component-appexchange/" >How to Design, Build and Publish Your Lightning Component for AppExchange</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-10 </span> »
<span class="title"><a href="/2017/03/10/pilot-madness/" >Pilot Madness!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-05 </span> »
<span class="title"><a href="/2017/03/05/salesforce-dx-week-1/" >Salesforce DX Week 1</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-03-03 </span> »
<span class="title"><a href="/2017/03/03/tips-for-an-effective-architecture-review-board/" >Tips for an Effective Architecture Review Board</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-02-20 </span> »
<span class="title"><a href="/2017/02/20/what-is-salesforce-dx-and-what-does-it-mean-for-admins/" >What is Salesforce DX and what does it mean for Admins</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-02-19 </span> »
<span class="title"><a href="/2017/02/19/lightning-design-system-in-visualforce/" >Lightning Design System in Visualforce Part 2 - Forms</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-02-13 </span> »
<span class="title"><a href="/2017/02/13/secure-your-org-with-salesforce-health-check/" >Secure your Org with Salesforce Health Check</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-02-10 </span> »
<span class="title"><a href="/2017/02/10/10-ux-lightning-experience-need-fixing/" >10 UX Issues in Lightning Experience that Need Fixing</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-02-06 </span> »
<span class="title"><a href="/2017/02/06/the-thousand-developer-march-on-dx-ga/" >The Thousand Developer March on DX GA</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-01-31 </span> »
<span class="title"><a href="/2017/01/31/confluence-templates-for-all/" >Confluence Templates For All</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-01-29 </span> »
<span class="title"><a href="/2017/01/29/undertanding-how-your-app-experience-fits-into-lightning-experience/" >Understanding how your App Experience fits into Lightning Experience</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-01-17 </span> »
<span class="title"><a href="/2017/01/17/ant-sf-dx-for-the-rest-of-us/" >Ant-SF: DX for the rest of us</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2017-01-09 </span> »
<span class="title"><a href="/2017/01/09/hot-javascript-tips-visualforce-developers/" >Hot JavaScript tips for Visualforce Developers!</a></span>
</li>
</ul>
<h4 class="archive-ul" data-toggle="collapse" data-target="#2016">2016<b class="caret"></b></h4>
<ul id="2016" class="collapse in">
<li class="listing-item">
<span class="date_class"> 2016-12-30 </span> »
<span class="title"><a href="/2016/12/30/javascript-promises-in-lightning-components/" >JavaScript Promises in Lightning Components</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-12-08 </span> »
<span class="title"><a href="/2016/12/08/sample-application-with-ionic-2-and-salesforce/" >Sample Application with Ionic 2 and Salesforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-12-05 </span> »
<span class="title"><a href="/2016/12/05/implementing-material-design-in-salesforce/" >Implementing Material Design in Salesforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-11-20 </span> »
<span class="title"><a href="/2016/11/20/browse-the-dreamops-guide/" >Browse the DreamOps Guide</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-11-15 </span> »
<span class="title"><a href="/2016/11/15/jira-our-nexus-of-truth/" >JIRA: Our nexus of truth</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-10-25 </span> »
<span class="title"><a href="/2016/10/25/source-driven-development-huh-what/" >Source driven development - Huh? What?</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-10-20 </span> »
<span class="title"><a href="/2016/10/20/write-better-apex-with-codescan/" >Write Better Apex With CodeScan</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-10-18 </span> »
<span class="title"><a href="/2016/10/18/from-waterfall-to-pipeline-to-mobius-strip/" >From waterfall to pipeline to mobius strip</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-10-14 </span> »
<span class="title"><a href="/2016/10/14/visualforce-development-cookbook-second-edition/" >Visualforce Development Cookbook Second Edition</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-08-10 </span> »
<span class="title"><a href="/2016/08/10/quick-easy-etl-from-salesforce-to-mysql-with-workflow-heroku/" >Quick & Easy ETL from Salesforce to MySQL with Workflow & Heroku</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-07-25 </span> »
<span class="title"><a href="/2016/07/25/are-you-ready-for-lightning-find-out-in-less-than-5-minutes/" >Are you ready for Lightning? Find out in less than 5 minutes!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-07-19 </span> »
<span class="title"><a href="/2016/07/19/introducing-the-flow-factory/" >Introducing the Flow Factory</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-06-14 </span> »
<span class="title"><a href="/2016/06/14/machine-learning-on-heroku-with-predictionio/" >Machine Learning on Heroku with PredictionIO</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-06-01 </span> »
<span class="title"><a href="/2016/06/01/login-forensics-login-history-plus-for/" >Login Forensics: Login History plus for auditing user logins</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-05-25 </span> »
<span class="title"><a href="/2016/05/25/bitbucket-pipelines-beta/" >Bitbucket Pipelines (Beta)</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-03-17 </span> »
<span class="title"><a href="/2016/03/17/uploading-data-to-the-salesforce-wave-analytics-cloud/" >Uploading data to the Salesforce Wave Analytics Cloud</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-28 </span> »
<span class="title"><a href="/2016/02/28/dynamically-calling-flows-in-apex/" >Dynamically Calling Flows in Apex</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-25 </span> »
<span class="title"><a href="/2016/02/25/angular2-ionic2-salesforce/" >Building Customer-Facing Mobile Apps with Angular 2, Ionic 2, and Salesforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-22 </span> »
<span class="title"><a href="/2016/02/22/a-seriously-nimble-and-free-tool-that-every-salesforce-admin-needs/" >A Seriously Nimble (And Free) Tool That Every App Builder Needs</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-13 </span> »
<span class="title"><a href="/2016/02/13/visit-planet-dreamops/" >Visit Planet DreamOps</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-06 </span> »
<span class="title"><a href="/2016/02/06/pair-programming-with-salesforce-app-cloud/" >Pair Programming with Salesforce App Cloud</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-02-05 </span> »
<span class="title"><a href="/2016/02/05/spring-’16-–-developer-tidbits/" >Spring ’16 – Developer Tidbits</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2016-01-10 </span> »
<span class="title"><a href="/2016/01/10/apex-sharing-and-applying-to-apex-enterprise-patterns/" >Apex Sharing and applying to Apex Enterprise Patterns</a></span>
</li>
</ul>
<h4 class="archive-ul" data-toggle="collapse" data-target="#2015">2015<b class="caret"></b></h4>
<ul id="2015" class="collapse in">
<li class="listing-item">
<span class="date_class"> 2015-12-29 </span> »
<span class="title"><a href="/2015/12/29/lightning-everywhere/" >Lightning Everywhere</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-12-12 </span> »
<span class="title"><a href="/2015/12/12/visual-flow-with-list-view-and-related-list-buttons/" >Visual Flow with List View and Related List Buttons</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-11-23 </span> »
<span class="title"><a href="/2015/11/23/google-script-connection-to-salesforce-nimble-ams-via-oauth/" >Google Script Connection to Salesforce / Nimble AMS via OAUTH</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-10-29 </span> »
<span class="title"><a href="/2015/10/29/sobject-test-data-design-pattern/" >sObject Test Data Design Pattern</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-10-18 </span> »
<span class="title"><a href="/2015/10/18/setup-audit-trail-api-in-winter’16/" >Setup Audit Trail API in Winter’16</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-09-28 </span> »
<span class="title"><a href="/2015/09/28/designing-with-the-users-mind-in-mind/" >Designing with the Users in Mind</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-09-27 </span> »
<span class="title"><a href="/2015/09/27/using-task-lists-to-get-more-done-better/" >Using task lists to get more done better</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-06-08 </span> »
<span class="title"><a href="/2015/06/08/comparing-application-deployment-2005-vs-2015/" >Comparing Application Deployment: 2005 vs. 2015</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-04-19 </span> »
<span class="title"><a href="/2015/04/19/considerations-placing-validation-code-in-an-apex-triggers/" >Where to place Validation code in an Apex Trigger?</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-03-19 </span> »
<span class="title"><a href="/2015/03/19/unit-testing-apex-enterprise-patterns-and-apexmocks-part-2/" >Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 2</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-03-18 </span> »
<span class="title"><a href="/2015/03/18/17-sites-every-force-com-developer-should-bookmark/" >17 Sites Every Force.com Developer Should Bookmark</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-03-17 </span> »
<span class="title"><a href="/2015/03/17/dita-best-practices-use-the-maps-folks-use-the-maps/" >DITA Best Practices: Use the maps, folks. Use the maps.</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-03-01 </span> »
<span class="title"><a href="/2015/03/01/extending-lightning-process-builder-and-visual-workflow-with-apex/" >Extending Lightning Process Builder and Visual Workflow with Apex</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-02-24 </span> »
<span class="title"><a href="/2015/02/24/5-skills-salesforce-devs-need-for-2015/" >5 Skills Salesforce Devs Need for 2015</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-02-17 </span> »
<span class="title"><a href="/2015/02/17/if-programming-languages-were-beer/" >If Programming Languages Were Beer ...</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-01-20 </span> »
<span class="title"><a href="/2015/01/20/nuops-how-the-nimble-ams-sausages-are-made/" >NuOps: How the Nimble AMS Sausages are Made</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2015-01-14 </span> »
<span class="title"><a href="/2015/01/14/creating-assigning-and-checking-custom-permissions/" >Creating, Assigning and Checking Custom Permissions</a></span>
</li>
</ul>
<h4 class="archive-ul" data-toggle="collapse" data-target="#2014">2014<b class="caret"></b></h4>
<ul id="2014" class="collapse in">
<li class="listing-item">
<span class="date_class"> 2014-12-22 </span> »
<span class="title"><a href="/2014/12/22/permission-sets-and-packaging/" >Permission Sets and Packaging</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-11-03 </span> »
<span class="title"><a href="/2014/11/03/what-is-salesforce1-lightning/" >What is Salesforce1 Lightning?</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-10-26 </span> »
<span class="title"><a href="/2014/10/26/calling-flow-from-apex/" >Calling Flow from Apex</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-10-23 </span> »
<span class="title"><a href="/2014/10/23/salesforce-publisher-actions-101-solutions-to-common-problems/" >Salesforce Publisher Actions 101 - Solutions to Common Problems</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-10-21 </span> »
<span class="title"><a href="/2014/10/21/salesforce-developer-console-query-editor/" >Salesforce Developer Console Query Editor</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-09-27 </span> »
<span class="title"><a href="/2014/09/27/the-new-github-deploy-to-salesforce-button/" >The new GitHub Deploy to Salesforce Button!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-08-24 </span> »
<span class="title"><a href="/2014/08/24/customizing-salesforce-help/" >Customizing Salesforce Help</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-07-29 </span> »
<span class="title"><a href="/2014/07/29/post-install-apex-metadata-api-configuration-solved/" >Post Install Apex Metadata API Configuration Solved!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-07-29 </span> »
<span class="title"><a href="/2014/07/29/salesforce-com-new-open-source-releases/" >Salesforce.com’s New Open Source Releases – Part 3</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-07-22 </span> »
<span class="title"><a href="/2014/07/22/choosey-partners-choose-trialforce/" >Choosey partners choose Trialforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-04-24 </span> »
<span class="title"><a href="/2014/04/24/apex-metadata-api-and-spring’14-keys-to-the-kingdom/" >Apex Metadata API and Spring’14 : Keys to the Kingdom!</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-04-01 </span> »
<span class="title"><a href="/2014/04/01/mountain-top-servers-are-now-literally-in-the-clouds/" >Mountain-top servers are now literally in the clouds</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-03-23 </span> »
<span class="title"><a href="/2014/03/23/unit-testing-with-the-domain-layer/" >Unit Testing with the Domain Layer</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-03-07 </span> »
<span class="title"><a href="/2014/03/07/getting-started-with-chromecast-on-visualforce/" >Getting Started with Chromecast on Visualforce</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-02-19 </span> »
<span class="title"><a href="/2014/02/19/clicks-not-code-with-visual-flow-custom-buttons/" >Clicks not Code with Visual Flow Custom Buttons</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-02-12 </span> »
<span class="title"><a href="/2014/02/12/my-devops-take-aways/" >My DevOps Take Aways</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-01-19 </span> »
<span class="title"><a href="/2014/01/19/apex-testing-username-creation-best-practice/" >Apex Testing Username Creation Best Practice</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-01-07 </span> »
<span class="title"><a href="/2014/01/07/why-feature-branches-are-a-good-thing/" >Why feature branches are a good thing</a></span>
</li>
<li class="listing-item">
<span class="date_class"> 2014-01-05 </span> »
<span class="title"><a href="/2014/01/05/welcome-to-dreamops/" >Welcome to DreamOps</a></span>
</li>
</ul>
<h4 class="archive-ul" data-toggle="collapse" data-target="#2013">2013<b class="caret"></b></h4>
<ul id="2013" class="collapse in">
<li class="listing-item">
<span class="date_class"> 2013-04-15 </span> »
<span class="title"><a href="/2013/04/15/why-standard-profile-permissions-can-t-be-changed/" >Why 'Standard' Profile Permissions Can't Be Changed</a></span>
</li>
</ul>
</div>
</div> <!-- col-md-9/col-md-12 -->
<div class="col-md-3">
<div id="sidebar">
<div id="site_search">
<div class="form-group">
<input type="text" id="local-search-input" name="q" results="0" placeholder="Search" class="st-search-input st-default-search-input form-control"/>
</div>
<div id="local-search-result"></div>
</div>
<div class="widget">
<h4>Recent Posts</h4>
<ul class="entry list-unstyled">
<li>
<a href="/2017/05/28/lightning-component-dev-tips/" ><i class="fa fa-file-o"></i>Lightning Component Dev Tips</a>
</li>
<li>
<a href="/2017/05/27/creating-a-jira-change-log-in-confluence/" ><i class="fa fa-file-o"></i>Creating a JIRA Change Log ...</a>
</li>
<li>
<a href="/2017/05/23/introducing-slackforce-a-salesforce-slack-community/" ><i class="fa fa-file-o"></i>Introducing Slackforce: A S...</a>
</li>
<li>
<a href="/2017/05/22/updating-multiple-sites-from-jenkins/" ><i class="fa fa-file-o"></i>Updating Multiple Sites fro...</a>
</li>
<li>
<a href="/2017/05/17/free-debugger-for-unlimited-edition/" ><i class="fa fa-file-o"></i>Free Debugger for Unlimited...</a>
</li>
</ul>
</div>
<div class="widget">
<h4>Links</h4>
<ul class="blogroll list-unstyled">
<li><i class=""></i><a href="https://github.com/DreamOps/ant-sf" title="Ant SF (pilot)" target="_blank"]);">Migration Tool on steroids</a></li>
<li><i class=""></i><a href="http://www.dreamops.org/guide" title="Guide (beta)" target="_blank"]);">Guide to Continuous Delivery</a></li>
<li><i class=""></i><a href="http://www.dreamops.org/planet" title="Planet (feedly)" target="_blank"]);">Every SF blog in the known universe</a></li>
<li><i class=""></i><a href="http://www.dreamops.org/group" title="Success Group" target="_blank"]);">Chew the fat, geek to geek</a></li>
<li><i class=""></i><a href="http://www.dreamops.org/hub" title="Hub" target="_blank"]);">Show me the source</a></li>
<li><i class=""></i><a href="http://www.dreamops.org/wiki/index.html" title="Wiki" target="_blank"]);">Best Practice Articles</a></li>
<li><i class=""></i><a href="/roadmap/index.html" title="Roadmap" target="_blank"]);">Invent the Future</a></li>
</ul>
</div>
</div> <!-- sidebar -->
</div> <!-- col-md-3 -->
</div>
</div>
<div class="container-narrow">
<footer> <p><a href="http://www.dreamops.org/powered-by/index.html">DreamOps is made possible by Nimble AMS Engineering</a>.</p> </footer>
</div> <!-- container-narrow -->
<a id="gotop" href="#">
<span>▲</span>
</a>
<a href="/atom.xml"><img src="/images/rss.png"/></a>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/main.js"></script>
<script src="/js/search.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
$('.fancybox').fancybox();
})(jQuery);
</script>
<script type="text/javascript">
var search_path = "search.xml";
if (search_path.length == 0) {
search_path = "search.xml";
}
var path = "/" + search_path;
searchFunc(path, 'local-search-input', 'local-search-result');
</script>
</body>
</html>
| {
"content_hash": "7f4a31aa9fc5c4dd83b22fa964fe024e",
"timestamp": "",
"source": "github",
"line_count": 1087,
"max_line_length": 275,
"avg_line_length": 28.229070837166514,
"alnum_prop": 0.618901743522894,
"repo_name": "DreamOps/dreamops.github.io",
"id": "7e1d83331a303a96d0e672b0f0f6b0db333e39cd",
"size": "30713",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "archives/2016/06/index.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "2485097"
},
{
"name": "HTML",
"bytes": "3665693"
},
{
"name": "JavaScript",
"bytes": "10770"
}
],
"symlink_target": ""
} |
using System;
namespace Rawr.Elemental.Spells
{
public class ChainLightning : Spell, ILightningOverload
{
private int additionalTargets = 0;
private float loCoef, lightningSpellpower = 0f, lspCoef;
public ChainLightning() : base()
{
}
protected override void SetBaseValues()
{
base.SetBaseValues();
baseMinDamage = 973;
baseMaxDamage = 1111;
baseCastTime = 2f;
castTime = 2f;
spCoef = 2f / 3.5f;
lspCoef = spCoef;
loCoef = spCoef / 2f;
manaCost = 0.26f * Constants.BaseMana;
cooldown = 6f;
lightningSpellpower = 0f;
}
public override void Initialize(ISpellArgs args)
{
additionalTargets = args.AdditionalTargets;
// jumps
if (additionalTargets < 0)
additionalTargets = 0;
if (additionalTargets > 3)
additionalTargets = 3;
shortName = "CL" + (1 + additionalTargets);
if (!args.Talents.GlyphofChainLightning && additionalTargets > 2)
additionalTargets = 2;
totalCoef *= new float[] { 1f, 1.7f, 2.19f, 2.533f, 2.7731f }[additionalTargets];
manaCost *= 1f - .02f * args.Talents.Convection;
totalCoef += .01f * args.Talents.Concussion;
crit += .05f * args.Talents.CallOfThunder;
spCoef += .04f * args.Talents.Shamanism;
loCoef += .04f * args.Talents.Shamanism;
castTime -= .1f * args.Talents.LightningMastery;
cooldown -= new float[] { 0, .75f, 1.5f, 2.5f }[args.Talents.StormEarthAndFire];
crit += .01f * args.Talents.TidalMastery;
spellPower += args.Stats.SpellNatureDamageRating;
lightningSpellpower += args.Stats.LightningSpellPower;
totalCoef *= 1 + args.Stats.BonusNatureDamageMultiplier;
lightningOverload = args.Talents.LightningOverload;
base.Initialize(args);
}
public ChainLightning(ISpellArgs args)
: this()
{
Initialize(args);
}
public int AdditionalTargets
{
get { return additionalTargets; }
}
public static ChainLightning operator +(ChainLightning A, ChainLightning B)
{
ChainLightning C = (ChainLightning)A.MemberwiseClone();
add(A, B, C);
return C;
}
public static ChainLightning operator *(ChainLightning A, float b)
{
ChainLightning C = (ChainLightning)A.MemberwiseClone();
multiply(A, b, C);
return C;
}
private int lightningOverload = 0;
public override float CCCritChance
{
get { return Math.Min(1f, CritChance * (1f + AdditionalTargets) * (1f + LOChance())); }
}
public override float MinHit
{
get { return totalCoef * (baseMinDamage * baseCoef + spellPower * spCoef + lightningSpellpower * lspCoef); }
}
public override float MaxHit
{
get { return totalCoef * (baseMaxDamage * baseCoef + spellPower * spCoef + lightningSpellpower * lspCoef); }
}
public float LOChance()
{
return .11f * lightningOverload / 3f * (1 + AdditionalTargets);
}
public override float TotalDamage
{
get { return base.TotalDamage + LOChance() * LightningOverloadDamage(); }
}
public override float DirectDpS
{
get { return (AvgDamage + LOChance() * LightningOverloadDamage()) / CastTime; }
}
public float LightningOverloadDamage()
{
return totalCoef * ((baseMinDamage + baseMaxDamage) / 4f * baseCoef + spellPower * loCoef + lightningSpellpower * lspCoef) * (1 + CritChance * critModifier);
}
}
} | {
"content_hash": "fcd12f1cc57802d1be20c7fee9163111",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 169,
"avg_line_length": 33.03305785123967,
"alnum_prop": 0.5596697523142357,
"repo_name": "Alacant/Rawr-RG",
"id": "a7a406a1f05071b7a089491c5490641ea1fea616",
"size": "3997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rawr.Elemental/Spells/ChainLightning.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "3464"
},
{
"name": "C#",
"bytes": "12955708"
},
{
"name": "HTML",
"bytes": "3289"
},
{
"name": "JavaScript",
"bytes": "556553"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Wed Jul 09 15:05:41 CEST 2014 -->
<title>ExtendedList</title>
<meta name="date" content="2014-07-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ExtendedList";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../at/irian/ankor/viewmodel/watch/AbstractExtendedList.html" title="class in at.irian.ankor.viewmodel.watch"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedListWrapper.html" title="class in at.irian.ankor.viewmodel.watch"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?at/irian/ankor/viewmodel/watch/ExtendedList.html" target="_top">Frames</a></li>
<li><a href="ExtendedList.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">at.irian.ankor.viewmodel.watch</div>
<h2 title="Interface ExtendedList" class="title">Interface ExtendedList<E></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd>java.util.Collection<E>, java.lang.Iterable<E>, java.util.List<E></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../at/irian/ankor/viewmodel/watch/AbstractExtendedList.html" title="class in at.irian.ankor.viewmodel.watch">AbstractExtendedList</a>, <a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedListWrapper.html" title="class in at.irian.ankor.viewmodel.watch">ExtendedListWrapper</a>, <a href="../../../../../at/irian/ankor/viewmodel/watch/WatchedList.html" title="class in at.irian.ankor.viewmodel.watch">WatchedList</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">ExtendedList<E></span>
extends java.util.List<E></pre>
<div class="block"><code>List</code> interface extension, inspired by JavaFX <code>ObservableList</code></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#addAll(E...)">addAll</a></strong>(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#remove(int, int)">remove</a></strong>(int from,
int to)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#removeAll(E...)">removeAll</a></strong>(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#retainAll(E...)">retainAll</a></strong>(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#setAll(java.util.Collection)">setAll</a></strong>(java.util.Collection<? extends <a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>> col)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html#setAll(E...)">setAll</a></strong>(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.util.List">
<!-- -->
</a>
<h3>Methods inherited from interface java.util.List</h3>
<code>add, add, addAll, addAll, clear, contains, containsAll, equals, get, hashCode, indexOf, isEmpty, iterator, lastIndexOf, listIterator, listIterator, remove, remove, removeAll, retainAll, set, size, subList, toArray, toArray</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="addAll(java.lang.Object[])">
<!-- -->
</a><a name="addAll(E...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addAll</h4>
<pre>boolean addAll(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</pre>
</li>
</ul>
<a name="setAll(java.lang.Object[])">
<!-- -->
</a><a name="setAll(E...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAll</h4>
<pre>boolean setAll(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</pre>
</li>
</ul>
<a name="setAll(java.util.Collection)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAll</h4>
<pre>boolean setAll(java.util.Collection<? extends <a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>> col)</pre>
</li>
</ul>
<a name="removeAll(java.lang.Object[])">
<!-- -->
</a><a name="removeAll(E...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removeAll</h4>
<pre>boolean removeAll(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</pre>
</li>
</ul>
<a name="retainAll(java.lang.Object[])">
<!-- -->
</a><a name="retainAll(E...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>retainAll</h4>
<pre>boolean retainAll(<a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedList.html" title="type parameter in ExtendedList">E</a>... elements)</pre>
</li>
</ul>
<a name="remove(int, int)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>remove</h4>
<pre>void remove(int from,
int to)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../at/irian/ankor/viewmodel/watch/AbstractExtendedList.html" title="class in at.irian.ankor.viewmodel.watch"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../at/irian/ankor/viewmodel/watch/ExtendedListWrapper.html" title="class in at.irian.ankor.viewmodel.watch"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?at/irian/ankor/viewmodel/watch/ExtendedList.html" target="_top">Frames</a></li>
<li><a href="ExtendedList.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "17a825d7bc7b4944329163782ec440c1",
"timestamp": "",
"source": "github",
"line_count": 296,
"max_line_length": 455,
"avg_line_length": 39.01013513513514,
"alnum_prop": 0.6335844808175284,
"repo_name": "ankor-io/ankor-framework",
"id": "a8d02adf16cbeaaccf0b254839a0c071b0856311",
"size": "11547",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable",
"path": "website/ankorsite/static/javadoc/apidocs-0.3/at/irian/ankor/viewmodel/watch/ExtendedList.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "526"
},
{
"name": "C",
"bytes": "12173"
},
{
"name": "C#",
"bytes": "157078"
},
{
"name": "CSS",
"bytes": "10636"
},
{
"name": "CoffeeScript",
"bytes": "48194"
},
{
"name": "HTML",
"bytes": "17806"
},
{
"name": "Java",
"bytes": "751745"
},
{
"name": "JavaScript",
"bytes": "290740"
},
{
"name": "Makefile",
"bytes": "811"
},
{
"name": "Objective-C",
"bytes": "114772"
},
{
"name": "PowerShell",
"bytes": "3261"
},
{
"name": "Python",
"bytes": "17835"
},
{
"name": "Shell",
"bytes": "36"
}
],
"symlink_target": ""
} |
package de.textmining.nerdle.evaluation;
public enum QuestionType {
WHO, WHICH, WHERE, WHEN, HOW, WHOM, WHAT, WHY;
} | {
"content_hash": "86d5d26fd7e317494d744ef463be0903",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 50,
"avg_line_length": 17.571428571428573,
"alnum_prop": 0.7154471544715447,
"repo_name": "nerdle/nerdle",
"id": "2cbd3d7ce5aa016a37ca7e8024b6af8b1f3e0e6f",
"size": "768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nerdle-core/src/main/java/de/textmining/nerdle/evaluation/QuestionType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "148605"
},
{
"name": "Shell",
"bytes": "422"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ThermalViz.iml" filepath="$PROJECT_DIR$/ThermalViz.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/openCVLibrary2411/openCVLibrary2411.iml" filepath="$PROJECT_DIR$/openCVLibrary2411/openCVLibrary2411.iml" />
<module fileurl="file://$PROJECT_DIR$/usbSerialForAndroid/usbSerialForAndroid.iml" filepath="$PROJECT_DIR$/usbSerialForAndroid/usbSerialForAndroid.iml" />
</modules>
</component>
</project> | {
"content_hash": "fccb3154ee0e7c561f93aa231b74393d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 160,
"avg_line_length": 61,
"alnum_prop": 0.7183308494783904,
"repo_name": "JoeWolski/CMSC436",
"id": "049bdfff2078f3224db25c3ed80185dd14b31463",
"size": "671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ThermalViz/.idea/modules.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "200539"
},
{
"name": "C++",
"bytes": "2706927"
},
{
"name": "CMake",
"bytes": "182598"
},
{
"name": "HTML",
"bytes": "36040"
},
{
"name": "Java",
"bytes": "7478722"
},
{
"name": "Makefile",
"bytes": "8728"
},
{
"name": "Objective-C",
"bytes": "7718"
},
{
"name": "Python",
"bytes": "2335"
}
],
"symlink_target": ""
} |
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
<predicate lemma="froth">
<note>
Frames file for 'froth' based on survey of sentences in the WSJ
corpus.
</note>
<roleset id="froth.01" name="to foam, become bubbly" vncls="47.2">
<roles>
<role descr="entity frothing" n="1">
<vnrole vncls="47.2" vntheta="Theme"/>
</role>
</roles>
<example name="intransitive">
<inflection aspect="ns" form="ns" person="ns" tense="ns" voice="active"/>
<text>
At 4 1\/2 pounds , it may be too ambitiously named [*-1] , but it nevertheless opens up the kind of marketing possibilities that [*T*-2] make analysts froth .
</text>
<arg n="1">analysts</arg>
<rel>froth</rel>
</example>
</roleset>
</predicate>
<note>
frames created by Olga
</note>
</frameset>
| {
"content_hash": "8d489a655e71ec0a3f22308850e82ba7",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 178,
"avg_line_length": 32.696969696969695,
"alnum_prop": 0.4782205746061168,
"repo_name": "keenon/jamr",
"id": "354b456e2f92d4be86bb49a5acd32f8c183f492d",
"size": "1079",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "data/frames/froth.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "640454"
},
{
"name": "Perl",
"bytes": "8697"
},
{
"name": "Python",
"bytes": "76079"
},
{
"name": "Scala",
"bytes": "353885"
},
{
"name": "Shell",
"bytes": "41192"
}
],
"symlink_target": ""
} |
namespace Microsoft.Azure.Management.Internal.Network.Version2017_10_01
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkSecurityGroupsOperations operations.
/// </summary>
internal partial class NetworkSecurityGroupsOperations : IServiceOperations<NetworkManagementClient>, INetworkSecurityGroupsOperations
{
/// <summary>
/// Initializes a new instance of the NetworkSecurityGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal NetworkSecurityGroupsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NetworkSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NetworkSecurityGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<NetworkSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<NetworkSecurityGroup> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a network security group tags.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update network security group tags.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<NetworkSecurityGroup>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, TagsObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<NetworkSecurityGroup> _response = await BeginUpdateTagsWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NetworkSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NetworkSecurityGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a network security group tags.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update network security group tags.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NetworkSecurityGroup>> BeginUpdateTagsWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, TagsObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-10-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdateTags", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NetworkSecurityGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkSecurityGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NetworkSecurityGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkSecurityGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| {
"content_hash": "194e4ac0a3c5c1e921aae1f18a60f845",
"timestamp": "",
"source": "github",
"line_count": 1636,
"max_line_length": 325,
"avg_line_length": 47.02261613691932,
"alnum_prop": 0.5585669903417437,
"repo_name": "devigned/azure-powershell",
"id": "65bcef4a55754c4276d7544caaaccf4386f86fa7",
"size": "77282",
"binary": false,
"copies": "4",
"ref": "refs/heads/preview",
"path": "src/Common/Commands.Common.Network/Version2017_10_01/NetworkSecurityGroupsOperations.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18388"
},
{
"name": "C#",
"bytes": "60706952"
},
{
"name": "HTML",
"bytes": "209"
},
{
"name": "JavaScript",
"bytes": "4979"
},
{
"name": "PHP",
"bytes": "41"
},
{
"name": "PowerShell",
"bytes": "7187413"
},
{
"name": "Ruby",
"bytes": "398"
},
{
"name": "Shell",
"bytes": "50"
},
{
"name": "Smalltalk",
"bytes": "2510"
},
{
"name": "XSLT",
"bytes": "6114"
}
],
"symlink_target": ""
} |
mafia
=====
Diku, Rom, Animud Area Editor
I wrote and worked on this mostly in the years 2002-2004. After that I made tweaks and used it to experiment with Java code from time to time.
This is a Swing implementation of an area editor for Roms, that could easily work for Diku or any other type of mud with some modifications.
Work did begin on forming a proper layer of abstraction. You should be able to separate some of the area behavior and provide an implementation for the services that depends on the type of mud area at runtime.
This code is provided as is, though emails and messages about it are welcome.
You can play Animud which is still running, but visiting https://animud.net or directly via telnet at animud.net:6667
Happy Mudding/Building! :-)
| {
"content_hash": "fa097d10005d64e689259e49f64222fd",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 209,
"avg_line_length": 45.1764705882353,
"alnum_prop": 0.7799479166666666,
"repo_name": "georgefrick/mafia",
"id": "d3cb90af6c4c08e4ab3c7639b859f3a936bc33b0",
"size": "768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1169671"
}
],
"symlink_target": ""
} |
/* $NetBSD: queue.h,v 1.30 2001/06/22 06:18:22 chs Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
#ifndef BL_BSD_SYS_QUEUE_H_
#define BL_BSD_SYS_QUEUE_H_
#include <bl/base/platform.h>
/*---------------------------------------------------------------------------*/
/* Man page copy. Remember that we use lower case
DESCRIPTION
These macros define and operate on four types of data structures:
singly-linked lists, singly-linked tail queues, lists, and tail queues. All
four structures support the following functionality:
1. Insertion of a new entry at the head of the list.
2. Insertion of a new entry after any element in the list.
3. O(1) removal of an entry from the head of the list.
4. Forward traversal through the list.
5. Swapping the contents of two lists.
Singly-linked lists are the simplest of the four data structures and support
only the above functionality. Singly-linked lists are ideal for applications
with large datasets and few or no removals, or for implementing a LIFO queue.
Singly-linked lists add the following functionality:
1. O(n) removal of any entry in the list.
Singly-linked tail queues add the following functionality:
1. Entries can be added at the end of a list.
2. O(n) removal of any entry in the list.
3. They may be concatenated.
However:
1. All list insertions must specify the head of the list.
2. Each head entry requires two pointers rather than one.
3. Code size is about 15% greater and operations run about 20% slower than
singly-linked lists.
Singly-linked tail queues are ideal for applications with large datasets and
few or no removals, or for implementing a FIFO queue.
All doubly linked types of data structures (lists and tail queues)
additionally allow:
1. Insertion of a new entry before any element in the list.
2. O(1) removal of any entry in the list.
However:
1. Each element requires two pointers rather than one.
2. Code size and execution time of operations (except for removal) is about
twice that of the singly-linked data-structures.
Linked lists are the simplest of the doubly linked data structures. They add
the following functionality over the above:
1. They may be traversed backwards.
However:
1. To traverse backwards, an entry to begin the traversal and the list in
which it is contained must be specified.
Tail queues add the following functionality:
1. Entries can be added at the end of a list.
2. They may be traversed backwards, from tail to head.
3. They may be concatenated.
However:
1. All list insertions and removals must specify the head of the list.
2. Each head entry requires two pointers rather than one.
3. Code size is about 15% greater and operations run about 20% slower than
singly-linked lists.
In the macro definitions, TYPE is the name of a user defined structure, that
must contain a field of type SLIST_ENTRY, STAILQ_ENTRY, LIST_ENTRY, or
TAILQ_ENTRY, named NAME. The argument HEADNAME is the name of a user defined
structure that must be declared using the macros SLIST_HEAD, STAILQ_HEAD,
LIST_HEAD, or TAILQ_HEAD. See the examples below for further explanation of
how these macros are used.
SINGLY-LINKED LISTS
A singly-linked list is headed by a structure defined by the SLIST_HEAD macro.
This structure contains a single pointer to the first element on the list.
The elements are singly linked for minimum space and pointer manipulation
overhead at the expense of O(n) removal for arbitrary elements. New elements
can be added to the list after an existing element or at the head of the list.
An SLIST_HEAD structure is declared as follows:
SLIST_HEAD(HEADNAME, TYPE) head;
where HEADNAME is the name of the structure to be defined, and TYPE is the
type of the elements to be linked into the list. A pointer to the head of the
list can later be declared as:
struct HEADNAME *headp;
(The names head and headp are user selectable.)
The macro SLIST_HEAD_INITIALIZER evaluates to an initializer for the list
head.
The macro SLIST_EMPTY evaluates to true if there are no elements in the list.
The macro SLIST_ENTRY declares a structure that connects the elements in the
list.
The macro SLIST_FIRST returns the first element in the list or NULL if the
list is empty.
The macro SLIST_FOREACH traverses the list referenced by head in the forward
direction, assigning each element in turn to var.
The macro SLIST_FOREACH_FROM behaves identically to SLIST_FOREACH when var is
NULL, else it treats var as a previously found SLIST element and begins the
loop at var instead of the first element in the SLIST referenced by head.
The macro SLIST_FOREACH_SAFE traverses the list referenced by head in the
forward direction, assigning each element in turn to var. However, unlike
SLIST_FOREACH() here it is permitted to both remove var as well as free it
from within the loop safely without interfering with the traversal.
The macro SLIST_FOREACH_FROM_SAFE behaves identically to SLIST_FOREACH_SAFE
when var is NULL, else it treats var as a previously found SLIST element and
begins the loop at var instead of the first element in the SLIST referenced
by head.
The macro SLIST_INIT initializes the list referenced by head.
The macro SLIST_INSERT_HEAD inserts the new element elm at the head of the
list.
The macro SLIST_INSERT_AFTER inserts the new element elm after the element
listelm.
The macro SLIST_NEXT returns the next element in the list.
The macro SLIST_REMOVE_AFTER removes the element after elm from the list.
Unlike SLIST_REMOVE, this macro does not traverse the entire list.
The macro SLIST_REMOVE_HEAD removes the element elm from the head of the list.
For optimum efficiency, elements being removed from the head of the list
should explicitly use this macro instead of the generic SLIST_REMOVE macro.
The macro SLIST_REMOVE removes the element elm from the list.
The macro SLIST_SWAP swaps the contents of head1 and head2.
SINGLY-LINKED LIST EXAMPLE
SLIST_HEAD(slisthead, entry) head =
SLIST_HEAD_INITIALIZER(head);
struct slisthead *headp; --> Singly-linked List head.
struct entry {
...
SLIST_ENTRY(entry) entries; --> Singly-linked List.
...
} *n1, *n2, *n3, *np;
SLIST_INIT(&head); --> Initialize the list.
n1 = malloc(sizeof(struct entry)); --> Insert at the head.
SLIST_INSERT_HEAD(&head, n1, entries);
n2 = malloc(sizeof(struct entry)); --> Insert after.
SLIST_INSERT_AFTER(n1, n2, entries);
SLIST_REMOVE(&head, n2, entry, entries);--> Deletion.
free(n2);
n3 = SLIST_FIRST(&head);
SLIST_REMOVE_HEAD(&head, entries); --> Deletion from the head.
free(n3);
--> Forward traversal.
SLIST_FOREACH(np, &head, entries)
np-> ...
--> Safe forward traversal.
SLIST_FOREACH_SAFE(np, &head, entries, np_temp) {
np->do_stuff();
...
SLIST_REMOVE(&head, np, entry, entries);
free(np);
}
while (!SLIST_EMPTY(&head)) { --> List Deletion.
n1 = SLIST_FIRST(&head);
SLIST_REMOVE_HEAD(&head, entries);
free(n1);
}
SINGLY-LINKED TAIL QUEUES
A singly-linked tail queue is headed by a structure defined by the
STAILQ_HEAD macro. This structure contains a pair of pointers, one to the
first element in the tail queue and the other to the last element in the tail
queue. The elements are singly linked for minimum space and pointer
manipulation overhead at the expense of O(n) removal for arbitrary elements.
New elements can be added to the tail queue after an existing element, at the
head of the tail queue, or at the end of the tail queue. A STAILQ_HEAD
structure is declared as follows:
STAILQ_HEAD(HEADNAME, TYPE) head;
where HEADNAME is the name of the structure to be defined, and TYPE is the
type of the elements to be linked into the tail queue. A pointer to the head
of the tail queue can later be declared as:
struct HEADNAME *headp;
(The names head and headp are user selectable.)
The macro STAILQ_HEAD_INITIALIZER evaluates to an initializer for the tail
queue head.
The macro STAILQ_CONCAT concatenates the tail queue headed by head2 onto the
end of the one headed by head1 removing all entries from the former.
The macro STAILQ_EMPTY evaluates to true if there are no items on the tail
queue.
The macro STAILQ_ENTRY declares a structure that connects the elements in the
tail queue.
The macro STAILQ_FIRST returns the first item on the tail queue or NULL if the
tail queue is empty.
The macro STAILQ_FOREACH traverses the tail queue referenced by head in the
forward direction, assigning each element in turn to var.
The macro STAILQ_FOREACH_FROM behaves identically to STAILQ_FOREACH when var
is NULL, else it treats var as a previously found STAILQ element and begins
the loop at var instead of the first element in the STAILQ referenced by head.
The macro STAILQ_FOREACH_SAFE traverses the tail queue referenced by head in
the forward direction, assigning each element in turn to var. However, unlike
STAILQ_FOREACH() here it is permitted to both remove var as well as free it
from within the loop safely without interfering with the traversal.
The macro STAILQ_FOREACH_FROM_SAFE behaves identically to STAILQ_FOREACH_SAFE
when var is NULL, else it treats var as a previously found STAILQ element and
begins the loop at var instead of the first element in the STAILQ referenced
by head.
The macro STAILQ_INIT initializes the tail queue referenced by head.
The macro STAILQ_INSERT_HEAD inserts the new element elm at the head of the
tail queue.
The macro STAILQ_INSERT_TAIL inserts the new element elm at the end of the
tail queue.
The macro STAILQ_INSERT_AFTER inserts the new element elm after the element
listelm.
The macro STAILQ_LAST returns the last item on the tail queue. If the tail
queue is empty the return value is NULL.
The macro STAILQ_NEXT returns the next item on the tail queue, or NULL this
item is the last.
The macro STAILQ_REMOVE_AFTER removes the element after elm from the tail
queue. Unlike STAILQ_REMOVE, this macro does not traverse the entire tail
queue.
The macro STAILQ_REMOVE_HEAD removes the element at the head of the tail
queue. For optimum efficiency, elements being removed from the head of the
tail queue should use this macro explicitly rather than the generic
STAILQ_REMOVE macro.
The macro STAILQ_REMOVE removes the element elm from the tail queue.
The macro STAILQ_SWAP swaps the contents of head1 and head2.
SINGLY-LINKED TAIL QUEUE EXAMPLE
STAILQ_HEAD(stailhead, entry) head =
STAILQ_HEAD_INITIALIZER(head);
struct stailhead *headp; --> Singly-linked tail queue head.
struct entry {
...
STAILQ_ENTRY(entry) entries; --> Tail queue.
...
} *n1, *n2, *n3, *np;
STAILQ_INIT(&head); --> Initialize the queue.
n1 = malloc(sizeof(struct entry)); --> Insert at the head.
STAILQ_INSERT_HEAD(&head, n1, entries);
n1 = malloc(sizeof(struct entry)); --> Insert at the tail.
STAILQ_INSERT_TAIL(&head, n1, entries);
n2 = malloc(sizeof(struct entry)); --> Insert after.
STAILQ_INSERT_AFTER(&head, n1, n2, entries);
--> Deletion.
STAILQ_REMOVE(&head, n2, entry, entries);
free(n2);
--> Deletion from the head.
n3 = STAILQ_FIRST(&head);
STAILQ_REMOVE_HEAD(&head, entries);
free(n3);
--> Forward traversal.
STAILQ_FOREACH(np, &head, entries)
np-> ...
--> Safe forward traversal.
STAILQ_FOREACH_SAFE(np, &head, entries, np_temp) {
np->do_stuff();
...
STAILQ_REMOVE(&head, np, entry, entries);
free(np);
}
--> TailQ Deletion.
while (!STAILQ_EMPTY(&head)) {
n1 = STAILQ_FIRST(&head);
STAILQ_REMOVE_HEAD(&head, entries);
free(n1);
}
--> Faster TailQ Deletion.
n1 = STAILQ_FIRST(&head);
while (n1 != NULL) {
n2 = STAILQ_NEXT(n1, entries);
free(n1);
n1 = n2;
}
STAILQ_INIT(&head);
LISTS
A list is headed by a structure defined by the LIST_HEAD macro. This
structure contains a single pointer to the first element on the list. The
elements are doubly linked so that an arbitrary element can be removed without
traversing the list. New elements can be added to the list after an existing
element, before an existing element, or at the head of the list. A LIST_HEAD
structure is declared as follows:
LIST_HEAD(HEADNAME, TYPE) head;
where HEADNAME is the name of the structure to be defined, and TYPE is the
type of the elements to be linked into the list. A pointer to the head of the
list can later be declared as:
struct HEADNAME *headp;
(The names head and headp are user selectable.)
The macro LIST_HEAD_INITIALIZER evaluates to an initializer for the list head.
The macro LIST_EMPTY evaluates to true if there are no elements in the list.
The macro LIST_ENTRY declares a structure that connects the elements in the
list.
The macro LIST_FIRST returns the first element in the list or NULL if the list
is empty.
The macro LIST_FOREACH traverses the list referenced by head in the forward
direction, assigning each element in turn to var.
The macro LIST_FOREACH_FROM behaves identically to LIST_FOREACH when var is
NULL, else it treats var as a previously found LIST element and begins the
loop at var instead of the first element in the LIST referenced by head.
The macro LIST_FOREACH_SAFE traverses the list referenced by head in the
forward direction, assigning each element in turn to var. However, unlike
LIST_FOREACH() here it is permitted to both remove var as well as free it from
within the loop safely without interfering with the traversal.
The macro LIST_FOREACH_FROM_SAFE behaves identically to LIST_FOREACH_SAFE when
var is NULL, else it treats var as a previously found LIST element and begins
the loop at var instead of the first element in the LIST referenced by head.
The macro LIST_INIT initializes the list referenced by head.
The macro LIST_INSERT_HEAD inserts the new element elm at the head of the
list.
The macro LIST_INSERT_AFTER inserts the new element elm after the element
listelm.
The macro LIST_INSERT_BEFORE inserts the new element elm before the element
listelm.
The macro LIST_NEXT returns the next element in the list, or NULL if this is
the last.
The macro LIST_PREV returns the previous element in the list, or NULL if this
is the first. List head must contain element elm.
The macro LIST_REMOVE removes the element elm from the list.
The macro LIST_SWAP swaps the contents of head1 and head2.
LIST EXAMPLE
LIST_HEAD(listhead, entry) head =
LIST_HEAD_INITIALIZER(head);
struct listhead *headp; --> List head.
struct entry {
...
LIST_ENTRY(entry) entries; --> List.
...
} *n1, *n2, *n3, *np, *np_temp;
LIST_INIT(&head); --> Initialize the list.
n1 = malloc(sizeof(struct entry)); --> Insert at the head.
LIST_INSERT_HEAD(&head, n1, entries);
n2 = malloc(sizeof(struct entry)); --> Insert after.
LIST_INSERT_AFTER(n1, n2, entries);
n3 = malloc(sizeof(struct entry)); --> Insert before.
LIST_INSERT_BEFORE(n2, n3, entries);
LIST_REMOVE(n2, entries); --> Deletion.
free(n2);
--> Forward traversal.
LIST_FOREACH(np, &head, entries)
np-> ...
--> Safe forward traversal.
LIST_FOREACH_SAFE(np, &head, entries, np_temp) {
np->do_stuff();
...
LIST_REMOVE(np, entries);
free(np);
}
while (!LIST_EMPTY(&head)) { --> List Deletion.
n1 = LIST_FIRST(&head);
LIST_REMOVE(n1, entries);
free(n1);
}
n1 = LIST_FIRST(&head); --> Faster List Deletion.
while (n1 != NULL) {
n2 = LIST_NEXT(n1, entries);
free(n1);
n1 = n2;
}
LIST_INIT(&head);
TAIL QUEUES
A tail queue is headed by a structure defined by the TAILQ_HEAD macro. This
structure contains a pair of pointers, one to the first element in the tail
queue and the other to the last element in the tail queue. The elements are
doubly linked so that an arbitrary element can be removed without traversing
the tail queue. New elements can be added to the tail queue after an existing
element, before an existing element, at the head of the tail queue, or at the
end of the tail queue. A TAILQ_HEAD structure is declared as follows:
TAILQ_HEAD(HEADNAME, TYPE) head;
where HEADNAME is the name of the structure to be defined, and TYPE is the
type of the elements to be linked into the tail queue. A pointer to the head
of the tail queue can later be declared as:
struct HEADNAME *headp;
(The names head and headp are user selectable.)
The macro TAILQ_HEAD_INITIALIZER evaluates to an initializer for the tail
queue head.
The macro TAILQ_CONCAT concatenates the tail queue headed by head2 onto the
end of the one headed by head1 removing all entries from the former.
The macro TAILQ_EMPTY evaluates to true if there are no items on the tail
queue.
The macro TAILQ_ENTRY declares a structure that connects the elements in the
tail queue.
The macro TAILQ_FIRST returns the first item on the tail queue or NULL if the
tail queue is empty.
The macro TAILQ_FOREACH traverses the tail queue referenced by head in the
forward direction, assigning each element in turn to var. var is set to NULL
if the loop completes normally, or if there were no elements.
The macro TAILQ_FOREACH_FROM behaves identically to TAILQ_FOREACH when var is
NULL, else it treats var as a previously found TAILQ element and begins the
loop at var instead of the first element in the TAILQ referenced by head.
The macro TAILQ_FOREACH_REVERSE traverses the tail queue referenced by head in
the reverse direction, assigning each element in turn to var.
The macro TAILQ_FOREACH_REVERSE_FROM behaves identically to
TAILQ_FOREACH_REVERSE when var is NULL, else it treats var as a previously
found TAILQ element and begins the reverse loop at var instead of the last
element in the TAILQ referenced by head.
The macros TAILQ_FOREACH_SAFE and TAILQ_FOREACH_REVERSE_SAFE traverse the list
referenced by head in the forward or reverse direction respectively, assigning
each element in turn to var. However, unlike their unsafe counterparts,
TAILQ_FOREACH and TAILQ_FOREACH_REVERSE permit to both remove var as well as
free it from within the loop safely without interfering with the traversal.
The macro TAILQ_FOREACH_FROM_SAFE behaves identically to TAILQ_FOREACH_SAFE
when var is NULL, else it treats var as a previously found TAILQ element and
begins the loop at var instead of the first element in the TAILQ referenced by
head.
The macro TAILQ_FOREACH_REVERSE_FROM_SAFE behaves identically to
TAILQ_FOREACH_REVERSE_SAFE when var is NULL, else it treats var as a
previously found TAILQ element and begins the reverse loop at var instead of
the last element in the TAILQ referenced by head.
The macro TAILQ_INIT initializes the tail queue referenced by head.
The macro TAILQ_INSERT_HEAD inserts the new element elm at the head of the
tail queue.
The macro TAILQ_INSERT_TAIL inserts the new element elm at the end of the
tail queue.
The macro TAILQ_INSERT_AFTER inserts the new element elm after the element
listelm.
The macro TAILQ_INSERT_BEFORE inserts the new element elm before the element
listelm.
The macro TAILQ_LAST returns the last item on the tail queue. If the tail
queue is empty the return value is NULL.
The macro TAILQ_NEXT returns the next item on the tail queue, or NULL if this
item is the last.
The macro TAILQ_PREV returns the previous item on the tail queue, or NULL if
this item is the first.
The macro TAILQ_REMOVE removes the element elm from the tail queue.
The macro TAILQ_SWAP swaps the contents of head1 and head2.
TAIL QUEUE EXAMPLE
TAILQ_HEAD(tailhead, entry) head =
TAILQ_HEAD_INITIALIZER(head);
struct tailhead *headp; --> Tail queue head.
struct entry {
...
TAILQ_ENTRY(entry) entries; --> Tail queue.
...
} *n1, *n2, *n3, *np;
TAILQ_INIT(&head); --> Initialize the queue.
n1 = malloc(sizeof(struct entry)); --> Insert at the head.
TAILQ_INSERT_HEAD(&head, n1, entries);
n1 = malloc(sizeof(struct entry)); --> Insert at the tail.
TAILQ_INSERT_TAIL(&head, n1, entries);
n2 = malloc(sizeof(struct entry)); --> Insert after.
TAILQ_INSERT_AFTER(&head, n1, n2, entries);
n3 = malloc(sizeof(struct entry)); --> Insert before.
TAILQ_INSERT_BEFORE(n2, n3, entries);
TAILQ_REMOVE(&head, n2, entries); --> Deletion.
free(n2);
--> Forward traversal.
TAILQ_FOREACH(np, &head, entries)
np-> ...
--> Safe forward traversal.
TAILQ_FOREACH_SAFE(np, &head, entries, np_temp) {
np->do_stuff();
...
TAILQ_REMOVE(&head, np, entries);
free(np);
}
--> Reverse traversal.
TAILQ_FOREACH_REVERSE(np, &head, tailhead, entries)
np-> ...
--> TailQ Deletion.
while (!TAILQ_EMPTY(&head)) {
n1 = TAILQ_FIRST(&head);
TAILQ_REMOVE(&head, n1, entries);
free(n1);
}
--> Faster TailQ Deletion.
n1 = TAILQ_FIRST(&head);
while (n1 != NULL) {
n2 = TAILQ_NEXT(n1, entries);
free(n1);
n1 = n2;
}
TAILQ_INIT(&head);
*/
/*---------------------------------------------------------------------------*/
#define bl_list_head(name, type)\
struct name {\
struct type *lh_first; /* first element */\
}
#define bl_list_head_initializer(head)\
{ nullptr }
#define bl_list_entry(type)\
struct {\
struct type *le_next; /* next element */\
struct type **le_prev; /* address of previous next element */\
}
/*
* list functions.
*/
#define bl_queuedebug_list_insert_head(head, elm, field)
#define bl_queuedebug_list_op(elm, field)
#define bl_queuedebug_list_postremove(elm, field)
#define bl_list_init(head)\
do {\
(head)->lh_first = nullptr;\
} while (/*constcond*/0)
#define bl_list_insert_after(listelm, elm, field)\
do {\
bl_queuedebug_list_op((listelm), field)\
if (((elm)->field.le_next = (listelm)->field.le_next) != nullptr)\
(listelm)->field.le_next->field.le_prev =\
&(elm)->field.le_next;\
(listelm)->field.le_next = (elm);\
(elm)->field.le_prev = &(listelm)->field.le_next;\
} while (/*constcond*/0)
#define bl_list_insert_before(listelm, elm, field)\
do {\
bl_queuedebug_list_op((listelm), field)\
(elm)->field.le_prev = (listelm)->field.le_prev;\
(elm)->field.le_next = (listelm);\
*(listelm)->field.le_prev = (elm);\
(listelm)->field.le_prev = &(elm)->field.le_next;\
} while (/*constcond*/0)
#define bl_list_insert_head(head, elm, field)\
do {\
bl_queuedebug_list_insert_head((head), (elm), field)\
if (((elm)->field.le_next = (head)->lh_first) != nullptr)\
(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
(head)->lh_first = (elm);\
(elm)->field.le_prev = &(head)->lh_first;\
} while (/*constcond*/0)
#define bl_list_remove(elm, field)\
do {\
bl_queuedebug_list_op((elm), field)\
if ((elm)->field.le_next != nullptr)\
(elm)->field.le_next->field.le_prev = \
(elm)->field.le_prev;\
*(elm)->field.le_prev = (elm)->field.le_next;\
bl_queuedebug_list_postremove((elm), field)\
} while (/*constcond*/0)
#define bl_list_foreach(var, head, field)\
for ((var) = ((head)->lh_first);\
(var);\
(var) = ((var)->field.le_next))
/*
* list access methods.
*/
#define bl_list_empty(head) ((head)->lh_first == nullptr)
#define bl_list_first(head) ((head)->lh_first)
#define bl_list_next(elm, field) ((elm)->field.le_next)
/*
* singly-linked list definitions.
*/
#define bl_slist_head(name, type)\
struct name {\
struct type *slh_first; /* first element */\
}
#define sbl_list_head_initializer(head)\
{ nullptr }
#define bl_slist_entry(type)\
struct {\
struct type *sle_next; /* next element */\
}
/*
* singly-linked list functions.
*/
#define bl_slist_empty(head) ((head)->slh_first == nullptr)
#define bl_slist_first(head) ((head)->slh_first)
#define bl_slist_next(elm, field) ((elm)->field.sle_next)
#define bl_slist_foreach(var, head, field)\
for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next)
#define bl_slist_init(head)\
do {\
(head)->slh_first = nullptr;\
} while (/*constcond*/0)
#define bl_slist_insert_after(slistelm, elm, field)\
do {\
(elm)->field.sle_next = (slistelm)->field.sle_next;\
(slistelm)->field.sle_next = (elm);\
} while (/*constcond*/0)
#define bl_slist_insert_head(head, elm, field)\
do {\
(elm)->field.sle_next = (head)->slh_first;\
(head)->slh_first = (elm);\
} while (/*constcond*/0)
#define bl_slist_next(elm, field) ((elm)->field.sle_next)
#define bl_slist_remove_head(head, field)\
do {\
(head)->slh_first = (head)->slh_first->field.sle_next;\
} while (/*constcond*/0)
#define bl_slist_remove(head, elm, type, field)\
do {\
if ((head)->slh_first == (elm)) {\
bl_slist_remove_head((head), field);\
}\
else {\
struct type *curelm = (head)->slh_first;\
while(curelm->field.sle_next != (elm))\
curelm = curelm->field.sle_next;\
curelm->field.sle_next =\
curelm->field.sle_next->field.sle_next;\
}\
} while (/*constcond*/0)
/*
* simple queue definitions.
*/
#define bl_simpleq_head(name, type)\
struct name {\
struct type *sqh_first; /* first element */\
struct type **sqh_last; /* addr of last next element */\
}
#define bl_simpleq_head_initializer(head)\
{ nullptr, &(head).sqh_first }
#define bl_simpleq_entry(type)\
struct {\
struct type *sqe_next; /* next element */\
}
/*
* simple queue functions.
*/
#define bl_simpleq_init(head)\
do {\
(head)->sqh_first = nullptr;\
(head)->sqh_last = &(head)->sqh_first;\
} while (/*constcond*/0)
#define bl_simpleq_insert_head(head, elm, field)\
do {\
if (((elm)->field.sqe_next = (head)->sqh_first) == nullptr)\
(head)->sqh_last = &(elm)->field.sqe_next;\
(head)->sqh_first = (elm);\
} while (/*constcond*/0)
#define bl_simpleq_insert_tail(head, elm, field)\
do {\
(elm)->field.sqe_next = nullptr;\
*(head)->sqh_last = (elm);\
(head)->sqh_last = &(elm)->field.sqe_next;\
} while (/*constcond*/0)
#define bl_simpleq_insert_after(head, listelm, elm, field)\
do {\
if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == nullptr)\
(head)->sqh_last = &(elm)->field.sqe_next;\
(listelm)->field.sqe_next = (elm);\
} while (/*constcond*/0)
#define bl_simpleq_remove_head(head, elm, field)\
do {\
if (((head)->sqh_first = (elm)->field.sqe_next) == nullptr)\
(head)->sqh_last = &(head)->sqh_first;\
} while (/*constcond*/0)
#define bl_simpleq_foreach(var, head, field)\
for ((var) = ((head)->sqh_first);\
(var);\
(var) = ((var)->field.sqe_next))
/*
* simple queue access methods.
*/
#define bl_simpleq_empty(head) ((head)->sqh_first == nullptr)
#define bl_simpleq_first(head) ((head)->sqh_first)
#define bl_simpleq_next(elm, field) ((elm)->field.sqe_next)
/*
* tail queue definitions.
*/
#define bl_tailq_head(name, type)\
struct name {\
struct type *tqh_first; /* first element */\
struct type **tqh_last; /* addr of last next element */\
}
#define bl_tailq_head_initializer(head)\
{ nullptr, &(head).tqh_first }
#define bl_tailq_entry(type)\
struct {\
struct type *tqe_next; /* next element */\
struct type **tqe_prev; /* address of previous next element */\
}
/*
* tail queue functions.
*/
#define bl_queuedebug_tailq_insert_head(head, elm, field)
#define bl_queuedebug_tailq_insert_tail(head, elm, field)
#define bl_queuedebug_tailq_op(elm, field)
#define bl_queuedebug_tailq_postremove(elm, field)
#define bl_tailq_init(head)\
do {\
(head)->tqh_first = nullptr;\
(head)->tqh_last = &(head)->tqh_first;\
} while (/*constcond*/0)
#define bl_tailq_insert_head(head, elm, field)\
do {\
bl_queuedebug_tailq_insert_head((head), (elm), field)\
if (((elm)->field.tqe_next = (head)->tqh_first) != nullptr)\
(head)->tqh_first->field.tqe_prev =\
&(elm)->field.tqe_next;\
else\
(head)->tqh_last = &(elm)->field.tqe_next;\
(head)->tqh_first = (elm);\
(elm)->field.tqe_prev = &(head)->tqh_first;\
} while (/*constcond*/0)
#define bl_tailq_insert_tail(head, elm, field)\
do {\
bl_queuedebug_tailq_insert_tail((head), (elm), field)\
(elm)->field.tqe_next = nullptr;\
(elm)->field.tqe_prev = (head)->tqh_last;\
*(head)->tqh_last = (elm);\
(head)->tqh_last = &(elm)->field.tqe_next;\
} while (/*constcond*/0)
#define bl_tailq_insert_after(head, listelm, elm, field)\
do {\
bl_queuedebug_tailq_op((listelm), field)\
if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != nullptr)\
(elm)->field.tqe_next->field.tqe_prev = \
&(elm)->field.tqe_next;\
else\
(head)->tqh_last = &(elm)->field.tqe_next;\
(listelm)->field.tqe_next = (elm);\
(elm)->field.tqe_prev = &(listelm)->field.tqe_next;\
} while (/*constcond*/0)
#define bl_tailq_insert_before(listelm, elm, field)\
do {\
bl_queuedebug_tailq_op((listelm), field)\
(elm)->field.tqe_prev = (listelm)->field.tqe_prev;\
(elm)->field.tqe_next = (listelm);\
*(listelm)->field.tqe_prev = (elm);\
(listelm)->field.tqe_prev = &(elm)->field.tqe_next;\
} while (/*constcond*/0)
#define bl_tailq_remove(head, elm, field)\
do {\
bl_queuedebug_tailq_op((elm), field)\
if (((elm)->field.tqe_next) != nullptr)\
(elm)->field.tqe_next->field.tqe_prev = \
(elm)->field.tqe_prev;\
else\
(head)->tqh_last = (elm)->field.tqe_prev;\
*(elm)->field.tqe_prev = (elm)->field.tqe_next;\
bl_queuedebug_tailq_postremove((elm), field);\
} while (/*constcond*/0)
/*
* tail queue access methods.
*/
#define bl_tailq_empty(head) ((head)->tqh_first == nullptr)
#define bl_tailq_first(head) ((head)->tqh_first)
#define bl_tailq_next(elm, field) ((elm)->field.tqe_next)
#define bl_tailq_last(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
#define bl_tailq_prev(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define bl_tailq_foreach(var, head, field)\
for ((var) = ((head)->tqh_first);\
(var);\
(var) = ((var)->field.tqe_next))
#define bl_tailq_foreach_reverse(var, head, headname, field)\
for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last));\
(var);\
(var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last)))
/*
* circular queue definitions.
*/
#define bl_circleq_head(name, type)\
struct name {\
struct type *cqh_first; /* first element */\
struct type *cqh_last; /* last element */\
}
#define bl_circleq_head_initializer(head)\
{ (void *)&head, (void *)&head }
#define bl_circleq_entry(type)\
struct {\
struct type *cqe_next; /* next element */\
struct type *cqe_prev; /* previous element */\
}
/*
* circular queue functions.
*/
#define bl_circleq_init(head)\
do {\
(head)->cqh_first = (void *)(head);\
(head)->cqh_last = (void *)(head);\
} while (/*constcond*/0)
#define bl_circleq_insert_after(head, listelm, elm, field)\
do {\
(elm)->field.cqe_next = (listelm)->field.cqe_next;\
(elm)->field.cqe_prev = (listelm);\
if ((listelm)->field.cqe_next == (void *)(head))\
(head)->cqh_last = (elm);\
else\
(listelm)->field.cqe_next->field.cqe_prev = (elm);\
(listelm)->field.cqe_next = (elm);\
} while (/*constcond*/0)
#define bl_circleq_insert_before(head, listelm, elm, field)\
do {\
(elm)->field.cqe_next = (listelm);\
(elm)->field.cqe_prev = (listelm)->field.cqe_prev;\
if ((listelm)->field.cqe_prev == (void *)(head))\
(head)->cqh_first = (elm);\
else\
(listelm)->field.cqe_prev->field.cqe_next = (elm);\
(listelm)->field.cqe_prev = (elm);\
} while (/*constcond*/0)
#define bl_circleq_insert_head(head, elm, field)\
do {\
(elm)->field.cqe_next = (head)->cqh_first;\
(elm)->field.cqe_prev = (void *)(head);\
if ((head)->cqh_last == (void *)(head))\
(head)->cqh_last = (elm);\
else\
(head)->cqh_first->field.cqe_prev = (elm);\
(head)->cqh_first = (elm);\
} while (/*constcond*/0)
#define bl_circleq_insert_tail(head, elm, field)\
do {\
(elm)->field.cqe_next = (void *)(head);\
(elm)->field.cqe_prev = (head)->cqh_last;\
if ((head)->cqh_first == (void *)(head))\
(head)->cqh_first = (elm);\
else\
(head)->cqh_last->field.cqe_next = (elm);\
(head)->cqh_last = (elm);\
} while (/*constcond*/0)
#define bl_circleq_remove(head, elm, field)\
do {\
if ((elm)->field.cqe_next == (void *)(head))\
(head)->cqh_last = (elm)->field.cqe_prev;\
else\
(elm)->field.cqe_next->field.cqe_prev =\
(elm)->field.cqe_prev;\
if ((elm)->field.cqe_prev == (void *)(head))\
(head)->cqh_first = (elm)->field.cqe_next;\
else\
(elm)->field.cqe_prev->field.cqe_next =\
(elm)->field.cqe_next;\
} while (/*constcond*/0)
#define bl_circleq_foreach(var, head, field)\
for ((var) = ((head)->cqh_first);\
(var) != (void *)(head);\
(var) = ((var)->field.cqe_next))
#define bl_circleq_foreach_reverse(var, head, field)\
for ((var) = ((head)->cqh_last);\
(var) != (void *)(head);\
(var) = ((var)->field.cqe_prev))
/*
* circular queue access methods.
*/
#define bl_circleq_empty(head) ((head)->cqh_first == (void *)(head))
#define bl_circleq_first(head) ((head)->cqh_first)
#define bl_circleq_last(head) ((head)->cqh_last)
#define bl_circleq_next(elm, field) ((elm)->field.cqe_next)
#define bl_circleq_prev(elm, field) ((elm)->field.cqe_prev)
#endif /* !_SYS_QUEUE_H_ */
| {
"content_hash": "d06eafd911f71a412d0d4a93fd2880e6",
"timestamp": "",
"source": "github",
"line_count": 1028,
"max_line_length": 80,
"avg_line_length": 34.54182879377432,
"alnum_prop": 0.6841927398687657,
"repo_name": "RafaGago/base_library",
"id": "0892f2bfc881872aad7bb9069b28a7a8582cc598",
"size": "35509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/bl/base/bsd_queue.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "331"
},
{
"name": "C",
"bytes": "1245269"
},
{
"name": "C++",
"bytes": "283160"
},
{
"name": "Meson",
"bytes": "14243"
},
{
"name": "Objective-C",
"bytes": "1469"
},
{
"name": "Shell",
"bytes": "10174"
}
],
"symlink_target": ""
} |
This is an extension to add functionality to the Zend Server Z-Ray.
It will result in additional tab(s) to be presented in the browser.
More information on the usage of this extension can be found on our site:
[www.yireo.com/software/joomla-extensions/zray](https://www.yireo.com/software/joomla-extensions/zray)
### Current state
Version 0.2.8 (stable) = Ready for production. Leave your comment for feature suggestions.
### Requirements
- For version 0.2.4: Zend Server 8.0 with Z-Ray support enabled.
- For version 0.2.5 or higher: Zend Server 8.1 with Z-Ray support enabled.
This extension will only output on Joomla sites with the Z-Ray toolbar enabled.
### Installation
Create a directory `/usr/local/zend/var/zray/extensions/Joomla`, and add the contents of this repo within.
```
/usr/local/zend/var/zray/extensions/Joomla/zray.php
/usr/local/zend/var/zray/extensions/Joomla/logo.png
```
The `zray` folder might also be a custom folder (like `/opt/zray`) when using the Z-Ray standalone version without Zend Server.
### Features
* Listing of all rendered Joomla modules (`mod_menu`, etcetera)
* Listing of triggered Joomla events (`onAfterRender`, etcetera)
* Listing of Joomla plugins that catch a triggered event (`plgContentEmailcloak`, etcetera)
* Listing of request data (component-name, view, layout, ID, Itemid, other data)
* Listing of configuration data (version, template name, template parameters, global config)
### Contact
Open an issue in the GitHub repo if you want. Alternatively, contact me at jisse AT yireo AT com or tweet to @yireo. Eat your vegetables.
| {
"content_hash": "79447b7532f13411fb839962d2f60a03",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 137,
"avg_line_length": 48.42424242424242,
"alnum_prop": 0.762828535669587,
"repo_name": "yireo/Z-Ray-Joomla",
"id": "a4707c7daa8eeca3d862ca55f3985e500b7c987d",
"size": "1614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "zray/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "18615"
}
],
"symlink_target": ""
} |
'use strict'
const pkg = require('./../package.json')
module.exports = (req, res) => {
res.send(`Hello from Staticman version ${pkg.version}!`)
}
| {
"content_hash": "042c4c32615a7d404960fea19868cc92",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 58,
"avg_line_length": 21.428571428571427,
"alnum_prop": 0.64,
"repo_name": "eduardoboucas/jekyll-discuss",
"id": "4299769b8aef6252da74a2511eb5afc0d791049f",
"size": "150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controllers/home.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "722"
},
{
"name": "JavaScript",
"bytes": "10109"
},
{
"name": "Shell",
"bytes": "1669"
}
],
"symlink_target": ""
} |
'use strict';
function extractLocationOrigin(location) {
if (Ember.typeOf(location) === 'string') {
var link = document.createElement('a');
link.href = location;
//IE requires the following line when url is relative.
//First assignment of relative url to link.href results in absolute url on link.href but link.hostname and other properties are not set
//Second assignment of absolute url to link.href results in link.hostname and other properties being set as expected
link.href = link.href;
location = link;
}
var port = location.port;
if (Ember.isEmpty(port)) {
//need to include the port whether its actually present or not as some versions of IE will always set it
port = location.protocol === 'http:' ? '80' : (location.protocol === 'https:' ? '443' : '');
}
return location.protocol + '//' + location.hostname + (port !== '' ? ':' + port : '');
}
/**
The main namespace for Ember.SimpleAuth.
__For a general overview of how Ember.SimpleAuth works, see the
[README](https://github.com/simplabs/ember-simple-auth#readme).__
@class SimpleAuth
@namespace Ember
**/
Ember.SimpleAuth = Ember.Namespace.create({
Authenticators: Ember.Namespace.create(),
Authorizers: Ember.Namespace.create(),
Stores: Ember.Namespace.create(),
/**
The route to transition to for authentication; can be set through
[Ember.SimpleAuth.setup](#Ember-SimpleAuth-setup).
@property authenticationRoute
@readOnly
@static
@type String
@default 'login'
*/
authenticationRoute: 'login',
/**
The route to transition to after successful authentication; can be set
through [Ember.SimpleAuth.setup](#Ember-SimpleAuth-setup).
@property routeAfterAuthentication
@readOnly
@static
@type String
@default 'index'
*/
routeAfterAuthentication: 'index',
/**
The route to transition to after session invalidation; can be set through
[Ember.SimpleAuth.setup](#Ember-SimpleAuth-setup).
@property routeAfterInvalidation
@readOnly
@static
@type String
@default 'index'
*/
routeAfterInvalidation: 'index',
/**
Sets up Ember.SimpleAuth for the application; this method __should be invoked in a custom
initializer__ like this:
```javascript
Ember.Application.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.setup(container, application);
}
});
```
@method setup
@static
@param {Container} container The Ember.js application's dependency injection container
@param {Ember.Application} application The Ember.js application instance
@param {Object} [options]
@param {String} [options.authenticationRoute] route to transition to for authentication - defaults to `'login'`
@param {String} [options.routeAfterAuthentication] route to transition to after successful authentication - defaults to `'index'`
@param {String} [options.routeAfterInvalidation] route to transition to after session invalidation - defaults to `'index'`
@param {Array[String]} [options.crossOriginWhitelist] Ember.SimpleAuth will never authorize requests going to a different origin than the one the Ember.js application was loaded from; to explicitely enable authorization for additional origins, whitelist those origins - defaults to `[]` _(beware that origins consist of protocol, host and port (port can be left out when it is 80))_
@param {Object} [options.authorizer] The authorizer _class_ to use; must extend `Ember.SimpleAuth.Authorizers.Base` - defaults to `Ember.SimpleAuth.Authorizers.OAuth2`
@param {Object} [options.store] The store _class_ to use; must extend `Ember.SimpleAuth.Stores.Base` - defaults to `Ember.SimpleAuth.Stores.LocalStorage`
**/
setup: function(container, application, options) {
options = options || {};
this.routeAfterAuthentication = options.routeAfterAuthentication || this.routeAfterAuthentication;
this.routeAfterInvalidation = options.routeAfterInvalidation || this.routeAfterInvalidation;
this.authenticationRoute = options.authenticationRoute || this.authenticationRoute;
this._crossOriginWhitelist = Ember.A(options.crossOriginWhitelist || []).map(function(origin) {
return extractLocationOrigin(origin);
});
container.register('ember-simple-auth:authenticators:oauth2', Ember.SimpleAuth.Authenticators.OAuth2);
var store = (options.store || Ember.SimpleAuth.Stores.LocalStorage).create();
var session = Ember.SimpleAuth.Session.create({ store: store, container: container });
var authorizer = (options.authorizer || Ember.SimpleAuth.Authorizers.OAuth2).create({ session: session });
container.register('ember-simple-auth:session:current', session, { instantiate: false });
Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
container.injection(component, 'session', 'ember-simple-auth:session:current');
});
Ember.$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (Ember.SimpleAuth.shouldAuthorizeRequest(options.url)) {
authorizer.authorize(jqXHR, options);
}
});
},
/**
@method shouldAuthorizeRequest
@private
@static
*/
shouldAuthorizeRequest: function(url) {
this._urlOrigins = this._urlOrigins || {};
this._documentOrigin = this._documentOrigin || extractLocationOrigin(window.location);
var urlOrigin = this._urlOrigins[url] = this._urlOrigins[url] || extractLocationOrigin(url);
return this._crossOriginWhitelist.indexOf(urlOrigin) > -1 || urlOrigin === this._documentOrigin;
}
});
| {
"content_hash": "8fb6c3fda7364cf9b30b31b13a7df37b",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 388,
"avg_line_length": 43.446969696969695,
"alnum_prop": 0.7060156931124673,
"repo_name": "dschmidt/ember-simple-auth",
"id": "fd5312d0e0b9542154003e4807732af7803658b8",
"size": "5735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/ember-simple-auth/lib/core.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "957"
},
{
"name": "Ruby",
"bytes": "11075"
}
],
"symlink_target": ""
} |
namespace UnitTest.Rollbar
{
using global::Rollbar;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using global::Rollbar.DTOs;
using Exception = System.Exception;
using System.Diagnostics;
using UnitTest.Rollbar.Mocks;
using global::Rollbar.Infrastructure;
/// <summary>
/// Defines test class RollbarLoggerFixture.
/// Implements the <see cref="UnitTest.Rollbar.RollbarLiveFixtureBase" />
/// </summary>
/// <seealso cref="UnitTest.Rollbar.RollbarLiveFixtureBase" />
[TestClass]
[TestCategory(nameof(RollbarLoggerFixture))]
public class RollbarLoggerFixture
: RollbarLiveFixtureBase
{
/// <summary>
/// Sets the fixture up.
/// </summary>
[TestInitialize]
public override void SetupFixture()
{
base.SetupFixture();
}
/// <summary>
/// Tears down this fixture.
/// </summary>
[TestCleanup]
public override void TearDownFixture()
{
base.TearDownFixture();
}
#region failure recovery tests
/// <summary>
/// Main purpose of these tests is to make sure that no Rollbar.NET usage scenario encountering an error
/// brings down or halts the RollbarLogger operation.
/// These tests are attempting to simulate various possible failure scenarios:
/// - corrupt/invalid data for a payload,
/// - an exception during payload transformation delegates execution,
/// - exception within a packager or package decorator,
/// - TBD...
/// </summary>
[TestMethod]
public void InvalidPayloadDataTest()
{
//TODO:
}
[TestMethod]
public void RethrowConfigOptionWorks()
{
this.Reset();
RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
using IRollbar rollbar = this.ProvideDisposableRollbar();
rollbar.Configure(config);
this.IncrementCount<CommunicationEventArgs>();
rollbar.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged async!"));
this.IncrementCount<CommunicationEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged sync!"));
int rethrowCount = 0;
config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting = true;
rollbar.Configure(config);
try
{
this.IncrementCount<CommunicationEventArgs>();
rollbar.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged async with rethrow!"));
}
catch
{
rethrowCount++;
}
try
{
this.IncrementCount<CommunicationEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged sync with rethrow!"));
}
catch
{
rethrowCount++;
}
config.RollbarDeveloperOptions.RethrowExceptionsAfterReporting = false;
rollbar.Configure(config);
this.IncrementCount<CommunicationEventArgs>();
rollbar.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged async!"));
this.IncrementCount<CommunicationEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3))
.Critical(ExceptionSimulator.GetExceptionWith(5,"Exception logged sync!"));
Assert.AreEqual(2,rethrowCount,"matching total of rethrows...");
}
[TestMethod]
public void TransmitConfigOptionWorks()
{
this.Reset();
RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
using IRollbar rollbar = this.ProvideDisposableRollbar();
rollbar.Configure(config);
this.IncrementCount<CommunicationEventArgs>();
rollbar.Critical("Transmission is expected to happen!");
this.IncrementCount<CommunicationEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to happen!");
config.RollbarDeveloperOptions.Transmit = false;
rollbar.Configure(config);
this.IncrementCount<TransmissionOmittedEventArgs>();
rollbar.Critical("Transmission is expected to be omitted!");
this.IncrementCount<TransmissionOmittedEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to be omitted!");
config.RollbarDeveloperOptions.Transmit = true;
rollbar.Configure(config);
this.IncrementCount<CommunicationEventArgs>();
rollbar.Critical("Transmission is expected to happen!");
this.IncrementCount<CommunicationEventArgs>();
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("Transmission is expected to happen!");
}
/// <summary>
/// Defines the test method FaultyPayloadTransformationTest.
/// </summary>
[TestMethod]
public void FaultyPayloadTransformationTest()
{
this.Reset();
RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
RollbarPayloadManipulationOptions rollbarPayloadManipulationOptions = new RollbarPayloadManipulationOptions();
rollbarPayloadManipulationOptions.Transform = delegate (Payload payload)
{
throw new Exception("Buggy transform delegate!");
};
config.RollbarPayloadManipulationOptions.Reconfigure(rollbarPayloadManipulationOptions);
using (IRollbar rollbar = this.ProvideDisposableRollbar())
{
rollbar.Configure(config);
rollbar.Critical("This message's Transform will fail!");
this.VerifyInstanceOperational(rollbar);
// one more extra sanity check:
Assert.AreEqual(0, RollbarQueueController.Instance.GetTotalPayloadCount());
}
this.Reset();
}
/// <summary>
/// Defines the test method FaultyCheckIgnoreTest.
/// </summary>
[TestMethod]
public void FaultyCheckIgnoreTest()
{
this.Reset();
RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();
payloadManipulationOptions.CheckIgnore = delegate (Payload payload)
{
throw new Exception("Buggy check-ignore delegate!");
};
config.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
using (IRollbar rollbar = this.ProvideDisposableRollbar())
{
rollbar.Configure(config);
rollbar.Critical("This message's CheckIgnore will fail!");
this.VerifyInstanceOperational(rollbar);
// one more extra sanity check:
Assert.AreEqual(0, RollbarQueueController.Instance.GetTotalPayloadCount());
}
this.Reset();
}
/// <summary>
/// Defines the test method FaultyTruncateTest.
/// </summary>
[TestMethod]
public void FaultyTruncateTest()
{
this.Reset();
RollbarLoggerConfig config = this.ProvideLiveRollbarConfig() as RollbarLoggerConfig;
RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();
payloadManipulationOptions.Truncate = delegate (Payload payload)
{
throw new Exception("Buggy truncate delegate!");
};
config.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
using(IRollbar rollbar = this.ProvideDisposableRollbar())
{
rollbar.Configure(config);
rollbar.Critical("This message's Truncate will fail!");
this.VerifyInstanceOperational(rollbar);
// one more extra sanity check:
Assert.AreEqual(0, RollbarQueueController.Instance.GetTotalPayloadCount());
}
this.Reset();
}
/// <summary>
/// Enum TrickyPackage
/// </summary>
public enum TrickyPackage
{
/// <summary>
/// The asynchronous faulty package
/// </summary>
AsyncFaultyPackage,
/// <summary>
/// The synchronize faulty package
/// </summary>
SyncFaultyPackage,
/// <summary>
/// The asynchronous nothing package
/// </summary>
AsyncNothingPackage,
/// <summary>
/// The synchronize nothing package
/// </summary>
SyncNothingPackage,
}
/// <summary>
/// Trickies the package test.
/// </summary>
/// <param name="trickyPackage">The tricky package.</param>
[DataTestMethod]
[DataRow(TrickyPackage.AsyncFaultyPackage)]
[DataRow(TrickyPackage.SyncFaultyPackage)]
[DataRow(TrickyPackage.AsyncNothingPackage)]
[DataRow(TrickyPackage.SyncNothingPackage)]
public void TrickyPackageTest(TrickyPackage trickyPackage)
{
this.Reset();
IRollbarPackage package = null;
switch (trickyPackage)
{
case TrickyPackage.AsyncFaultyPackage:
package = new FaultyPackage(false);
break;
case TrickyPackage.SyncFaultyPackage:
package = new FaultyPackage(true);
break;
case TrickyPackage.AsyncNothingPackage:
package = new NothingPackage(false);
break;
case TrickyPackage.SyncNothingPackage:
package = new NothingPackage(true);
break;
default:
Assert.Fail($"Unexpected {nameof(trickyPackage)}: {trickyPackage}!");
break;
}
using (IRollbar rollbar = this.ProvideDisposableRollbar())
{
rollbar.Critical(package);
this.VerifyInstanceOperational(rollbar);
// one more extra sanity check:
Assert.AreEqual(0, RollbarQueueController.Instance.GetTotalPayloadCount());
}
this.Reset();
}
#endregion failure recovery tests
#region rate limiting tests
/// <summary>
/// Defines the test method RateLimitConfigSettingOverridesServerHeadersBasedReportingRateTest.
/// </summary>
[TestMethod]
public void RateLimitConfigSettingOverridesServerHeadersBasedReportingRateTest()
{
const int totalTestPayloads = 10;
const int localReportingRate = 30;
using (IRollbar rollbar = this.ProvideDisposableRollbar())
{
// using Rollbar API service enforced reporting rate:
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < totalTestPayloads; i++)
{
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("RateLimitConfigSettingOverridesServerHeadersBasedReportingRateTest");
}
sw.Stop();
TimeSpan serverRateDuration = sw.Elapsed;
// reconfigure with locally defined reporting rate:
//RollbarLoggerConfig rollbarConfig = new RollbarLoggerConfig();
//rollbarConfig.Reconfigure(rollbar.Config);
//Assert.IsFalse(rollbarConfig.RollbarInfrastructureOptions.MaxReportsPerMinute.HasValue);
Assert.IsFalse(RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxReportsPerMinute.HasValue);
RollbarInfrastructureOptions rollbarInfrastructureOptions = new RollbarInfrastructureOptions();
rollbarInfrastructureOptions.MaxReportsPerMinute = localReportingRate;
RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.Reconfigure(rollbarInfrastructureOptions);
Assert.IsTrue(RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxReportsPerMinute.HasValue);
Assert.AreEqual(localReportingRate, RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxReportsPerMinute.Value);
//rollbar.Config.Reconfigure(rollbarConfig);
//Assert.IsTrue(rollbar.Config.RollbarInfrastructureOptions.MaxReportsPerMinute.HasValue);
//Assert.AreEqual(localReportingRate, rollbar.Config.RollbarInfrastructureOptions.MaxReportsPerMinute.Value);
// using local config defined reporting rate:
sw.Restart();
for (int i = 0; i < totalTestPayloads; i++)
{
rollbar.AsBlockingLogger(TimeSpan.FromSeconds(3)).Critical("RateLimitConfigSettingOverridesServerHeadersBasedReportingRateTest");
}
sw.Stop();
TimeSpan localRateDuration = sw.Elapsed;
Assert.IsTrue(2 < (localRateDuration.TotalMilliseconds / serverRateDuration.TotalMilliseconds), "This is good enough confirmation of locally defined rate in action...");
}
this.IncrementCount<CommunicationEventArgs>(2 * totalTestPayloads);
}
#endregion rate limiting tests
[TestMethod]
public void ThrowsExceptionWhenInitializedWithInvalidConfigInstance()
{
RollbarLoggerConfig invalidConfig = new RollbarLoggerConfig(string.Empty);
invalidConfig.RollbarPayloadAdditionOptions.Person = new Person();
try
{
using var rollbar = RollbarFactory.CreateNew(invalidConfig);
}
catch (RollbarException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.ToString());
Assert.IsTrue(ex.Data.Count > 0, "Expected to contain failed validation rules!");
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.ToString());
Assert.Fail("Should never reach here due to exception above!");
}
Assert.Fail("Should never reach here due to exception above!");
}
[TestMethod]
public void ThrowsExceptionWhenConfiguredWithInvalidConfigInstance()
{
RollbarLoggerConfig invalidConfig = new RollbarLoggerConfig(string.Empty);
invalidConfig.RollbarPayloadAdditionOptions.Person = new Person();
var rollbar = RollbarFactory.CreateNew();
try
{
rollbar.Configure(invalidConfig);
}
catch (RollbarException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.ToString());
Assert.IsTrue(ex.Data.Count > 0, "Expected to contain failed validation rules!");
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.ToString());
Assert.Fail("Should never reach here due to exception above!");
}
Assert.Fail("Should never reach here due to exception above!");
}
//TODO: redo the test below to properly account for payload persistence in case of wrong proxy!!!
/// <summary>
/// Defines the test method AllowsProxySettingsReconfiguration.
/// </summary>
//[TestMethod]
//public void AllowsProxySettingsReconfiguration()
//{
// this.Reset();
// using (IRollbar logger = this.ProvideDisposableRollbar())
// {
// IRollbarConfig initialConfig = logger.Config;
// Assert.AreSame(initialConfig, logger.Config);
// logger.Configure(initialConfig);
// Assert.AreSame(initialConfig, logger.Config);
// int errorCount = 0;
// logger.AsBlockingLogger(TimeSpan.FromSeconds(3)).Info("test 1");
// this.IncrementCount<CommunicationEventArgs>();
// Assert.AreEqual(0, errorCount, "Checking errorCount 1.");
// RollbarConfig newConfig = new RollbarConfig("seed");
// newConfig.Reconfigure(initialConfig);
// Assert.AreNotSame(initialConfig, newConfig);
// logger.Configure(newConfig);
// logger.AsBlockingLogger(TimeSpan.FromSeconds(3)).Info("test 2");
// this.IncrementCount<CommunicationEventArgs>();
// Assert.AreEqual(0, errorCount, "Checking errorCount 2.");
// newConfig.ProxyAddress = "www.fakeproxy.com";
// newConfig.ProxyUsername = "fakeusername";
// newConfig.ProxyPassword = "fakepassword";
// logger.Configure(newConfig);
// Assert.IsFalse(string.IsNullOrEmpty(logger.Config.ProxyAddress));
// Assert.IsFalse(string.IsNullOrEmpty(logger.Config.ProxyUsername));
// Assert.IsFalse(string.IsNullOrEmpty(logger.Config.ProxyPassword));
// try
// {
// // the fake proxy settings will not cause a timeout exception here!
// // the payload will not be transmitted but persisted:
// int expectedFewcomMMerrors = 6; // this is a non-deterministic experimental value!
// while (expectedFewcomMMerrors-- > 0)
// {
// this.IncrementCount<CommunicationErrorEventArgs>();
// }
// logger.AsBlockingLogger(TimeSpan.FromSeconds(3)).Info("test 3 with fake proxy");
// }
// catch
// {
// errorCount++;
// }
// Assert.AreEqual(0, errorCount, "Checking errorCount 3.");
// //TODO: gain access to the payload store persisted records count.
// // The count is expected to be 1.
// newConfig.ProxyAddress = null;
// newConfig.ProxyUsername = null;
// newConfig.ProxyPassword = null;
// logger.Configure(newConfig);
// Assert.IsTrue(string.IsNullOrEmpty(logger.Config.ProxyAddress));
// Assert.IsTrue(string.IsNullOrEmpty(logger.Config.ProxyUsername));
// Assert.IsTrue(string.IsNullOrEmpty(logger.Config.ProxyPassword));
// try
// {
// // the fake proxy settings are gone, so, next call is expected to succeed:
// this.IncrementCount<CommunicationEventArgs>();
// logger.AsBlockingLogger(TimeSpan.FromSeconds(15)).Info("test 4");
// }
// catch
// {
// errorCount++;
// }
// Assert.AreEqual(0, errorCount, "Checking errorCount 4.");
// //TODO: gain access to the payload store persisted records count.
// // The count is expected to be 1 (one record stuck with wrfng proxy settings until stale in a few days).
// }
//}
/// <summary>
/// Defines the test method ImplementsIDisposable.
/// </summary>
[TestMethod]
public void ImplementsIDisposable()
{
using IRollbar logger = this.ProvideDisposableRollbar();
IDisposable disposable = logger as IDisposable;
Assert.IsNotNull(disposable);
}
/// <summary>
/// The maximum scoped instance test duration in millisec
/// </summary>
private const int maxScopedInstanceTestDurationInMillisec = 60 * 1000;
/// <summary>
/// Defines the test method ScopedInstanceTest.
/// </summary>
[TestMethod]
[Timeout(maxScopedInstanceTestDurationInMillisec)]
public void ScopedInstanceTest()
{
// we need to make sure we are starting clean:
RollbarQueueController.Instance.FlushQueues();
RollbarQueueController.Instance.Start();
var accessTokenQueues =
RollbarQueueController.Instance.GetQueues(RollbarUnitTestSettings.AccessToken);
while (accessTokenQueues.Any())
{
string msg = "Initial queues count: " + accessTokenQueues.Count();
System.Diagnostics.Trace.WriteLine(msg);
Console.WriteLine(msg);
foreach(var queue in accessTokenQueues)
{
msg = "---Payloads in a queue: " + queue.GetPayloadCount();
System.Diagnostics.Trace.WriteLine(msg);
Console.WriteLine(msg);
if(!queue.IsReleased)
{
queue.Release();
}
else
{
queue.Flush();
}
}
Thread.Sleep(TimeSpan.FromMilliseconds(250));
accessTokenQueues =
RollbarQueueController.Instance.GetQueues(RollbarUnitTestSettings.AccessToken);
}
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
int totalInitialQueues = RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);
using (var logger = RollbarFactory.CreateNew().Configure(loggerConfig))
{
Assert.AreEqual(totalInitialQueues + 1, RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken));
this.IncrementCount<CommunicationEventArgs>();
logger.Log(ErrorLevel.Error, "test message");
}
// an unused queue does not get removed immediately (but eventually) - so let's wait for it for a few processing cycles:
int currentQueuesCount =
RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);
while (totalInitialQueues != currentQueuesCount)
{
string msg = "Current queues count: " + currentQueuesCount + " while initial count was: " + totalInitialQueues;
System.Diagnostics.Trace.WriteLine(msg);
Console.WriteLine(msg);
Thread.Sleep(TimeSpan.FromMilliseconds(250));
currentQueuesCount =
RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken);
}
// if everything is good, we should get here way before this test method times out:
Assert.AreEqual(totalInitialQueues, RollbarQueueController.Instance.GetQueuesCount(RollbarUnitTestSettings.AccessToken));
}
/// <summary>
/// Defines the test method ReportException.
/// </summary>
[TestMethod]
public void ReportException()
{
using IRollbar logger = this.ProvideDisposableRollbar();
try
{
this.IncrementCount<CommunicationEventArgs>();
logger.AsBlockingLogger(defaultRollbarTimeout).Error(new System.Exception("test exception"));
}
catch
{
Assert.Fail("the execution should not reach here!");
}
}
/// <summary>
/// Defines the test method ReportFromCatch.
/// </summary>
[TestMethod]
public void ReportFromCatch()
{
try
{
var a = 10;
var b = 0;
var c = a / b;
}
catch (System.Exception ex)
{
using IRollbar logger = this.ProvideDisposableRollbar();
try
{
this.IncrementCount<CommunicationEventArgs>();
logger.AsBlockingLogger(defaultRollbarTimeout).Error(new System.Exception("outer exception",ex));
}
catch
{
Assert.Fail();
}
}
}
/// <summary>
/// Defines the test method ReportMessage.
/// </summary>
[TestMethod]
public void ReportMessage()
{
using IRollbar logger = this.ProvideDisposableRollbar();
try
{
this.IncrementCount<CommunicationEventArgs>();
logger.AsBlockingLogger(defaultRollbarTimeout).Log(ErrorLevel.Error,"test message");
}
catch(Exception ex)
{
Console.WriteLine(ex);
Assert.Fail("should never reach here!");
}
}
/// <summary>
/// Conveniences the methods use appropriate error levels.
/// </summary>
/// <param name="expectedLogLevel">The expected log level.</param>
[DataTestMethod]
[DataRow(ErrorLevel.Critical)]
[DataRow(ErrorLevel.Error)]
[DataRow(ErrorLevel.Warning)]
[DataRow(ErrorLevel.Info)]
[DataRow(ErrorLevel.Debug)]
public void ConvenienceMethodsUseAppropriateErrorLevels(ErrorLevel expectedLogLevel)
{
var awaitAsyncSend = new ManualResetEventSlim(false);
var acctualLogLevel = ErrorLevel.Info;
void Transform(Payload payload)
{
acctualLogLevel = payload.Data.Level.Value;
awaitAsyncSend.Set();
}
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();
payloadManipulationOptions.Transform = Transform;
loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
this.IncrementCount<CommunicationEventArgs>();
using (var logger = RollbarFactory.CreateNew().Configure(loggerConfig))
{
try
{
//TODO: implement and add SynchronousPackage around the payload object!!!
var ex = new Exception();
switch (expectedLogLevel)
{
case ErrorLevel.Critical:
logger.Critical(ex);
break;
case ErrorLevel.Error:
logger.Error(ex);
break;
case ErrorLevel.Warning:
logger.Warning(ex);
break;
case ErrorLevel.Info:
logger.Info(ex);
break;
case ErrorLevel.Debug:
logger.Debug(ex);
break;
}
}
catch
{
Assert.Fail("should never reach here!");
}
}
awaitAsyncSend.Wait();
Assert.AreEqual(expectedLogLevel, acctualLogLevel);
}
/// <summary>
/// Defines the test method LongReportIsAsync.
/// </summary>
[TestMethod]
public void LongReportIsAsync()
{
const int maxCallLengthInMillisec = 50;
TimeSpan payloadSubmissionDelay = TimeSpan.FromMilliseconds(3 * maxCallLengthInMillisec);
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();
payloadManipulationOptions.Transform = delegate
{
Thread.Sleep(payloadSubmissionDelay);
};
loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
using IRollbar logger = RollbarFactory.CreateNew().Configure(loggerConfig);
try
{
this.IncrementCount<CommunicationEventArgs>();
Stopwatch sw = Stopwatch.StartNew();
logger.Log(ErrorLevel.Error,"test message");
sw.Stop();
Assert.IsTrue(sw.ElapsedMilliseconds < maxCallLengthInMillisec);
Thread.Sleep(payloadSubmissionDelay);
}
catch
{
Assert.Fail("should never get here!");
}
}
/// <summary>
/// Defines the test method ExceptionWhileTransformingPayloadAsync.
/// </summary>
[TestMethod]
[Timeout(5000)]
public void ExceptionWhileTransformingPayloadAsync()
{
this._transformException = false;
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
RollbarPayloadManipulationOptions payloadManipulationOptions = new RollbarPayloadManipulationOptions();
payloadManipulationOptions.Transform = delegate {
throw new NullReferenceException();
};
loggerConfig.RollbarPayloadManipulationOptions.Reconfigure(payloadManipulationOptions);
using IRollbar logger = RollbarFactory.CreateNew().Configure(loggerConfig);
logger.InternalEvent += Logger_InternalEvent;
try
{
this.IncrementCount<CommunicationEventArgs>();
logger.Log(ErrorLevel.Error,"test message");
}
catch
{
logger.InternalEvent -= Logger_InternalEvent;
Assert.Fail("should never get here!");
throw;
}
this._signal.Wait();
logger.InternalEvent -= Logger_InternalEvent;
Assert.IsTrue(this._transformException);
}
/// <summary>
/// The transform exception
/// </summary>
private bool _transformException = false;
/// <summary>
/// The signal
/// </summary>
private readonly SemaphoreSlim _signal = new SemaphoreSlim(0, 1);
/// <summary>
/// Handles the InternalEvent event of the Logger control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RollbarEventArgs"/> instance containing the event data.</param>
private void Logger_InternalEvent(object sender, RollbarEventArgs e)
{
this._transformException = true;
this._signal.Release();
}
#region Stress test
/// <summary>
/// Defines the test method MultithreadedStressTest_BlockingLogs.
/// </summary>
[TestMethod]
[Timeout(120000)]
public void MultithreadedStressTest_BlockingLogs()
{
RollbarLoggerFixture.stressLogsCount = 0;
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
RollbarInfrastructureOptions infrastructureOptions = new RollbarInfrastructureOptions();
infrastructureOptions.ReportingQueueDepth = 200;
RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.Reconfigure(infrastructureOptions);
this.IncrementCount<CommunicationEventArgs>(RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.ReportingQueueDepth);
TimeSpan rollbarBlockingTimeout = TimeSpan.FromMilliseconds(55000);
List<IRollbar> rollbars =
new List<IRollbar>(MultithreadedStressTestParams.TotalThreads);
List<ILogger> loggers = new List<ILogger>(MultithreadedStressTestParams.TotalThreads);
for (int i = 0; i < MultithreadedStressTestParams.TotalThreads; i++)
{
var rollbar = RollbarFactory.CreateNew().Configure(loggerConfig);
loggers.Add(rollbar.AsBlockingLogger(rollbarBlockingTimeout));
rollbars.Add(rollbar);
}
PerformTheMultithreadedStressTest(loggers.ToArray());
rollbars.ForEach(r => {
r.Dispose();
});
}
/// <summary>
/// Defines the test method MultithreadedStressTest_ConnectivityMonitorDisabled.
/// </summary>
//[TestMethod]
//[Timeout(60000)]
//public void MultithreadedStressTest_ConnectivityMonitorDisabled()
//{
// ConnectivityMonitor.Instance.Disable();
// MultithreadedStressTest();
//}
/// <summary>
/// Defines the test method MultithreadedStressTest.
/// </summary>
[TestMethod]
[Timeout(100000)]
public void MultithreadedStressTest()
{
RollbarLoggerFixture.stressLogsCount = 0;
//ConnectivityMonitor.Instance.Disable();
RollbarDestinationOptions destinationOptions =
new RollbarDestinationOptions(
RollbarUnitTestSettings.AccessToken,
RollbarUnitTestSettings.Environment
);
RollbarLoggerConfig loggerConfig = new RollbarLoggerConfig();
loggerConfig.RollbarDestinationOptions.Reconfigure(destinationOptions);
RollbarInfrastructureOptions infrastructureOptions = new RollbarInfrastructureOptions();
infrastructureOptions.ReportingQueueDepth = 200;
RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.Reconfigure(infrastructureOptions);
this.IncrementCount<CommunicationEventArgs>(RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.ReportingQueueDepth);
List<IRollbar> rollbars =
new List<IRollbar>(MultithreadedStressTestParams.TotalThreads);
for (int i = 0; i < MultithreadedStressTestParams.TotalThreads; i++)
{
var rollbar = RollbarFactory.CreateNew().Configure(loggerConfig);
rollbars.Add(rollbar);
}
PerformTheMultithreadedStressTest(rollbars.ToArray());
rollbars.ForEach(r => {
r.Dispose();
});
}
/// <summary>
/// Performs the multithreaded stress test.
/// </summary>
/// <param name="loggers">The loggers.</param>
private static void PerformTheMultithreadedStressTest(ILogger[] loggers)
{
//first let's make sure the controller queues are not populated by previous tests:
RollbarQueueController.Instance.FlushQueues();
RollbarQueueController.Instance.InternalEvent += RollbarStress_InternalEvent;
List<Task> tasks =
new List<Task>(MultithreadedStressTestParams.TotalThreads);
for (int t = 0; t < MultithreadedStressTestParams.TotalThreads; t++)
{
var task = new Task((state) =>
{
int taskIndex = (int)state;
TimeSpan sleepIntervalDelta =
TimeSpan.FromTicks(taskIndex * MultithreadedStressTestParams.LogIntervalDelta.Ticks);
var logger = loggers[taskIndex];
int i = 0;
while (i < MultithreadedStressTestParams.LogsPerThread)
{
var customFields = new Dictionary<string, object>(Fields.FieldsCount)
{
[Fields.ThreadID] = taskIndex + 1,
[Fields.ThreadLogID] = i + 1,
[Fields.Timestamp] = DateTimeOffset.UtcNow
};
logger.Info(
//$"{customFields[Fields.Timestamp]} Stress test: thread #{customFields[Fields.ThreadID]}, log #{customFields[Fields.ThreadLogID]}"
"Stress test"
, customFields
);
Thread.Sleep(MultithreadedStressTestParams.LogIntervalBase.Add(sleepIntervalDelta));
i++;
}
}
, t
);
tasks.Add(task);
}
tasks.ForEach(t => t.Start());
Task.WaitAll(tasks.ToArray());
int expectedCount =
MultithreadedStressTestParams.TotalThreads * MultithreadedStressTestParams.LogsPerThread;
//we need this delay loop for async logs:
while (RollbarQueueController.Instance.GetTotalPayloadCount() > 0)
{
Thread.Sleep(TimeSpan.FromMilliseconds(50));
}
Thread.Sleep(TimeSpan.FromSeconds(10));
RollbarQueueController.Instance.InternalEvent -= RollbarStress_InternalEvent;
Assert.AreEqual(expectedCount, RollbarLoggerFixture.stressLogsCount, "Matching stressLogsCount");
}
/// <summary>
/// The stress logs count
/// </summary>
private static int stressLogsCount = 0;
/// <summary>
/// Handles the InternalEvent event of the RollbarStress control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RollbarEventArgs"/> instance containing the event data.</param>
private static void RollbarStress_InternalEvent(object sender, RollbarEventArgs e)
{
if (e is CommunicationEventArgs)
{
Interlocked.Increment(ref RollbarLoggerFixture.stressLogsCount);
}
else
{
}
}
/// <summary>
/// Class MultithreadedStressTestParams.
/// </summary>
private static class MultithreadedStressTestParams
{
/// <summary>
/// The total threads
/// </summary>
public const int TotalThreads = 20;
/// <summary>
/// The logs per thread
/// </summary>
public const int LogsPerThread = 10;
/// <summary>
/// The log interval delta
/// </summary>
public static readonly TimeSpan LogIntervalDelta =
TimeSpan.FromMilliseconds(10);
/// <summary>
/// The log interval base
/// </summary>
public static readonly TimeSpan LogIntervalBase =
TimeSpan.FromMilliseconds(20);
}
/// <summary>
/// Class Fields.
/// </summary>
private static class Fields
{
/// <summary>
/// The fields count
/// </summary>
public const int FieldsCount = 3;
/// <summary>
/// The timestamp
/// </summary>
public const string Timestamp = "stress.timestamp";
/// <summary>
/// The thread identifier
/// </summary>
public const string ThreadID = "stress.thread.id";
/// <summary>
/// The thread log identifier
/// </summary>
public const string ThreadLogID = "stress.thread.log.id";
}
#endregion Stress test
//[TestMethod]
//public void _RollbarRateLimitVerification()
//{
// RollbarConfig config = this.ProvideLiveRollbarConfig() as RollbarConfig;
// int count = 0;
// using (IRollbar rollbar = this.ProvideDisposableRollbar())
// {
// rollbar.Configure(config);
// while (count++ < 300)
// {
// rollbar.Critical("RollbarRateLimitVerification test");
// Thread.Sleep(TimeSpan.FromSeconds(1));
// }
// }
//}
}
}
| {
"content_hash": "cb3f924e4371dcf0304afd576e25e3da",
"timestamp": "",
"source": "github",
"line_count": 1070,
"max_line_length": 185,
"avg_line_length": 40.0588785046729,
"alnum_prop": 0.5743881669505168,
"repo_name": "rollbar/Rollbar.NET",
"id": "1b0cbaa3a7032da434868a16b69f28a549c67def",
"size": "42863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UnitTest.Rollbar/RollbarLoggerFixture.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "69"
},
{
"name": "C#",
"bytes": "1485180"
},
{
"name": "PowerShell",
"bytes": "8767"
}
],
"symlink_target": ""
} |
import {suite, test, timeout} from "mocha-typescript";
import {expect} from 'chai';
import {Injector} from "../../src/injector/Injector";
import {CustomModel} from "./data/CustomModel";
import {CustomModel2} from "./data/CustomModel2";
import {CustomModelWithInject} from "./data/CustomModelWithInject";
import {CustomExtendedModel} from "./data/CustomExtendedModel";
import {ClassWithInjections} from "../metadata/data/ClassWithInjections";
import {InjectionMapping} from "../../src/injector/data/InjectionMapping";
import {CustomModelWithPostConstruct} from "./data/CustomModelWithPostConstruct";
import {AbstractClass} from "./data/AbstractClass";
import {AbstractClassImpl} from "./data/AbstractClassImpl";
/**
* Injector test suite
* @author Kristaps Peļņa
*/
@suite export class InjectorTest {
private injector:Injector;
before() {
this.injector = new Injector();
}
after() {
CustomModelWithInject.onDestroy = null;
if (!this.injector) {
return;
}
expect(
() => this.injector.destroy(),
"Injector destroy should not cause any errors"
).to.not.throw(Error);
this.injector = null;
}
@test("Get self")
get() {
expect(
this.injector.get(Injector),
"injector.get(Injector) should return itself"
).to.be.eq(this.injector);
}
@test("Get unavailable type")
getUnavailableType() {
expect(
() => this.injector.get(CustomModel),
"Accessing an unavailable type should cause an error"
).to.throw(Error);
}
@test("Map")
map() {
this.injector.map(CustomModel);
let model:CustomModel = this.injector.get(CustomModel);
expect(
model,
"Mapped model should be available from injector"
).to.not.be.null;
expect(
this.injector.get(CustomModel),
"Each returned model instance should be unique"
).to.not.be.eq(model);
}
@test("Map as singleton")
mapAsSingleton() {
this.injector.map(CustomModel).asSingleton();
let model:CustomModel = this.injector.get(CustomModel);
expect(
model,
"Mapped model should be available from injector"
).to.not.be.null;
expect(
this.injector.get(CustomModel),
"Model mapped as singleton should return the same instance"
).to.be.eq(model);
}
@test("Map to singleton")
mapToSingleton() {
this.injector.map(CustomModel2).toSingleton(CustomModel);
expect(
this.injector.get(CustomModel2),
"CustomModel2 mapped to CustomModel should return instance of CustomModel"
).to.be.instanceof(CustomModel);
}
@test("Map to type")
mapToType() {
this.injector.map(CustomModel2).toType(CustomModel);
expect(
this.injector.get(CustomModel2),
"CustomModel2 mapped to CustomModel should return instance of CustomModel"
).to.be.instanceof(CustomModel);
}
@test("Map to value")
mapToValue() {
let model:CustomModel = new CustomModel();
model.value = 999;
this.injector.map(CustomModel).toValue(model);
expect(
this.injector.get(CustomModel),
"Mapped model should be available from injector"
).to.not.be.null;
expect(
this.injector.get(CustomModel),
"Model mapped as value should return the same mapped instance"
).to.be.eq(model);
}
@test("Map to existing")
mapToExisting() {
this.injector.map(CustomModel).asSingleton();
this.injector.map(CustomModel2).toExisting(CustomModel);
expect(
this.injector.get(CustomModel2),
"Mapped model should be available from injector"
).to.not.be.null;
expect(
this.injector.get(CustomModel2),
"Model mapped as existing should return the same mapping as for the existing mapping"
).to.be.eq(this.injector.get(CustomModel));
}
@test("Map by abstract class")
mapByAbstractClass() {
this.injector.map(AbstractClass).toType(AbstractClassImpl);
expect(
this.injector.get(AbstractClass),
"Abstract class should be usable as mapping key"
).to.be.instanceof(AbstractClassImpl);
}
@test("Create subInjector")
createSubInjector() {
let subInjector:Injector = this.injector.createSubInjector();
subInjector.map(CustomModel).asSingleton();
expect(
subInjector.parent,
"SubInjector parent should be the original injector"
).to.be.eq(this.injector);
expect(
this.injector.hasMapping(CustomModel),
"SubInjector mappings should not be available from the parent injector"
).to.be.false;
}
@test("Has mapping")
hasMapping() {
this.injector.map(CustomModel).asSingleton();
expect(
this.injector.hasMapping(CustomModel),
"Mapped model should have a mapping"
).to.be.true;
expect(
this.injector.hasDirectMapping(CustomModel),
"Mapped model should have a direct mapping"
).to.be.true;
}
@test("Has direct mapping")
hasDirectMapping() {
let subInjector:Injector = this.injector.createSubInjector();
this.injector.map(CustomModel).asSingleton();
expect(
subInjector.hasMapping(CustomModel),
"Mapped model should be available from the subInject"
).to.be.true;
expect(
subInjector.hasDirectMapping(CustomModel),
"Mapped model should not be a direct mapping as it is mapped to the parent injector"
).to.be.false;
}
@test("unMap")
unMap() {
this.injector.map(CustomModel).asSingleton();
expect(
this.injector.hasMapping(CustomModel),
"Mapped model should be available from the injector"
).to.be.true;
this.injector.unMap(CustomModel);
expect(
this.injector.hasMapping(CustomModel),
"Model should no longer have a mapping after unMap"
).to.be.false;
expect(
() => this.injector.get(CustomModel),
"Accessing an unMapped model should cause an error"
).to.throw(Error);
}
@test("Seal")
seal() {
const mapping:InjectionMapping = this.injector.map(CustomModel);
mapping.seal();
expect(
() => mapping.asSingleton(),
"Changing sealed mappings should throw an error"
).to.throw(Error);
}
@test("Unseal")
unseal() {
const mapping:InjectionMapping = this.injector.map(CustomModel);
expect(
() => mapping.unseal(null),
"Trying to unseal a not sealed mapping should throw an error"
).to.throw(Error);
mapping.seal();
expect(
() => mapping.unseal(null),
"Trying to unseal a mapping with an incorrect key should throw an error"
).to.throw(Error);
}
@test("Remapping")
remapping() {
const mapping:InjectionMapping = this.injector.map(CustomModel2).asSingleton();
expect(
() => mapping.toValue(new CustomModel()),
"Remapping should not throw an error"
).to.not.throw(Error);
}
@test("Instantiate instance")
instantiateInstance() {
let model:any = this.injector.instantiateInstance(CustomModel);
expect(
model,
"Instantiated instance should not be null"
).to.not.be.null;
expect(
model instanceof CustomModel,
"Instantiated instance should match the class"
).to.not.be.null;
}
@test("Inject Into")
@timeout(500) //Limit waiting time in case the callback is not called
injectInto(done:() => void) {
expect(
() => this.injector.injectInto(new ClassWithInjections()),
"An error should be thrown because the injections can not be provided"
).to.throw(Error);
ClassWithInjections.onPostConstruct = done;
this.injector.map(CustomModel);
expect(
() => this.injector.injectInto(new ClassWithInjections()),
"An error should not be thrown because the injections can be provided"
).to.not.throw(Error);
}
@test("Property injections")
propertyInjections() {
let model:CustomModelWithInject = this.injector.instantiateInstance(CustomModelWithInject);
expect(
model.injector,
"Instantiated instance should have their Inject() properties filled"
).to.not.be.undefined;
let extendedModel:CustomExtendedModel = this.injector.instantiateInstance(CustomExtendedModel);
expect(
extendedModel.injector,
"Extended instances should have inherited Inject() properties filled"
).to.not.be.undefined;
}
@test("Destroy mapping")
destroyMapping() {
const mapping:InjectionMapping = this.injector.map(CustomModel);
expect(
() => mapping.destroy(),
"Destroying a mapping should work"
).to.not.throw(Error);
expect(
() => mapping.destroy(),
"Double destroying a mapping should throw an error"
).to.throw(Error);
expect(
() => mapping.asSingleton(),
"Changing mapping providers after destroy should throw an error"
).to.throw(Error);
expect(
() => mapping.getInjectedValue(),
"Accessing getInjectedValue destroy should throw an error"
).to.throw(Error);
}
@test("Destroy instance")
@timeout(500) //Limit waiting time in case the callback is not called
destroyInstance(done:() => void) {
let model:CustomModelWithInject = this.injector.instantiateInstance(CustomModelWithInject);
CustomModelWithInject.onDestroy = done;
this.injector.destroyInstance(model);
}
@test("Destroy instance without metadata")
destroyInstanceWithoutMetadata() {
this.injector.destroyInstance({});
}
@test("Destroy injector")
destroyInjector(done:() => void) {
this.injector.map(CustomModelWithInject).asSingleton();
this.injector.get(CustomModelWithInject);
CustomModelWithInject.onDestroy = done;
this.injector.destroy();
const methods:Function[] = [
() => this.injector.createSubInjector(),
() => this.injector.map(null),
() => this.injector.unMap(null),
() => this.injector.hasDirectMapping(null),
() => this.injector.hasMapping(null),
() => this.injector.getMapping(null),
() => this.injector.get(null),
() => this.injector.instantiateInstance(null),
() => this.injector.injectInto(null),
() => this.injector.destroyInstance(null)
];
for (let method of methods) {
expect(
method,
"Accessing a destroyed injector functionality should throw an error"
).to.throw(Error);
}
this.injector = null;
}
@test("Double destroy injector")
doubleDestroyInjector() {
this.injector.destroy();
expect(
() => this.injector.destroy(),
"Trying to destroy a destroyed injector should throw an error"
).to.throw(Error);
this.injector = null;
}
@test("Instance must be available in Injector before @PostConstruct is invoked")
@timeout(10)
isInstanceInInjectorOnPostConstruct(done:() => void) {
this.injector.map(CustomModelWithPostConstruct).asSingleton();
let instance:CustomModelWithPostConstruct;
CustomModelWithPostConstruct.onPostConstruct = () => {
expect(
this.injector.get(CustomModelWithPostConstruct),
"Injection must be available in Injector before postConstruct is invoked"
).to.be.eq(instance);
done();
};
instance = this.injector.get(CustomModelWithPostConstruct);
}
} | {
"content_hash": "3347a8ca1e1cd3b9d550b48be6f31ba0",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 103,
"avg_line_length": 30.649382716049384,
"alnum_prop": 0.6038024651574961,
"repo_name": "kristapsPelna/Quiver-Framework",
"id": "cfd5bd9fd5cfd60887df7d7eebf54b92380c3355",
"size": "12415",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "test/injector/InjectorTest.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1362"
},
{
"name": "TypeScript",
"bytes": "172193"
}
],
"symlink_target": ""
} |
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.emr import EmrHook
from airflow.utils.decorators import apply_defaults
class EmrCreateJobFlowOperator(BaseOperator):
"""
Creates an EMR JobFlow, reading the config from the EMR connection.
A dictionary of JobFlow overrides can be passed that override
the config from the connection.
:param aws_conn_id: aws connection to uses
:type aws_conn_id: str
:param emr_conn_id: emr connection to use
:type emr_conn_id: str
:param job_flow_overrides: boto3 style arguments to override
emr_connection extra. (templated)
:type job_flow_overrides: dict
"""
template_fields = ['job_flow_overrides']
template_ext = ()
ui_color = '#f9c915'
@apply_defaults
def __init__(
self,
aws_conn_id='aws_default',
emr_conn_id='emr_default',
job_flow_overrides=None,
region_name=None,
*args, **kwargs):
super().__init__(*args, **kwargs)
self.aws_conn_id = aws_conn_id
self.emr_conn_id = emr_conn_id
if job_flow_overrides is None:
job_flow_overrides = {}
self.job_flow_overrides = job_flow_overrides
self.region_name = region_name
def execute(self, context):
emr = EmrHook(aws_conn_id=self.aws_conn_id,
emr_conn_id=self.emr_conn_id,
region_name=self.region_name)
self.log.info(
'Creating JobFlow using aws-conn-id: %s, emr-conn-id: %s',
self.aws_conn_id, self.emr_conn_id
)
response = emr.create_job_flow(self.job_flow_overrides)
if not response['ResponseMetadata']['HTTPStatusCode'] == 200:
raise AirflowException('JobFlow creation failed: %s' % response)
else:
self.log.info('JobFlow with id %s created', response['JobFlowId'])
return response['JobFlowId']
| {
"content_hash": "ab7a3dd345cea56188e9310b81b9909f",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 78,
"avg_line_length": 36.142857142857146,
"alnum_prop": 0.6230237154150198,
"repo_name": "spektom/incubator-airflow",
"id": "c7d562d5a1edb2a2d7ce3c16364a15673ac83cf0",
"size": "2811",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "airflow/providers/amazon/aws/operators/emr_create_job_flow.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13715"
},
{
"name": "Dockerfile",
"bytes": "17179"
},
{
"name": "HTML",
"bytes": "148492"
},
{
"name": "JavaScript",
"bytes": "25233"
},
{
"name": "Jupyter Notebook",
"bytes": "2933"
},
{
"name": "Mako",
"bytes": "1339"
},
{
"name": "Python",
"bytes": "9768581"
},
{
"name": "Shell",
"bytes": "221415"
},
{
"name": "TSQL",
"bytes": "879"
}
],
"symlink_target": ""
} |
package com.pablodomingos.classes.rps.servicos;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("ListaMensagemRetorno")
public class ListaMensagemRetorno {
@XStreamImplicit
private List<MensagemRetorno> mensagemRetorno = new ArrayList<>();
public List<MensagemRetorno> getMensagemRetorno() {
return mensagemRetorno;
}
public void setMensagemRetorno(List<MensagemRetorno> mensagemRetorno) {
this.mensagemRetorno = mensagemRetorno;
}
@Override
public String toString() {
if (this.getMensagemRetorno() != null) {
List<String> mensagens = this.getMensagemRetorno().stream().map(MensagemRetorno::toString)
.collect(Collectors.toList());
return mensagens.stream().map(m -> m.toString()).collect(Collectors.joining("|"));
}
return null;
}
}
| {
"content_hash": "0636536e6427a979dfa101f259efa524",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 96,
"avg_line_length": 28.647058823529413,
"alnum_prop": 0.7474332648870636,
"repo_name": "pablopdomingos/nfse",
"id": "a6b4d8ea2c67b69b480037d8c3ef2ce48f954bda",
"size": "974",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nfse-bh/src/main/java/com/pablodomingos/classes/rps/servicos/ListaMensagemRetorno.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "197402"
}
],
"symlink_target": ""
} |
import * as ActionTypes from '../actions'
import { updateObject, createReducer } from './reducerUtilities'
import { fillArray, getMaxDomain } from '../helpers'
// import d3 from 'd3'
import chroma from 'chroma-js'
// case reducers
import {GRPBYCOLORSBASE, GRADIATIONFXNS} from '../constants/AppConstants'
function updateData (state, action) {
if (action.response.query) {
return updateObject(state, {
chartData: action.response.query.originalData || [],
transformedChartData: action.response.query.data,
isFetching: false,
groupKeys: action.response.query.groupKeys,
domainMax: action.response.query.domainMax,
rollupBy: action.response.query.rollupBy,
})
} else {
return state
}
}
function changeChartType (state, action) {
if(Object.keys(state).indexOf('groupKeys') > -1 ) {
if(state.groupKeys.length > 0){
return updateObject(state, {
chartType: action.chartType,
domainMax: getMaxDomain(state.chartData, true, action.chartType)
})
}
}
return updateObject(state, {
chartType: action.chartType,
domainMax: getMaxDomain(state.chartData, false, action.chartType)
})
}
function setDefaultChartType (state, action) {
return updateObject(state, {
chartType: action.chartType,
chartColor: "#2196f3"
})
}
function resetState (state, action) {
return {}
}
function changeRollUpBy (state, action) {
return updateObject(state, {
rollupBy: action.payload
})
}
/*
function clearData (state, action) {
return updateObject(state, {
chartData: [],
isFetching: true,
groupKeys: []
})
}
*/
export const isGroupByz = (groupByKeys) => {
let isGroupBy = false
if (groupByKeys) {
if (groupByKeys.length > 1) {
isGroupBy = true
}
}
//if(isGroupBy && groupKeys.length === 1){
// isGroupBy = false
//}
return isGroupBy
}
export const isSelectedColDate = (selectedColumnDef) => {
if( typeof selectedColumnDef !== 'undefined' && selectedColumnDef){
if (selectedColumnDef.type === 'date') {
return true
}
}
return false
}
function setColorSteps(gradiationFxn, step) {
let groupColors = GRPBYCOLORSBASE.map(function(color){
let cl = chroma(color)
let colorItem = gradiationFxn(cl, step)
return colorItem
})
return groupColors
}
function makeColors(groupColors, step){
Object.keys(GRADIATIONFXNS).forEach(function(gradientFxnKey){
let groupColorsStep = setColorSteps(GRADIATIONFXNS[gradientFxnKey], step)
groupColors = groupColors.concat(groupColorsStep)
})
return groupColors
}
export const setGroupByColorScale = (chartColor, chartData, isGroupBy) => {
let groupColors = GRPBYCOLORSBASE
if(chartData.length > 0){
if(isGroupBy){
if(Object.keys(chartData[0]).length < GRPBYCOLORSBASE.length){
return GRPBYCOLORSBASE
}else{
let step = 1
while ( groupColors.length < Object.keys(chartData[0]).length){
//console.log(step)
//console.log("** here chart data****")
//console.log(Object.keys(chartData[0]).length)
//console.log("** grp colors****")
//console.log(groupColors.length)
//console.log("****** here ****")
groupColors = groupColors.concat(makeColors(groupColors,step))
//console.log("** here chart data 2****")
//console.log(Object.keys(chartData[0]).length)
//console.log("** grp colors 2****")
//console.log(groupColors.length)
//console.log("****** here agai ****")
step = step + 1
//console.log(step)
}
//console.log("** returning colors***")
//console.log(groupColors)
return groupColors
}
}
}
return []
}
export const setXAxisTickInterval = (chartData) => {
let xAxisInterval
if(chartData){
xAxisInterval = Math.round(chartData.length * 0.09)
}
return xAxisInterval
}
export const explodeFrequencies = (chartData, chartType) => {
let freqs = []
if(chartData.length > 0 && chartType === 'histogram') {
chartData.forEach(function (el) {
// function fillArray (value, len, arr)
freqs = fillArray(Number(el.key), Number(el.value), freqs)
})
}
return freqs
}
export const rollUpChartData = (query,chartType, chartData) => {
let rollupBy = false
if(Object.keys(query).indexOf('rollupBy') > -1 ) {
rollupBy = query.rollupBy
}
else if (chartType && chartData){
if((chartType === 'bar') && (chartData.length > 12) && !rollupBy) {
rollupBy = 'other'
}else{
rollupBy = 'none'
}
}else{
rollupBy = 'none'
}
return rollupBy
}
// slice reducer - chart
export const chartReducer = createReducer({}, {
[ActionTypes.METADATA_REQUEST]: resetState,
[ActionTypes.DATA_SUCCESS]: updateData,
[ActionTypes.CHANGE_ROLLUPBY]: changeRollUpBy,
[ActionTypes.APPLY_CHART_TYPE]: changeChartType,
[ActionTypes.SET_DEFAULT_CHARTTYPE]: setDefaultChartType,
})
export default chartReducer
| {
"content_hash": "e60db472c9b6053af755de8ed5d0f560",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 77,
"avg_line_length": 26.151041666666668,
"alnum_prop": 0.6512646883091018,
"repo_name": "DataSF/open-data-explorer",
"id": "6764d17c8e475834949daa621576c1615574f3ea",
"size": "5021",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/reducers/chartReducer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "95809"
},
{
"name": "HTML",
"bytes": "1492"
},
{
"name": "JavaScript",
"bytes": "363000"
},
{
"name": "Shell",
"bytes": "3782"
}
],
"symlink_target": ""
} |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Page
{
/// <summary>
/// Reloads given page optionally ignoring the cache.
/// </summary>
[Command(ProtocolName.Page.Reload)]
[SupportedBy("Chrome")]
public class ReloadCommand: ICommand<ReloadCommandResponse>
{
/// <summary>
/// Gets or sets If true, browser cache is ignored (as if the user pressed Shift+refresh).
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public bool? IgnoreCache { get; set; }
/// <summary>
/// Gets or sets If set, the script will be injected into all frames of the inspected page after reload.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string ScriptToEvaluateOnLoad { get; set; }
}
}
| {
"content_hash": "4ceb706343944d5d6fe5538d5b01586b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 106,
"avg_line_length": 33.34615384615385,
"alnum_prop": 0.7381776239907728,
"repo_name": "MasterDevs/ChromeDevTools",
"id": "c118b96c5eb61091e677e7751132b962c72378f3",
"size": "867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/ChromeDevTools/Protocol/Chrome/Page/ReloadCommand.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1135040"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Thu Apr 28 18:37:58 UTC 2016 -->
<title>Uses of Class org.apache.cassandra.exceptions.WriteFailureException (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.exceptions.WriteFailureException (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/exceptions/WriteFailureException.html" title="class in org.apache.cassandra.exceptions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/exceptions/class-use/WriteFailureException.html" target="_top">Frames</a></li>
<li><a href="WriteFailureException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.exceptions.WriteFailureException" class="title">Uses of Class<br>org.apache.cassandra.exceptions.WriteFailureException</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/cassandra/exceptions/WriteFailureException.html" title="class in org.apache.cassandra.exceptions">WriteFailureException</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.cassandra.service">org.apache.cassandra.service</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.cassandra.service">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/cassandra/exceptions/WriteFailureException.html" title="class in org.apache.cassandra.exceptions">WriteFailureException</a> in <a href="../../../../../org/apache/cassandra/service/package-summary.html">org.apache.cassandra.service</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/cassandra/service/package-summary.html">org.apache.cassandra.service</a> that throw <a href="../../../../../org/apache/cassandra/exceptions/WriteFailureException.html" title="class in org.apache.cassandra.exceptions">WriteFailureException</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">AbstractWriteResponseHandler.</span><code><strong><a href="../../../../../org/apache/cassandra/service/AbstractWriteResponseHandler.html#get()">get</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">StorageProxy.</span><code><strong><a href="../../../../../org/apache/cassandra/service/StorageProxy.html#mutate(java.util.Collection, org.apache.cassandra.db.ConsistencyLevel)">mutate</a></strong>(java.util.Collection<? extends <a href="../../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>> mutations,
<a href="../../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a> consistency_level)</code>
<div class="block">Use this method to have these Mutations applied
across all replicas.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">StorageProxy.</span><code><strong><a href="../../../../../org/apache/cassandra/service/StorageProxy.html#mutateWithTriggers(java.util.Collection, org.apache.cassandra.db.ConsistencyLevel, boolean)">mutateWithTriggers</a></strong>(java.util.Collection<? extends <a href="../../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>> mutations,
<a href="../../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a> consistencyLevel,
boolean mutateAtomically)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/exceptions/WriteFailureException.html" title="class in org.apache.cassandra.exceptions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/exceptions/class-use/WriteFailureException.html" target="_top">Frames</a></li>
<li><a href="WriteFailureException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "c0948c50f92648df87651ab826a5cfae",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 447,
"avg_line_length": 46.94117647058823,
"alnum_prop": 0.6590225563909774,
"repo_name": "elisska/cloudera-cassandra",
"id": "7faabc97987913f6b15f0bc02f3ebbffeb0db473",
"size": "7980",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DATASTAX_CASSANDRA-2.2.6/javadoc/org/apache/cassandra/exceptions/class-use/WriteFailureException.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "75145"
},
{
"name": "CSS",
"bytes": "4112"
},
{
"name": "HTML",
"bytes": "331372"
},
{
"name": "PowerShell",
"bytes": "77673"
},
{
"name": "Python",
"bytes": "979128"
},
{
"name": "Shell",
"bytes": "143685"
},
{
"name": "Thrift",
"bytes": "80564"
}
],
"symlink_target": ""
} |
@interface HtmlElement_Span : UIView
@end
#endif // #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
| {
"content_hash": "c3c27019473268659851d71d1aec0bf9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 59,
"avg_line_length": 25.75,
"alnum_prop": 0.7281553398058253,
"repo_name": "xuzhenguo/samurai-native",
"id": "35cad6f9cbef80e6b49a21a55085c4bae0386ea6",
"size": "1719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samurai-framework/samurai-ui/extension-html/element/HtmlElement_Span.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "30502"
},
{
"name": "CSS",
"bytes": "91285"
},
{
"name": "Groff",
"bytes": "857"
},
{
"name": "HTML",
"bytes": "3746840"
},
{
"name": "JavaScript",
"bytes": "22922"
},
{
"name": "Objective-C",
"bytes": "2754680"
}
],
"symlink_target": ""
} |
import React from 'react';
import ReactDOM from 'react-dom';
import Demo from './Demo';
ReactDOM.render(
<Demo />,
document.querySelector('#app')
);
| {
"content_hash": "662b5df890a23bc5449a1878a1ad6a15",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 33,
"avg_line_length": 15.6,
"alnum_prop": 0.6794871794871795,
"repo_name": "milk-ui/generator-milk",
"id": "6b35f88e39b8567ab5d4b3c7695e25147e52a28f",
"size": "280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/demo/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "915"
},
{
"name": "HTML",
"bytes": "1881"
},
{
"name": "JavaScript",
"bytes": "7113"
}
],
"symlink_target": ""
} |
/*
postload.js
Provides Javascript support
*/
// Call the function displaydate()
displaydate();
function displaydate(){
// Displays the date and time in AM/PM format.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
if (minutes < 10){
minutes = "0" + minutes
}
var ampm = "";
if(hours > 11){
ampm = "PM"
} else {
ampm = "AM"
}
document.write("<div class=\"jstime\">" + day + "/" + month + "/" +
year + " " + hours + ":" + minutes + ampm + "</div>")
}
// Set navigation menu cookie
function setnavitem(item){
$.cookie("navmenuitem", item);
} | {
"content_hash": "f34fa1c97a1749f20094b33ca2bcd55c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 72,
"avg_line_length": 18.555555555555557,
"alnum_prop": 0.5592814371257485,
"repo_name": "merville/FreeBSD_CMS",
"id": "a07124d6104756532466f8a8dc97b93e5ce2c104",
"size": "835",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javascript/postload.js",
"mode": "33261",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
@*
* Copyright 2022 HM Revenue & Customs
*
* 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.
*@
@import config.ViewConfig
@this(
timeoutDialogue: uk.gov.hmrc.hmrcfrontend.views.html.helpers.HmrcTimeoutDialogHelper,
)
@(isLoggedIn: Boolean)(implicit r: Request[_], m: Messages, viewConf: ViewConfig)
@timeoutDialogue(
signOutUrl = routes.TimeoutController.killSession().url,
keepAliveUrl = Some(controllers.routes.TimeoutController.keepAliveSession().url),
timeout = Some(viewConf.timeoutDialogTimeout),
countdown = Some(viewConf.timeoutDialogCountdown),
title = None,
message = Some { if (isLoggedIn) Messages("timeoutDialog.message.logged-in") else Messages("timeoutDialog.message.logged-out") },
keepAliveButtonText = Some { if (isLoggedIn) Messages("timeoutDialog.keep-alive-button-text.logged-in") else Messages("timeoutDialog.keep-alive-button-text.logged-out") },
signOutButtonText = Some { if (isLoggedIn) Messages(s"timeoutDialog.sign-out-button-text.logged-in") else Messages("timeoutDialog.sign-out-button-text.logged-out") }
) | {
"content_hash": "ea713a490fdb423e7457900833bdab5a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 175,
"avg_line_length": 44.19444444444444,
"alnum_prop": 0.7510999371464487,
"repo_name": "hmrc/self-service-time-to-pay-frontend",
"id": "b68520575c1a00ebf2f2d01ca613addbcf01bbf4",
"size": "1591",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/views/partials/timeout_dialog_script.scala.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6365"
},
{
"name": "Cycript",
"bytes": "39036"
},
{
"name": "HTML",
"bytes": "147784"
},
{
"name": "JavaScript",
"bytes": "3653"
},
{
"name": "SCSS",
"bytes": "584"
},
{
"name": "Scala",
"bytes": "547695"
},
{
"name": "Shell",
"bytes": "80"
}
],
"symlink_target": ""
} |
using namespace Framework;
CZipInflateStream::CZipInflateStream(CStream& baseStream, unsigned int compressedLength) :
m_baseStream(baseStream),
m_compressedLength(compressedLength)
{
m_zStream.zalloc = Z_NULL;
m_zStream.zfree = Z_NULL;
m_zStream.opaque = Z_NULL;
m_zStream.avail_in = 0;
m_zStream.next_in = Z_NULL;
if(inflateInit2(&m_zStream, -MAX_WBITS) != Z_OK)
{
throw std::runtime_error("zlib stream initialization error.");
}
}
CZipInflateStream::~CZipInflateStream()
{
inflateEnd(&m_zStream);
}
void CZipInflateStream::Seek(int64, STREAM_SEEK_DIRECTION)
{
throw std::runtime_error("Unsupported operation.");
}
uint64 CZipInflateStream::Tell()
{
throw std::runtime_error("Unsupported operation.");
}
uint64 CZipInflateStream::Read(void* buffer, uint64 length)
{
Bytef outBuffer[BUFFERSIZE];
uint8* destBuffer = reinterpret_cast<uint8*>(buffer);
uint64 sizeCounter = length;
do
{
if(m_zStream.avail_in == 0)
{
if(m_compressedLength == 0)
{
//EOF
break;
}
FeedBuffer();
}
int bufferSize = std::min<int>(BUFFERSIZE, static_cast<int>(sizeCounter));
m_zStream.avail_out = bufferSize;
m_zStream.next_out = outBuffer;
int ret = inflate(&m_zStream, Z_NO_FLUSH);
switch (ret) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
throw std::runtime_error("Error occured while inflating.");
break;
}
int have = bufferSize - m_zStream.avail_out;
memcpy(destBuffer, outBuffer, have);
destBuffer += have;
sizeCounter -= have;
if(ret == Z_STREAM_END)
{
assert(IsEOF());
break;
}
}
while (sizeCounter != 0);
return length - sizeCounter;
}
uint64 CZipInflateStream::Write(const void* buffer, uint64 size)
{
throw std::runtime_error("Unsupported operation.");
}
bool CZipInflateStream::IsEOF()
{
return (m_compressedLength == 0) && (m_zStream.avail_in == 0);
}
void CZipInflateStream::FeedBuffer()
{
assert(m_zStream.avail_in == 0);
unsigned int toRead = std::min<unsigned int>(BUFFERSIZE, m_compressedLength);
m_zStream.avail_in = static_cast<uInt>(m_baseStream.Read(m_inputBuffer, toRead));
m_zStream.next_in = m_inputBuffer;
m_compressedLength -= m_zStream.avail_in;
}
| {
"content_hash": "9410ee324feff9fd3fe1aef65547e708",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 90,
"avg_line_length": 25.95744680851064,
"alnum_prop": 0.6233606557377049,
"repo_name": "Alloyed/Play--Framework",
"id": "6d435af1330f1c89077e6edd76767ccc70cd69b2",
"size": "2537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/zip/ZipInflateStream.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "122"
},
{
"name": "C",
"bytes": "5101"
},
{
"name": "C++",
"bytes": "454250"
},
{
"name": "CMake",
"bytes": "1676"
},
{
"name": "Makefile",
"bytes": "2617"
},
{
"name": "Shell",
"bytes": "472"
}
],
"symlink_target": ""
} |
package STORAGESVR.ENTITY.CRESULT;
public class CResult {
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| {
"content_hash": "3921e3dde056e082bbc7fbb8c71596c1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 15.615384615384615,
"alnum_prop": 0.7241379310344828,
"repo_name": "fpt-software/SENTestKit-Server",
"id": "7ae09b1e5018238b4fbbcafea9b14c5ce9dbbb14",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "storagesvr/src/STORAGESVR/ENTITY/CRESULT/CResult.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "259919"
}
],
"symlink_target": ""
} |
package org.wallerlab.yoink.math.linear;
import jcuda.Pointer;
import jcuda.Sizeof;
import jcuda.jcublas.JCublas;
import org.wallerlab.yoink.api.service.math.Matrix;
public class JCublasMatrix implements Matrix <float[][]>{
private float [][] internalMatrix;
private float [][] tempMatrix;
public JCublasMatrix(){
}
public JCublasMatrix (int rowDimension, int columnDimension){
this.internalMatrix = new float [rowDimension][columnDimension];
}
public void setEntry (int row, int column, double value){
this.internalMatrix [row][column]= (float) value;
}
public double getEntry(int row, int column){
return this.internalMatrix [row][column];
}
public Matrix transpose(){
throw new UnsupportedOperationException();
}
public float[] convert2DArrayTo1DArray ( float [][] array ) {
int totalLength = 0;
for ( float[] arr : array ) {
totalLength += arr.length;
}
float[] result = new float [ totalLength ];
int idx = 0;
for ( float[] arr : array ) {
for ( float i : arr ) {
result[ idx++ ] = i;
}
}
return result;
}
public float [][] convert1DArrayTo2DArray ( float [] array ) {
float [][] array2D = new float [internalMatrix.length][internalMatrix[0].length];
int k = 0;
for(int i=0;i<internalMatrix.length;i++){
for(int j=0;j<internalMatrix[0].length;j++){
array2D [i][j]= array[k];
k++;
}
}
return array2D;
}
public Matrix add(Matrix m){
float [] internMatrix;
float alpha = 1.0f;
internMatrix = convert2DArrayTo1DArray(this.internalMatrix);
float [] internm = convert2DArrayTo1DArray(((JCublasMatrix) m).getDatafloat());
int nrow= internalMatrix.length;
int mcolumn = internalMatrix[0].length;
int nm = nrow*mcolumn;
//Initialize JCublas
JCublas.cublasInit();
//Allocate memory on the device
Pointer deviceinternMatrix = new Pointer();
JCublas.cublasAlloc(nm, Sizeof.FLOAT,deviceinternMatrix);
Pointer deviceinternm = new Pointer();
JCublas.cublasAlloc(nm, Sizeof.FLOAT,deviceinternm);
//Copy the memory from the host to the device
JCublas.cublasSetVector(nm, Sizeof.FLOAT, Pointer.to(internMatrix), 1, deviceinternMatrix, 1);
JCublas.cublasSetVector(nm, Sizeof.FLOAT, Pointer.to(internm), 1, deviceinternm, 1);
//Execute dotProduct
JCublas.cublasSaxpy(nm, alpha, deviceinternMatrix, 1, deviceinternm, 1);
//Copy the result from the device to the host
JCublas.cublasGetVector(nm, Sizeof.FLOAT, deviceinternm,1 , Pointer.to(internm),1);
JCublas.cublasGetVector(nm, Sizeof.FLOAT, deviceinternMatrix,1 , Pointer.to(internMatrix),1);
//Clean up
JCublas.cublasFree(deviceinternMatrix);
JCublas.cublasFree(deviceinternm);
Matrix temp = new JCublasMatrix();
tempMatrix = convert1DArrayTo2DArray(internm);
temp.setInternalMatrix(tempMatrix);
return temp;
}
@Override
public void array2DRowRealMatrix(double[][] d) {
// TODO Auto-generated method stub
}
@Override
public void addToEntry(int row, int column, double increment) {
// TODO Auto-generated method stub
}
@Override
public Matrix subtract(Matrix m) {
// TODO Auto-generated method stub
return null;
}
@Override
public Matrix scalarMultiply(double d) {
// TODO Auto-generated method stub
return null;
}
@Override
public Matrix ebeMultiply(Matrix m) {
// TODO Auto-generated method stub
return null;
}
public float[][] getDatafloat() {
return internalMatrix;
}
@Override
public double[] getRow(int i) {
double rowarray[] = new double [internalMatrix[0].length];
for (int j = 0; j< internalMatrix[0].length;j++){
rowarray [j]= internalMatrix[i][j];
}
return rowarray;
}
@Override
public double dotProduct() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double distance(Matrix m) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getNorm() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean equals(Matrix m) {
// TODO Auto-generated method stub
return false;
}
@Override
public float [][] getInternalMatrix() {
return internalMatrix;
}
@Override
public void setInternalMatrix(float[][] internalMatrix) {
this.internalMatrix = internalMatrix;
}
@Override
public double[][] getData() {
// TODO Auto-generated method stub
return null;
}
}
| {
"content_hash": "52f91ebf1d5d182539c81188a1dd7c41",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 98,
"avg_line_length": 26.58433734939759,
"alnum_prop": 0.6909132109675957,
"repo_name": "buralin/Yoinkchange",
"id": "343e433c58df7c50453d3bfc2df2f7b9df2bea22",
"size": "4413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yoink-core-math/src/main/java/org/wallerlab/yoink/math/linear/JCublasMatrix.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "215946"
},
{
"name": "Java",
"bytes": "2182976"
}
],
"symlink_target": ""
} |
#ifndef _MATRIX_
#define _MATRIX_
#include <iostream>
namespace concurrent_programming{
/**
* \class Matrix
*
* This class provides a manner to representing a square matrix
* and simple operations, like sum, subtraction and multiplication.
*
* @author Vinícius Campos
* @date 2017/10/06
* @version 1.0
*
*/
template<typename T>
class Matrix{
private:
T ** data;
int size = 0;
int n_threads = 0;
/**
* The auxiliar method used by threads to compute parallel multiplications
*
* @param result the matrix that will save the result of matrix computations
* @param a the matrix to multiply
* @param x0 the start point of multiplication
* @param x1 the last point of multiplication
**/
void auxiliarMultiply(Matrix<T> & result, const Matrix<T> & a, const int x0, const int x1);
public:
/**
*
* Constructor of class
*
* @param size_ defines the dimension of matrix
**/
Matrix(const int & size_);
/**
*
* Other constructor of class
*
* @param size_ defines the dimension of matrix
* @param n_threads_ defines the number of threads
**/
Matrix(const int & size_, const int & n_threads_);
/**
*
* Destructor of class
*
**/
~Matrix();
/**
*
* Get the value of marix in position data[row][col]
*
* @param row index of row matrix
* @param col index of col matrix
**/
T get(const int & row, const int & col);
/**
*
* Set the value of marix in position data[row][col]
*
* @param row index of row matrix
* @param col index of col matrix
* @param value the new value to insert in position data[row][col]
**/
void set(const int & row, const int & col, T & value);
/**
*
* Get the dimension of matrix
*
**/
int length() const;
/**
*
* Verify if the matrix os empty
*
**/
bool isEmpty();
/**
*
* Realize the parallel multiplication
*
* @param a the matrix to multiplying
**/
Matrix<T> multiply(const Matrix<T> & a);
/**
*
* Override [] methods to using de data information
*
**/
T *& operator[](const int & i);
T * operator[](const int & i) const;
/**
* Override + operator to realize sum of two matrixes
* @param a the matrix to sum
**/
Matrix<T> operator+(const Matrix<T> & a);
/**
* Override + operator to realize subtraction of two matrixes
* @param a the matrix to sum
**/
Matrix<T> operator-(const Matrix<T> & a);
/**
* Override * operator to realize sequential multiplication
* @param a the matrix to multiply
**/
Matrix<T> operator*(const Matrix<T> & a);
/**
* Override = operator to realize an assignment
**/
Matrix<T> & operator=(const Matrix<T> a);
};
/**
* Print the matrix
* @param os Output stream
* @param obj Matrix to be printed
**/
template<typename T>
std::ostream & operator<<(std::ostream & os, const concurrent_programming::Matrix<T> & obj);
}
#include "../src/matrix.inl"
#endif | {
"content_hash": "8bab851b48699e514ff3d4ac0b9708e6",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 94,
"avg_line_length": 20.43243243243243,
"alnum_prop": 0.609457671957672,
"repo_name": "Vinihcampos/concurrent-programming",
"id": "4001a8186f6dd066d9142050f4185ed2293ed08c",
"size": "3025",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01 - Practice with threads/include/matrix.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "14143"
},
{
"name": "CMake",
"bytes": "508"
},
{
"name": "Go",
"bytes": "3312"
},
{
"name": "Java",
"bytes": "9509"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Herb. port. 119. 1931
#### Original name
null
### Remarks
null | {
"content_hash": "7fab1b5b83d3c3bf0604165053d08f05",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 11.538461538461538,
"alnum_prop": 0.6866666666666666,
"repo_name": "mdoering/backbone",
"id": "54eec35d97678f8a50b1beab6596b5088c6cc82c",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Clinopodium/Clinopodium menthifolium/ Syn. Clinopodium ascendens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.adswizz.inforecast.common.beans;
/**
* Created by sorin.nica in June 2017
*/
public enum OpportunityField {
listenerId,
sessionId,
timestamp,
zoneMaxAdsMaxAdbreak,
position,
maxAdbreakDuration,
streamID,
language,
ip,
urlDomain,
urlPath,
urlQuery,
referer,
userAgent,
os,
browser,
ishttps,
country,
region,
city,
postalCode,
latitude,
longitude,
dma,
areaCode,
continent,
subregion,
clientSideOpportunity,
contactsTrail,
partialRequestId,
deviceType,
deviceName,
segments,
metropolitanAreas,
msa,
cma
}
| {
"content_hash": "d602c5f4a3b5e8c1bf58b0b8efb13079",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 44,
"avg_line_length": 14.755555555555556,
"alnum_prop": 0.6234939759036144,
"repo_name": "dragosbadswizz/testcsv",
"id": "d8c9f4c1249c65986265d5dc15904a68ec745b50",
"size": "664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/adswizz/inforecast/common/beans/OpportunityField.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "51689"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.