text stringlengths 2 1.04M | meta dict |
|---|---|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.download.home.list.mutator;
import org.chromium.chrome.browser.download.home.DownloadManagerUiConfig;
import org.chromium.chrome.browser.download.home.list.ListItem;
import org.chromium.chrome.browser.download.home.list.ListItem.OfflineItemListItem;
import org.chromium.components.offline_items_collection.OfflineItemFilter;
import java.util.List;
/**
* Post processes the items in the list and sets properties for UI as appropriate. The properties
* being set are:
* - Image item span width.
* - Margins between {@link OfflineItemFilter} types (image, document, etc.).
*/
public class ListItemPropertySetter implements ListConsumer {
private final DownloadManagerUiConfig mConfig;
private ListConsumer mListConsumer;
/** Constructor. */
public ListItemPropertySetter(DownloadManagerUiConfig config) {
mConfig = config;
}
@Override
public void onListUpdated(List<ListItem> inputList) {
setProperties(inputList);
mListConsumer.onListUpdated(inputList);
}
@Override
public ListConsumer setListConsumer(ListConsumer nextConsumer) {
mListConsumer = nextConsumer;
return mListConsumer;
}
/** Sets properties for items in the given list. */
private void setProperties(List<ListItem> sortedList) {
setWidthForImageItems(sortedList);
}
private void setWidthForImageItems(List<ListItem> listItems) {
if (!mConfig.supportFullWidthImages) return;
for (int i = 0; i < listItems.size(); i++) {
ListItem currentItem = listItems.get(i);
boolean currentItemIsImage = currentItem instanceof OfflineItemListItem
&& ((OfflineItemListItem) currentItem).item.filter == OfflineItemFilter.IMAGE;
if (!currentItemIsImage) continue;
ListItem previousItem = i == 0 ? null : listItems.get(i - 1);
ListItem nextItem = i >= listItems.size() - 1 ? null : listItems.get(i + 1);
boolean previousItemIsImage = previousItem instanceof OfflineItemListItem
&& ((OfflineItemListItem) previousItem).item.filter == OfflineItemFilter.IMAGE;
boolean nextItemIsImage = nextItem instanceof OfflineItemListItem
&& ((OfflineItemListItem) nextItem).item.filter == OfflineItemFilter.IMAGE;
if (!previousItemIsImage && !nextItemIsImage) {
((OfflineItemListItem) currentItem).spanFullWidth = true;
}
}
}
}
| {
"content_hash": "6f432256a3f53ff41003a0b00a9728e5",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 99,
"avg_line_length": 39.8955223880597,
"alnum_prop": 0.6965955854844744,
"repo_name": "chromium/chromium",
"id": "50f8cb59e3d62d5a970d93e0f15de84f9bca10a2",
"size": "2673",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/home/list/mutator/ListItemPropertySetter.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import animator from './core.animator';
import defaults, {overrides} from './core.defaults';
import Interaction from './core.interaction';
import layouts from './core.layouts';
import {_detectPlatform} from '../platform';
import PluginService from './core.plugins';
import registry from './core.registry';
import Config, {determineAxis, getIndexAxis} from './core.config';
import {retinaScale, _isDomSupported} from '../helpers/helpers.dom';
import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core';
import {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea} from '../helpers';
// @ts-ignore
import {version} from '../../package.json';
import {debounce} from '../helpers/helpers.extras';
/**
* @typedef { import('../../types').ChartEvent } ChartEvent
* @typedef { import("../../types").Point } Point
*/
const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
function positionIsHorizontal(position, axis) {
return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
}
function compare2Level(l1, l2) {
return function(a, b) {
return a[l1] === b[l1]
? a[l2] - b[l2]
: a[l1] - b[l1];
};
}
function onAnimationsComplete(context) {
const chart = context.chart;
const animationOptions = chart.options.animation;
chart.notifyPlugins('afterRender');
callCallback(animationOptions && animationOptions.onComplete, [context], chart);
}
function onAnimationProgress(context) {
const chart = context.chart;
const animationOptions = chart.options.animation;
callCallback(animationOptions && animationOptions.onProgress, [context], chart);
}
/**
* Chart.js can take a string id of a canvas element, a 2d context, or a canvas element itself.
* Attempt to unwrap the item passed into the chart constructor so that it is a canvas element (if possible).
*/
function getCanvas(item) {
if (_isDomSupported() && typeof item === 'string') {
item = document.getElementById(item);
} else if (item && item.length) {
// Support for array based queries (such as jQuery)
item = item[0];
}
if (item && item.canvas) {
// Support for any object associated to a canvas (including a context2d)
item = item.canvas;
}
return item;
}
const instances = {};
const getChart = (key) => {
const canvas = getCanvas(key);
return Object.values(instances).filter((c) => c.canvas === canvas).pop();
};
function moveNumericKeys(obj, start, move) {
const keys = Object.keys(obj);
for (const key of keys) {
const intKey = +key;
if (intKey >= start) {
const value = obj[key];
delete obj[key];
if (move > 0 || intKey > start) {
obj[intKey + move] = value;
}
}
}
}
/**
* @param {ChartEvent} e
* @param {ChartEvent|null} lastEvent
* @param {boolean} inChartArea
* @param {boolean} isClick
* @returns {ChartEvent|null}
*/
function determineLastEvent(e, lastEvent, inChartArea, isClick) {
if (!inChartArea || e.type === 'mouseout') {
return null;
}
if (isClick) {
return lastEvent;
}
return e;
}
class Chart {
static defaults = defaults;
static instances = instances;
static overrides = overrides;
static registry = registry;
static version = version;
static getChart = getChart;
static register(...items) {
registry.add(...items);
invalidatePlugins();
}
static unregister(...items) {
registry.remove(...items);
invalidatePlugins();
}
// eslint-disable-next-line max-statements
constructor(item, userConfig) {
const config = this.config = new Config(userConfig);
const initialCanvas = getCanvas(item);
const existingChart = getChart(initialCanvas);
if (existingChart) {
throw new Error(
'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.'
);
}
const options = config.createResolver(config.chartOptionScopes(), this.getContext());
this.platform = new (config.platform || _detectPlatform(initialCanvas))();
this.platform.updateConfig(config);
const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
const canvas = context && context.canvas;
const height = canvas && canvas.height;
const width = canvas && canvas.width;
this.id = uid();
this.ctx = context;
this.canvas = canvas;
this.width = width;
this.height = height;
this._options = options;
// Store the previously used aspect ratio to determine if a resize
// is needed during updates. Do this after _options is set since
// aspectRatio uses a getter
this._aspectRatio = this.aspectRatio;
this._layers = [];
this._metasets = [];
this._stacks = undefined;
this.boxes = [];
this.currentDevicePixelRatio = undefined;
this.chartArea = undefined;
this._active = [];
this._lastEvent = undefined;
this._listeners = {};
/** @type {?{attach?: function, detach?: function, resize?: function}} */
this._responsiveListeners = undefined;
this._sortedMetasets = [];
this.scales = {};
this._plugins = new PluginService();
this.$proxies = {};
this._hiddenIndices = {};
this.attached = false;
this._animationsDisabled = undefined;
this.$context = undefined;
this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0);
this._dataChanges = [];
// Add the chart instance to the global namespace
instances[this.id] = this;
if (!context || !canvas) {
// The given item is not a compatible context2d element, let's return before finalizing
// the chart initialization but after setting basic chart / controller properties that
// can help to figure out that the chart is not valid (e.g chart.canvas !== null);
// https://github.com/chartjs/Chart.js/issues/2807
console.error("Failed to create chart: can't acquire context from the given item");
return;
}
animator.listen(this, 'complete', onAnimationsComplete);
animator.listen(this, 'progress', onAnimationProgress);
this._initialize();
if (this.attached) {
this.update();
}
}
get aspectRatio() {
const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;
if (!isNullOrUndef(aspectRatio)) {
// If aspectRatio is defined in options, use that.
return aspectRatio;
}
if (maintainAspectRatio && _aspectRatio) {
// If maintainAspectRatio is truthly and we had previously determined _aspectRatio, use that
return _aspectRatio;
}
// Calculate
return height ? width / height : null;
}
get data() {
return this.config.data;
}
set data(data) {
this.config.data = data;
}
get options() {
return this._options;
}
set options(options) {
this.config.options = options;
}
get registry() {
return registry;
}
/**
* @private
*/
_initialize() {
// Before init plugin notification
this.notifyPlugins('beforeInit');
if (this.options.responsive) {
this.resize();
} else {
retinaScale(this, this.options.devicePixelRatio);
}
this.bindEvents();
// After init plugin notification
this.notifyPlugins('afterInit');
return this;
}
clear() {
clearCanvas(this.canvas, this.ctx);
return this;
}
stop() {
animator.stop(this);
return this;
}
/**
* Resize the chart to its container or to explicit dimensions.
* @param {number} [width]
* @param {number} [height]
*/
resize(width, height) {
if (!animator.running(this)) {
this._resize(width, height);
} else {
this._resizeBeforeDraw = {width, height};
}
}
_resize(width, height) {
const options = this.options;
const canvas = this.canvas;
const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
const mode = this.width ? 'resize' : 'attach';
this.width = newSize.width;
this.height = newSize.height;
this._aspectRatio = this.aspectRatio;
if (!retinaScale(this, newRatio, true)) {
return;
}
this.notifyPlugins('resize', {size: newSize});
callCallback(options.onResize, [this, newSize], this);
if (this.attached) {
if (this._doResize(mode)) {
// The resize update is delayed, only draw without updating.
this.render();
}
}
}
ensureScalesHaveIDs() {
const options = this.options;
const scalesOptions = options.scales || {};
each(scalesOptions, (axisOptions, axisID) => {
axisOptions.id = axisID;
});
}
/**
* Builds a map of scale ID to scale object for future lookup.
*/
buildOrUpdateScales() {
const options = this.options;
const scaleOpts = options.scales;
const scales = this.scales;
const updated = Object.keys(scales).reduce((obj, id) => {
obj[id] = false;
return obj;
}, {});
let items = [];
if (scaleOpts) {
items = items.concat(
Object.keys(scaleOpts).map((id) => {
const scaleOptions = scaleOpts[id];
const axis = determineAxis(id, scaleOptions);
const isRadial = axis === 'r';
const isHorizontal = axis === 'x';
return {
options: scaleOptions,
dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
};
})
);
}
each(items, (item) => {
const scaleOptions = item.options;
const id = scaleOptions.id;
const axis = determineAxis(id, scaleOptions);
const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
scaleOptions.position = item.dposition;
}
updated[id] = true;
let scale = null;
if (id in scales && scales[id].type === scaleType) {
scale = scales[id];
} else {
const scaleClass = registry.getScale(scaleType);
scale = new scaleClass({
id,
type: scaleType,
ctx: this.ctx,
chart: this
});
scales[scale.id] = scale;
}
scale.init(scaleOptions, options);
});
// clear up discarded scales
each(updated, (hasUpdated, id) => {
if (!hasUpdated) {
delete scales[id];
}
});
each(scales, (scale) => {
layouts.configure(this, scale, scale.options);
layouts.addBox(this, scale);
});
}
/**
* @private
*/
_updateMetasets() {
const metasets = this._metasets;
const numData = this.data.datasets.length;
const numMeta = metasets.length;
metasets.sort((a, b) => a.index - b.index);
if (numMeta > numData) {
for (let i = numData; i < numMeta; ++i) {
this._destroyDatasetMeta(i);
}
metasets.splice(numData, numMeta - numData);
}
this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
}
/**
* @private
*/
_removeUnreferencedMetasets() {
const {_metasets: metasets, data: {datasets}} = this;
if (metasets.length > datasets.length) {
delete this._stacks;
}
metasets.forEach((meta, index) => {
if (datasets.filter(x => x === meta._dataset).length === 0) {
this._destroyDatasetMeta(index);
}
});
}
buildOrUpdateControllers() {
const newControllers = [];
const datasets = this.data.datasets;
let i, ilen;
this._removeUnreferencedMetasets();
for (i = 0, ilen = datasets.length; i < ilen; i++) {
const dataset = datasets[i];
let meta = this.getDatasetMeta(i);
const type = dataset.type || this.config.type;
if (meta.type && meta.type !== type) {
this._destroyDatasetMeta(i);
meta = this.getDatasetMeta(i);
}
meta.type = type;
meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
meta.order = dataset.order || 0;
meta.index = i;
meta.label = '' + dataset.label;
meta.visible = this.isDatasetVisible(i);
if (meta.controller) {
meta.controller.updateIndex(i);
meta.controller.linkScales();
} else {
const ControllerClass = registry.getController(type);
const {datasetElementType, dataElementType} = defaults.datasets[type];
Object.assign(ControllerClass, {
dataElementType: registry.getElement(dataElementType),
datasetElementType: datasetElementType && registry.getElement(datasetElementType)
});
meta.controller = new ControllerClass(this, i);
newControllers.push(meta.controller);
}
}
this._updateMetasets();
return newControllers;
}
/**
* Reset the elements of all datasets
* @private
*/
_resetElements() {
each(this.data.datasets, (dataset, datasetIndex) => {
this.getDatasetMeta(datasetIndex).controller.reset();
}, this);
}
/**
* Resets the chart back to its state before the initial animation
*/
reset() {
this._resetElements();
this.notifyPlugins('reset');
}
update(mode) {
const config = this.config;
config.update();
const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
const animsDisabled = this._animationsDisabled = !options.animation;
this._updateScales();
this._checkEventBindings();
this._updateHiddenIndices();
// plugins options references might have change, let's invalidate the cache
// https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
this._plugins.invalidate();
if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {
return;
}
// Make sure dataset controllers are updated and new controllers are reset
const newControllers = this.buildOrUpdateControllers();
this.notifyPlugins('beforeElementsUpdate');
// Make sure all dataset controllers have correct meta data counts
let minPadding = 0;
for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) {
const {controller} = this.getDatasetMeta(i);
const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
// New controllers will be reset after the layout pass, so we only want to modify
// elements added to new datasets
controller.buildOrUpdateElements(reset);
minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
}
minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
this._updateLayout(minPadding);
// Only reset the controllers if we have animations
if (!animsDisabled) {
// Can only reset the new controllers after the scales have been updated
// Reset is done to get the starting point for the initial animation
each(newControllers, (controller) => {
controller.reset();
});
}
this._updateDatasets(mode);
// Do this before render so that any plugins that need final scale updates can use it
this.notifyPlugins('afterUpdate', {mode});
this._layers.sort(compare2Level('z', '_idx'));
// Replay last event from before update, or set hover styles on active elements
const {_active, _lastEvent} = this;
if (_lastEvent) {
this._eventHandler(_lastEvent, true);
} else if (_active.length) {
this._updateHoverStyles(_active, _active, true);
}
this.render();
}
/**
* @private
*/
_updateScales() {
each(this.scales, (scale) => {
layouts.removeBox(this, scale);
});
this.ensureScalesHaveIDs();
this.buildOrUpdateScales();
}
/**
* @private
*/
_checkEventBindings() {
const options = this.options;
const existingEvents = new Set(Object.keys(this._listeners));
const newEvents = new Set(options.events);
if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
// The configured events have changed. Rebind.
this.unbindEvents();
this.bindEvents();
}
}
/**
* @private
*/
_updateHiddenIndices() {
const {_hiddenIndices} = this;
const changes = this._getUniformDataChanges() || [];
for (const {method, start, count} of changes) {
const move = method === '_removeElements' ? -count : count;
moveNumericKeys(_hiddenIndices, start, move);
}
}
/**
* @private
*/
_getUniformDataChanges() {
const _dataChanges = this._dataChanges;
if (!_dataChanges || !_dataChanges.length) {
return;
}
this._dataChanges = [];
const datasetCount = this.data.datasets.length;
const makeSet = (idx) => new Set(
_dataChanges
.filter(c => c[0] === idx)
.map((c, i) => i + ',' + c.splice(1).join(','))
);
const changeSet = makeSet(0);
for (let i = 1; i < datasetCount; i++) {
if (!setsEqual(changeSet, makeSet(i))) {
return;
}
}
return Array.from(changeSet)
.map(c => c.split(','))
.map(a => ({method: a[1], start: +a[2], count: +a[3]}));
}
/**
* Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
* hook, in which case, plugins will not be called on `afterLayout`.
* @private
*/
_updateLayout(minPadding) {
if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) {
return;
}
layouts.update(this, this.width, this.height, minPadding);
const area = this.chartArea;
const noArea = area.width <= 0 || area.height <= 0;
this._layers = [];
each(this.boxes, (box) => {
if (noArea && box.position === 'chartArea') {
// Skip drawing and configuring chartArea boxes when chartArea is zero or negative
return;
}
// configure is called twice, once in core.scale.update and once here.
// Here the boxes are fully updated and at their final positions.
if (box.configure) {
box.configure();
}
this._layers.push(...box._layers());
}, this);
this._layers.forEach((item, index) => {
item._idx = index;
});
this.notifyPlugins('afterLayout');
}
/**
* Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
* hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
* @private
*/
_updateDatasets(mode) {
if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {
return;
}
for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
this.getDatasetMeta(i).controller.configure();
}
for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);
}
this.notifyPlugins('afterDatasetsUpdate', {mode});
}
/**
* Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
* hook, in which case, plugins will not be called on `afterDatasetUpdate`.
* @private
*/
_updateDataset(index, mode) {
const meta = this.getDatasetMeta(index);
const args = {meta, index, mode, cancelable: true};
if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
return;
}
meta.controller._update(mode);
args.cancelable = false;
this.notifyPlugins('afterDatasetUpdate', args);
}
render() {
if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) {
return;
}
if (animator.has(this)) {
if (this.attached && !animator.running(this)) {
animator.start(this);
}
} else {
this.draw();
onAnimationsComplete({chart: this});
}
}
draw() {
let i;
if (this._resizeBeforeDraw) {
const {width, height} = this._resizeBeforeDraw;
this._resize(width, height);
this._resizeBeforeDraw = null;
}
this.clear();
if (this.width <= 0 || this.height <= 0) {
return;
}
if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) {
return;
}
// Because of plugin hooks (before/afterDatasetsDraw), datasets can't
// currently be part of layers. Instead, we draw
// layers <= 0 before(default, backward compat), and the rest after
const layers = this._layers;
for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
layers[i].draw(this.chartArea);
}
this._drawDatasets();
// Rest of layers
for (; i < layers.length; ++i) {
layers[i].draw(this.chartArea);
}
this.notifyPlugins('afterDraw');
}
/**
* @private
*/
_getSortedDatasetMetas(filterVisible) {
const metasets = this._sortedMetasets;
const result = [];
let i, ilen;
for (i = 0, ilen = metasets.length; i < ilen; ++i) {
const meta = metasets[i];
if (!filterVisible || meta.visible) {
result.push(meta);
}
}
return result;
}
/**
* Gets the visible dataset metas in drawing order
* @return {object[]}
*/
getSortedVisibleDatasetMetas() {
return this._getSortedDatasetMetas(true);
}
/**
* Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
* hook, in which case, plugins will not be called on `afterDatasetsDraw`.
* @private
*/
_drawDatasets() {
if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {
return;
}
const metasets = this.getSortedVisibleDatasetMetas();
for (let i = metasets.length - 1; i >= 0; --i) {
this._drawDataset(metasets[i]);
}
this.notifyPlugins('afterDatasetsDraw');
}
/**
* Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
* hook, in which case, plugins will not be called on `afterDatasetDraw`.
* @private
*/
_drawDataset(meta) {
const ctx = this.ctx;
const clip = meta._clip;
const useClip = !clip.disabled;
const area = this.chartArea;
const args = {
meta,
index: meta.index,
cancelable: true
};
if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
return;
}
if (useClip) {
clipArea(ctx, {
left: clip.left === false ? 0 : area.left - clip.left,
right: clip.right === false ? this.width : area.right + clip.right,
top: clip.top === false ? 0 : area.top - clip.top,
bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
});
}
meta.controller.draw();
if (useClip) {
unclipArea(ctx);
}
args.cancelable = false;
this.notifyPlugins('afterDatasetDraw', args);
}
/**
* Checks whether the given point is in the chart area.
* @param {Point} point - in relative coordinates (see, e.g., getRelativePosition)
* @returns {boolean}
*/
isPointInArea(point) {
return _isPointInArea(point, this.chartArea, this._minPadding);
}
getElementsAtEventForMode(e, mode, options, useFinalPosition) {
const method = Interaction.modes[mode];
if (typeof method === 'function') {
return method(this, e, options, useFinalPosition);
}
return [];
}
getDatasetMeta(datasetIndex) {
const dataset = this.data.datasets[datasetIndex];
const metasets = this._metasets;
let meta = metasets.filter(x => x && x._dataset === dataset).pop();
if (!meta) {
meta = {
type: null,
data: [],
dataset: null,
controller: null,
hidden: null, // See isDatasetVisible() comment
xAxisID: null,
yAxisID: null,
order: dataset && dataset.order || 0,
index: datasetIndex,
_dataset: dataset,
_parsed: [],
_sorted: false
};
metasets.push(meta);
}
return meta;
}
getContext() {
return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'}));
}
getVisibleDatasetCount() {
return this.getSortedVisibleDatasetMetas().length;
}
isDatasetVisible(datasetIndex) {
const dataset = this.data.datasets[datasetIndex];
if (!dataset) {
return false;
}
const meta = this.getDatasetMeta(datasetIndex);
// meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
// the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
}
setDatasetVisibility(datasetIndex, visible) {
const meta = this.getDatasetMeta(datasetIndex);
meta.hidden = !visible;
}
toggleDataVisibility(index) {
this._hiddenIndices[index] = !this._hiddenIndices[index];
}
getDataVisibility(index) {
return !this._hiddenIndices[index];
}
/**
* @private
*/
_updateVisibility(datasetIndex, dataIndex, visible) {
const mode = visible ? 'show' : 'hide';
const meta = this.getDatasetMeta(datasetIndex);
const anims = meta.controller._resolveAnimations(undefined, mode);
if (defined(dataIndex)) {
meta.data[dataIndex].hidden = !visible;
this.update();
} else {
this.setDatasetVisibility(datasetIndex, visible);
// Animate visible state, so hide animation can be seen. This could be handled better if update / updateDataset returned a Promise.
anims.update(meta, {visible});
this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);
}
}
hide(datasetIndex, dataIndex) {
this._updateVisibility(datasetIndex, dataIndex, false);
}
show(datasetIndex, dataIndex) {
this._updateVisibility(datasetIndex, dataIndex, true);
}
/**
* @private
*/
_destroyDatasetMeta(datasetIndex) {
const meta = this._metasets[datasetIndex];
if (meta && meta.controller) {
meta.controller._destroy();
}
delete this._metasets[datasetIndex];
}
_stop() {
let i, ilen;
this.stop();
animator.remove(this);
for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
this._destroyDatasetMeta(i);
}
}
destroy() {
this.notifyPlugins('beforeDestroy');
const {canvas, ctx} = this;
this._stop();
this.config.clearCache();
if (canvas) {
this.unbindEvents();
clearCanvas(canvas, ctx);
this.platform.releaseContext(ctx);
this.canvas = null;
this.ctx = null;
}
delete instances[this.id];
this.notifyPlugins('afterDestroy');
}
toBase64Image(...args) {
return this.canvas.toDataURL(...args);
}
/**
* @private
*/
bindEvents() {
this.bindUserEvents();
if (this.options.responsive) {
this.bindResponsiveEvents();
} else {
this.attached = true;
}
}
/**
* @private
*/
bindUserEvents() {
const listeners = this._listeners;
const platform = this.platform;
const _add = (type, listener) => {
platform.addEventListener(this, type, listener);
listeners[type] = listener;
};
const listener = (e, x, y) => {
e.offsetX = x;
e.offsetY = y;
this._eventHandler(e);
};
each(this.options.events, (type) => _add(type, listener));
}
/**
* @private
*/
bindResponsiveEvents() {
if (!this._responsiveListeners) {
this._responsiveListeners = {};
}
const listeners = this._responsiveListeners;
const platform = this.platform;
const _add = (type, listener) => {
platform.addEventListener(this, type, listener);
listeners[type] = listener;
};
const _remove = (type, listener) => {
if (listeners[type]) {
platform.removeEventListener(this, type, listener);
delete listeners[type];
}
};
const listener = (width, height) => {
if (this.canvas) {
this.resize(width, height);
}
};
let detached; // eslint-disable-line prefer-const
const attached = () => {
_remove('attach', attached);
this.attached = true;
this.resize();
_add('resize', listener);
_add('detach', detached);
};
detached = () => {
this.attached = false;
_remove('resize', listener);
// Stop animating and remove metasets, so when re-attached, the animations start from beginning.
this._stop();
this._resize(0, 0);
_add('attach', attached);
};
if (platform.isAttached(this.canvas)) {
attached();
} else {
detached();
}
}
/**
* @private
*/
unbindEvents() {
each(this._listeners, (listener, type) => {
this.platform.removeEventListener(this, type, listener);
});
this._listeners = {};
each(this._responsiveListeners, (listener, type) => {
this.platform.removeEventListener(this, type, listener);
});
this._responsiveListeners = undefined;
}
updateHoverStyle(items, mode, enabled) {
const prefix = enabled ? 'set' : 'remove';
let meta, item, i, ilen;
if (mode === 'dataset') {
meta = this.getDatasetMeta(items[0].datasetIndex);
meta.controller['_' + prefix + 'DatasetHoverStyle']();
}
for (i = 0, ilen = items.length; i < ilen; ++i) {
item = items[i];
const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
if (controller) {
controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
}
}
}
/**
* Get active (hovered) elements
* @returns array
*/
getActiveElements() {
return this._active || [];
}
/**
* Set active (hovered) elements
* @param {array} activeElements New active data points
*/
setActiveElements(activeElements) {
const lastActive = this._active || [];
const active = activeElements.map(({datasetIndex, index}) => {
const meta = this.getDatasetMeta(datasetIndex);
if (!meta) {
throw new Error('No dataset found at index ' + datasetIndex);
}
return {
datasetIndex,
element: meta.data[index],
index,
};
});
const changed = !_elementsEqual(active, lastActive);
if (changed) {
this._active = active;
// Make sure we don't use the previous mouse event to override the active elements in update.
this._lastEvent = null;
this._updateHoverStyles(active, lastActive);
}
}
/**
* Calls enabled plugins on the specified hook and with the given args.
* This method immediately returns as soon as a plugin explicitly returns false. The
* returned value can be used, for instance, to interrupt the current action.
* @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
* @param {Object} [args] - Extra arguments to apply to the hook call.
* @param {import('./core.plugins').filterCallback} [filter] - Filtering function for limiting which plugins are notified
* @returns {boolean} false if any of the plugins return false, else returns true.
*/
notifyPlugins(hook, args, filter) {
return this._plugins.notify(this, hook, args, filter);
}
/**
* @private
*/
_updateHoverStyles(active, lastActive, replay) {
const hoverOptions = this.options.hover;
const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));
const deactivated = diff(lastActive, active);
const activated = replay ? active : diff(active, lastActive);
if (deactivated.length) {
this.updateHoverStyle(deactivated, hoverOptions.mode, false);
}
if (activated.length && hoverOptions.mode) {
this.updateHoverStyle(activated, hoverOptions.mode, true);
}
}
/**
* @private
*/
_eventHandler(e, replay) {
const args = {
event: e,
replay,
cancelable: true,
inChartArea: this.isPointInArea(e)
};
const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type);
if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
return;
}
const changed = this._handleEvent(e, replay, args.inChartArea);
args.cancelable = false;
this.notifyPlugins('afterEvent', args, eventFilter);
if (changed || args.changed) {
this.render();
}
return this;
}
/**
* Handle an event
* @param {ChartEvent} e the event to handle
* @param {boolean} [replay] - true if the event was replayed by `update`
* @param {boolean} [inChartArea] - true if the event is inside chartArea
* @return {boolean} true if the chart needs to re-render
* @private
*/
_handleEvent(e, replay, inChartArea) {
const {_active: lastActive = [], options} = this;
// If the event is replayed from `update`, we should evaluate with the final positions.
//
// The `replay`:
// It's the last event (excluding click) that has occurred before `update`.
// So mouse has not moved. It's also over the chart, because there is a `replay`.
//
// The why:
// If animations are active, the elements haven't moved yet compared to state before update.
// But if they will, we are activating the elements that would be active, if this check
// was done after the animations have completed. => "final positions".
// If there is no animations, the "final" and "current" positions are equal.
// This is done so we do not have to evaluate the active elements each animation frame
// - it would be expensive.
const useFinalPosition = replay;
const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
const isClick = _isClickEvent(e);
const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
if (inChartArea) {
// Set _lastEvent to null while we are processing the event handlers.
// This prevents recursion if the handler calls chart.update()
this._lastEvent = null;
// Invoke onHover hook
callCallback(options.onHover, [e, active, this], this);
if (isClick) {
callCallback(options.onClick, [e, active, this], this);
}
}
const changed = !_elementsEqual(active, lastActive);
if (changed || replay) {
this._active = active;
this._updateHoverStyles(active, lastActive, replay);
}
this._lastEvent = lastEvent;
return changed;
}
/**
* @param {ChartEvent} e - The event
* @param {import('../../types').ActiveElement[]} lastActive - Previously active elements
* @param {boolean} inChartArea - Is the envent inside chartArea
* @param {boolean} useFinalPosition - Should the evaluation be done with current or final (after animation) element positions
* @returns {import('../../types').ActiveElement[]} - The active elements
* @pravate
*/
_getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
if (e.type === 'mouseout') {
return [];
}
if (!inChartArea) {
// Let user control the active elements outside chartArea. Eg. using Legend.
return lastActive;
}
const hoverOptions = this.options.hover;
return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
}
}
// @ts-ignore
function invalidatePlugins() {
return each(Chart.instances, (chart) => chart._plugins.invalidate());
}
export default Chart;
| {
"content_hash": "29e1760f97c336b1e77d238dada63267",
"timestamp": "",
"source": "github",
"line_count": 1266,
"max_line_length": 170,
"avg_line_length": 28.199842022116904,
"alnum_prop": 0.6275454469062491,
"repo_name": "touletan/Chart.js",
"id": "17394c9335d4bfd9b84946ae111aaa7af852ff67",
"size": "35701",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/core.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2286"
},
{
"name": "JavaScript",
"bytes": "1249741"
},
{
"name": "Shell",
"bytes": "2450"
},
{
"name": "TypeScript",
"bytes": "47594"
}
],
"symlink_target": ""
} |
import {map, Width, Height, MapWidth, MapHeight, BlockSize} from "./global.js";
import {game, scene, camera, display, input, layerLand, layerAnimals, Global} from "./global.js";
import { Block, initMap } from "./map.js";
import { Animal } from "./animal.js";
import { Deer, DeerControl } from "./deer.js";
import { Sound, SoundSpread } from "./sound.js";
import { Tiger } from "./tiger.js";
scene.addInput(input);
scene.addLayer(layerAnimals, 1);
scene.physics.f = 500;
scene.worldBackground = "#fffeb5";
game.start();
// Block Rendering
layerLand.onEndRender = function (args)
{
var o = input.coordinate.pointMapTo(Coordinate.Default, 0, Height);
var xto = input.coordinate.pointMapTo(Coordinate.Default, Width, 0);
var yto = input.coordinate.pointMapTo(Coordinate.Default, 0, 0);
o = new Vector2(parseInt(o.x / BlockSize)-3, parseInt(o.y / BlockSize)-3);
xto = parseInt(xto.x / BlockSize)+3;
yto = parseInt(yto.y / BlockSize)+3;
for (var x = o.x; x < xto; x++) {
for (var y = o.y; y < yto; y++) {
if (!map[x] || !map[x][y] || map[x][y].type == Block.Types.Sand)
continue;
switch(map[x][y].type)
{
case Block.Types.Sand:
//args.graphics.fillStyle = "#fffeb5";
break;
case Block.Types.Grass:
args.graphics.fillStyle = "#92d480";
args.graphics.fillStyle = new Color(146, 212, 128, map[x][y].resource / Block.MaxResource).toString();
break;
case Block.Types.Wood:
args.graphics.fillStyle = "#278165";
}
args.graphics.fillRect(x * BlockSize, (y+1) * BlockSize, BlockSize, BlockSize);
}
}
}
// Mouse Control
scene.onWheel = function (e)
{
if (e.wheelDelta < 0) {
camera.zoomTo(camera.zoom * 1.2, e.x, e.y);
}
else {
camera.zoomTo(camera.zoom * (1 / 1.2), e.x, e.y);
}
}
var mouseHold = false;
input.onMouseDown = function (e)
{
mouseHold = true;
}
input.onMouseUp = function (e)
{
mouseHold = false;
}
input.onMouseMove = function (e)
{
if (mouseHold)
camera.moveTo(camera.position.x - e.dx * input.coordinate.unitX, camera.position.y - e.dy * input.coordinate.unitY);
if (e.x < 10)
{
}
}
scene.onMouseMove = function (e)
{
debug.innerText = e.x + "," + e.y;
}
scene.onClick = function (e)
{
if (e.button == Mouse.Buttons.Right && deer)
{
deer.changeState(new DeerControl(deer));
deer.state.target = new Vector2(e.x, e.y);
}
else if (e.button == Mouse.Buttons.Left)
{
Global.AddEntity(new Tiger(Global.RegisterID(), e.x, e.y));
var sound = new Sound(Global.RegisterID(), deer, 10, e.x, e.y, 400);
Global.AddEntity(sound);
}
}
//var tiger = new Tiger(0);
var deer = new Deer(Global.RegisterID(), 0, 0);
Global.AddEntity(deer);
deer.gameObject.hitTest = true;
deer.gameObject.onClick = function (e)
{
e.handled = true;
}
//deer.state = new DeerGlobalState(deer);
for (let i = 0; i < 500; i++)
{
let deer = new Deer(Global.RegisterID(), Math.random() * MapWidth * BlockSize, Math.random() * MapHeight * BlockSize);
Global.AddEntity(deer);
deer.gameObject.hitTest = true;
deer.gameObject.onClick = function (e)
{
e.handled = true;
}
}
for (let i = 0; i < 50; i++)
{
Global.AddEntity(new Tiger(Global.RegisterID(), Math.random() * MapWidth * BlockSize, Math.random() * MapHeight * BlockSize));
} | {
"content_hash": "771c91eccab6fe684ab89a1f768f0a1f",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 130,
"avg_line_length": 31.52212389380531,
"alnum_prop": 0.592363840539023,
"repo_name": "SardineFish/SarEngine2D",
"id": "0d558d438047820a29d95f06b025e92d3c8ee430",
"size": "3562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SardineFish.Web.Engine2D/games-dev/LandSim/script.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100448"
},
{
"name": "HTML",
"bytes": "147269"
},
{
"name": "JavaScript",
"bytes": "890511"
}
],
"symlink_target": ""
} |
package com.kodcu.logging;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Created by usta on 04.06.2015.
*/
public class MyLog {
private StringProperty level = new SimpleStringProperty();
private StringProperty message = new SimpleStringProperty();
public MyLog(String level, String message) {
this.level.setValue(level);
this.message.setValue(message);
}
public String getLevel() {
return level.get();
}
public StringProperty levelProperty() {
return level;
}
public void setLevel(String level) {
this.level.set(level);
}
public String getMessage() {
return message.get();
}
public StringProperty messageProperty() {
return message;
}
public void setMessage(String message) {
this.message.set(message);
}
}
| {
"content_hash": "67b1f14af4fa77c7a8fa3b6ab846e7a6",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 64,
"avg_line_length": 21.5,
"alnum_prop": 0.655592469545958,
"repo_name": "lefou/AsciidocFX",
"id": "ff9cf1ac93bf4aef0841b39b32324079d8d630f7",
"size": "903",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/main/java/com/kodcu/logging/MyLog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18732"
},
{
"name": "HTML",
"bytes": "82130"
},
{
"name": "Java",
"bytes": "31716253"
}
],
"symlink_target": ""
} |
"""An implementation of the Zephyr Abstract Syntax Definition Language.
See http://asdl.sourceforge.net/ and
http://www.cs.princeton.edu/research/techreps/TR-554-97
Only supports top level module decl, not view. I'm guessing that view
is intended to support the browser and I'm not interested in the
browser.
Changes for Python: Add support for module versions
"""
import os
import sys
import traceback
import spark
def output(*strings):
for s in strings:
sys.stdout.write(str(s) + "\n")
class Token(object):
# spark seems to dispatch in the parser based on a token's
# type attribute
def __init__(self, type, lineno):
self.type = type
self.lineno = lineno
def __str__(self):
return self.type
def __repr__(self):
return str(self)
class Id(Token):
def __init__(self, value, lineno):
self.type = 'Id'
self.value = value
self.lineno = lineno
def __str__(self):
return self.value
class String(Token):
def __init__(self, value, lineno):
self.type = 'String'
self.value = value
self.lineno = lineno
class ASDLSyntaxError(Exception):
def __init__(self, lineno, token=None, msg=None):
self.lineno = lineno
self.token = token
self.msg = msg
def __str__(self):
if self.msg is None:
return "Error at '%s', line %d" % (self.token, self.lineno)
else:
return "%s, line %d" % (self.msg, self.lineno)
class ASDLScanner(spark.GenericScanner, object):
def tokenize(self, input):
self.rv = []
self.lineno = 1
super(ASDLScanner, self).tokenize(input)
return self.rv
def t_id(self, s):
r"[\w\.]+"
# XXX doesn't distinguish upper vs. lower, which is
# significant for ASDL.
self.rv.append(Id(s, self.lineno))
def t_string(self, s):
r'"[^"]*"'
self.rv.append(String(s, self.lineno))
def t_xxx(self, s): # not sure what this production means
r"<="
self.rv.append(Token(s, self.lineno))
def t_punctuation(self, s):
r"[\{\}\*\=\|\(\)\,\?\:]"
self.rv.append(Token(s, self.lineno))
def t_comment(self, s):
r"\-\-[^\n]*"
pass
def t_newline(self, s):
r"\n"
self.lineno += 1
def t_whitespace(self, s):
r"[ \t]+"
pass
def t_default(self, s):
r" . +"
raise ValueError("unmatched input: %r" % s)
class ASDLParser(spark.GenericParser, object):
def __init__(self):
super(ASDLParser, self).__init__("module")
def typestring(self, tok):
return tok.type
def error(self, tok):
raise ASDLSyntaxError(tok.lineno, tok)
def p_module_0(self, info):
" module ::= Id Id { } "
module, name, _0, _1 = info
if module.value != "module":
raise ASDLSyntaxError(module.lineno,
msg="expected 'module', found %s" % module)
return Module(name, None)
def p_module(self, info):
" module ::= Id Id { definitions } "
module, name, _0, definitions, _1 = info
if module.value != "module":
raise ASDLSyntaxError(module.lineno,
msg="expected 'module', found %s" % module)
return Module(name, definitions)
def p_definition_0(self, definition):
" definitions ::= definition "
return definition[0]
def p_definition_1(self, definitions):
" definitions ::= definition definitions "
return definitions[0] + definitions[1]
def p_definition(self, info):
" definition ::= Id = type "
id, _, type = info
return [Type(id, type)]
def p_type_0(self, product):
" type ::= product "
return product[0]
def p_type_1(self, sum):
" type ::= sum "
return Sum(sum[0])
def p_type_2(self, info):
" type ::= sum Id ( fields ) "
sum, id, _0, attributes, _1 = info
if id.value != "attributes":
raise ASDLSyntaxError(id.lineno,
msg="expected attributes, found %s" % id)
return Sum(sum, attributes)
def p_product_0(self, info):
" product ::= ( fields ) "
_0, fields, _1 = info
return Product(fields)
def p_product_1(self, info):
" product ::= ( fields ) Id ( fields ) "
_0, fields, _1, id, _2, attributes, _3 = info
if id.value != "attributes":
raise ASDLSyntaxError(id.lineno,
msg="expected attributes, found %s" % id)
return Product(fields, attributes)
def p_sum_0(self, constructor):
" sum ::= constructor "
return [constructor[0]]
def p_sum_1(self, info):
" sum ::= constructor | sum "
constructor, _, sum = info
return [constructor] + sum
def p_sum_2(self, info):
" sum ::= constructor | sum "
constructor, _, sum = info
return [constructor] + sum
def p_constructor_0(self, id):
" constructor ::= Id "
return Constructor(id[0])
def p_constructor_1(self, info):
" constructor ::= Id ( fields ) "
id, _0, fields, _1 = info
return Constructor(id, fields)
def p_fields_0(self, field):
" fields ::= field "
return [field[0]]
def p_fields_1(self, info):
" fields ::= fields , field "
fields, _, field = info
return fields + [field]
def p_field_0(self, type_):
" field ::= Id "
return Field(type_[0])
def p_field_1(self, info):
" field ::= Id Id "
type, name = info
return Field(type, name)
def p_field_2(self, info):
" field ::= Id * Id "
type, _, name = info
return Field(type, name, seq=True)
def p_field_3(self, info):
" field ::= Id ? Id "
type, _, name = info
return Field(type, name, opt=True)
def p_field_4(self, type_):
" field ::= Id * "
return Field(type_[0], seq=True)
def p_field_5(self, type_):
" field ::= Id ? "
return Field(type[0], opt=True)
builtin_types = ("identifier", "string", "bytes", "int", "object", "singleton")
# below is a collection of classes to capture the AST of an AST :-)
# not sure if any of the methods are useful yet, but I'm adding them
# piecemeal as they seem helpful
class AST(object):
pass # a marker class
class Module(AST):
def __init__(self, name, dfns):
self.name = name
self.dfns = dfns
self.types = {} # maps type name to value (from dfns)
for type in dfns:
self.types[type.name.value] = type.value
def __repr__(self):
return "Module(%s, %s)" % (self.name, self.dfns)
class Type(AST):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Type(%s, %s)" % (self.name, self.value)
class Constructor(AST):
def __init__(self, name, fields=None):
self.name = name
self.fields = fields or []
def __repr__(self):
return "Constructor(%s, %s)" % (self.name, self.fields)
class Field(AST):
def __init__(self, type, name=None, seq=False, opt=False):
self.type = type
self.name = name
self.seq = seq
self.opt = opt
def __repr__(self):
if self.seq:
extra = ", seq=True"
elif self.opt:
extra = ", opt=True"
else:
extra = ""
if self.name is None:
return "Field(%s%s)" % (self.type, extra)
else:
return "Field(%s, %s%s)" % (self.type, self.name, extra)
class Sum(AST):
def __init__(self, types, attributes=None):
self.types = types
self.attributes = attributes or []
def __repr__(self):
if self.attributes is None:
return "Sum(%s)" % self.types
else:
return "Sum(%s, %s)" % (self.types, self.attributes)
class Product(AST):
def __init__(self, fields, attributes=None):
self.fields = fields
self.attributes = attributes or []
def __repr__(self):
if self.attributes is None:
return "Product(%s)" % self.fields
else:
return "Product(%s, %s)" % (self.fields, self.attributes)
class VisitorBase(object):
def __init__(self, skip=False):
self.cache = {}
self.skip = skip
def visit(self, object, *args):
meth = self._dispatch(object)
if meth is None:
return
try:
meth(object, *args)
except Exception:
output("Error visiting" + repr(object))
output(str(sys.exc_info()[1]))
traceback.print_exc()
# XXX hack
if hasattr(self, 'file'):
self.file.flush()
os._exit(1)
def _dispatch(self, object):
assert isinstance(object, AST), repr(object)
klass = object.__class__
meth = self.cache.get(klass)
if meth is None:
methname = "visit" + klass.__name__
if self.skip:
meth = getattr(self, methname, None)
else:
meth = getattr(self, methname)
self.cache[klass] = meth
return meth
class Check(VisitorBase):
def __init__(self):
super(Check, self).__init__(skip=True)
self.cons = {}
self.errors = 0
self.types = {}
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
conflict = self.cons.get(key)
if conflict is None:
self.cons[key] = name
else:
output("Redefinition of constructor %s" % key)
output("Defined in %s and %s" % (conflict, name))
self.errors += 1
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
key = str(field.type)
l = self.types.setdefault(key, [])
l.append(name)
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
def check(mod):
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
uses = ", ".join(v.types[t])
output("Undefined type %s, used in %s" % (t, uses))
return not v.errors
def parse(file):
scanner = ASDLScanner()
parser = ASDLParser()
f = open(file)
try:
buf = f.read()
finally:
f.close()
tokens = scanner.tokenize(buf)
try:
return parser.parse(tokens)
except ASDLSyntaxError:
err = sys.exc_info()[1]
output(str(err))
lines = buf.split("\n")
output(lines[err.lineno - 1]) # lines starts at 0, files at 1
if __name__ == "__main__":
import glob
import sys
if len(sys.argv) > 1:
files = sys.argv[1:]
else:
testdir = "tests"
files = glob.glob(testdir + "/*.asdl")
for file in files:
output(file)
mod = parse(file)
if not mod:
break
output("module", mod.name)
output(len(mod.dfns), "definitions")
if not check(mod):
output("Check failed")
else:
for dfn in mod.dfns:
output(dfn.name, dfn.value)
| {
"content_hash": "6e37e10bee26e62d84361cbee1cd5e47",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 79,
"avg_line_length": 26.96330275229358,
"alnum_prop": 0.5340251786321878,
"repo_name": "OptimusGitEtna/RestSymf",
"id": "fc1b16c668153f630234377d9b33e2059750ceee",
"size": "11756",
"binary": false,
"copies": "36",
"ref": "refs/heads/master",
"path": "Python-3.4.2/Parser/asdl.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "594205"
},
{
"name": "C",
"bytes": "15348597"
},
{
"name": "C++",
"bytes": "65109"
},
{
"name": "CSS",
"bytes": "12039"
},
{
"name": "Common Lisp",
"bytes": "24481"
},
{
"name": "JavaScript",
"bytes": "10597"
},
{
"name": "Makefile",
"bytes": "9444"
},
{
"name": "Objective-C",
"bytes": "1390141"
},
{
"name": "PHP",
"bytes": "93070"
},
{
"name": "PowerShell",
"bytes": "1420"
},
{
"name": "Prolog",
"bytes": "557"
},
{
"name": "Python",
"bytes": "24018306"
},
{
"name": "Shell",
"bytes": "440753"
},
{
"name": "TeX",
"bytes": "323102"
},
{
"name": "Visual Basic",
"bytes": "481"
}
],
"symlink_target": ""
} |
@interface LaboratorioProtocoloTests : XCTestCase
@end
@implementation LaboratorioProtocoloTests
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample
{
XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}
@end
| {
"content_hash": "54996ec3825fd95b24ecc353f7754bd5",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 107,
"avg_line_length": 20.541666666666668,
"alnum_prop": 0.7079107505070994,
"repo_name": "montselozanod/iOS",
"id": "8e6a6430c61f2019dde7d6f79519b8c788e251dc",
"size": "695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LaboratorioProtocolo/LaboratorioProtocoloTests/LaboratorioProtocoloTests.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "266731"
}
],
"symlink_target": ""
} |
name: Question
about: Ask for help or start a discussion
title: 'Question: '
labels: question
---
<!--
1. Make sure your question hasn't been asked before.
2. Please only ask questions that are related to this project.
3. Don't give away secrets, your issue will be public.
-->
| {
"content_hash": "b9d6204136e7855e73b6db472c545d74",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 62,
"avg_line_length": 23.333333333333332,
"alnum_prop": 0.7285714285714285,
"repo_name": "cryptii/cryptii",
"id": "f7106852bc3eefd06c09edecafc753dc51a6901b",
"size": "284",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": ".github/ISSUE_TEMPLATE/Question.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3817"
},
{
"name": "JavaScript",
"bytes": "605363"
},
{
"name": "SCSS",
"bytes": "35478"
}
],
"symlink_target": ""
} |
import psycopg2 as db
import sys
import os
from flask import Flask, request, Response, render_template, session, redirect, json
from twilio import twiml
from twilio.rest import TwilioRestClient
import imp
#loads account_sid and auth_token from private space
config = imp.load_source('config', '../sensitive_data/config.py')
TWILIO_ACCOUNT_SID = config.TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN = config.TWILIO_AUTH_TOKEN
app = Flask(__name__, template_folder='templates')
app.secret_key = config.SECRET_KEY
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
requests = {}
# connect to doctor database
try:
con = db.connect(database="testdbdoc", user="postgres", password="seetoh", host="localhost")
print 'Successfully connected to databases!'
cur = con.cursor()
except:
print 'Failed to connect to database.'
@app.route('/receivemessage', methods = ['GET', 'POST'])
def receivemessage():
body = request.values.get('Body', None)
fromnum = request.values.get('From', None)
r = twiml.Response()
body = body.lower()
try:
answer = body[0]
request_id = body[1:]
if answer == 'y':
# This does prevent us from tracking multiple requests to a doctor, and requires him to respond only to the newest one.
# Will add a method to deconflict clashes in requests from the same area
if requests[request_id] == False:
requests[request_id] = True
r.message("Thank you for replying. You are the first to accept and other doctors will not be able to accept this request \
already. A message will be sent to the requester to let him know you are on the way.")
# create a response to the requestor
elif requests[request_id] == True:
r.message("Thank you for replying. Another doctor is on the way to the scene already, but we appreciate your prompt \
response. Have a good day.")
else:
r.message("The request is no longer valid, thank you for replying.")
elif answer == 'n':
r.message("Sorry to hear that, thank you for your prompt response, have a good day.")
else:
r.message("Invalid response.")
except:
r.message("Invalid response.")
# has to be valid twiml
return str(r)
@app.route('/sendmessage', methods = ['POST', 'GET'])
def sendmessage():
# Test values
# Need to add either a request database or a function that carries the request values in. I prefer database.
zipcode = '94720' # requester zipcode
username = 'danielseetoh' # just to message only me
request_id = '1' # retrieve request id in table request
requests[request_id] = False
# will add the ability to track gps location of requester to match locally with doctors nearby
# for now just testing by matching zipcode
cur.execute("SELECT phonenumber FROM doctors WHERE zipcode = '%s' AND username = '%s'" % (zipcode, username))
doctor_phone_numbers = cur.fetchall()
for number in doctor_phone_numbers:
client.messages.create(
body = "Request id: %s. There is an emergency at '%s', will you be able to respond in \
less than 8 minutes?(y%s/n%s)" % (request_id, zipcode, request_id, request_id),
to = number[0],
from_ = "+14245438814",
)
print session['requestor']
return('Messages sent')
@app.route('/')
def index(name = None):
return render_template('index.html', name=name)
@app.route('/signup', methods = ['POST', 'GET'])
def signup():
if request.method == 'POST':
try:
# insert into database
_username = request.form['username']
_password = request.form['password']
_phonenumber = request.form['phonenumber']
_zipcode = request.form['zipcode']
return redirect('/', name = _username)
cur.execute("INSERT INTO doctors (username, password, phonenumber, zipcode, active) \
VALUES ('%s', '%s', '%s', '%s', True ) " % (_username, _password, _phonenumber, _zipcode))
return redirect('/', name = _username)
except:
error = 'Unable to insert into database. {} {} {} {}'.format(_username,_password,_phonenumber,_zipcode)
return render_template('signup.html', error=error)
else:
return render_template('signup.html', error=error)
# if request.method == 'POST':
# if request.form['username'] != 'admin' or request.form['password'] != 'admin':
# error = 'Invalid Credentials. Please try again.'
# else:
# return redirect(url_for('home'))
# _username = request.form['username']
# _password = request.form['password']
# _phonenumber = request.form['phonenumber']
# _zipcode = request.form['zipcode']
# if not (_username and _password and _phonenumber and _zipcode):
# return json.dumps({'html':'<span>Enter the required fields</span>'})
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=8080)
| {
"content_hash": "a2d7efffd093beab510edc1277b23f2b",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 138,
"avg_line_length": 38.355555555555554,
"alnum_prop": 0.6235998455001931,
"repo_name": "danielseetoh/twilio185",
"id": "43ef0c0cd78ef4efbf7b32bf35b8172c36574a86",
"size": "5178",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": ".~c9_invoke_aGP52y.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "928"
},
{
"name": "HTML",
"bytes": "23891"
},
{
"name": "JavaScript",
"bytes": "825"
},
{
"name": "Python",
"bytes": "31797"
}
],
"symlink_target": ""
} |
package io.gatling.http.check.async
import io.gatling.core.check.extractor.jsonpath._
import io.gatling.core.check.{ Extender, DefaultMultipleFindCheckBuilder, Preparer }
import io.gatling.core.json.JsonParsers
import io.gatling.core.session.Expression
import io.gatling.http.check.body.HttpBodyJsonpJsonPathCheckBuilder
trait AsyncJsonpJsonPathOfType {
self: AsyncJsonpJsonPathCheckBuilder[String] =>
def ofType[X: JsonFilter](implicit extractorFactory: JsonPathExtractorFactory) =
new AsyncJsonpJsonPathCheckBuilder[X](path, extender, jsonParsers)
}
object AsyncJsonpJsonPathCheckBuilder {
def asyncJsonpPreparer(jsonParsers: JsonParsers): Preparer[String, Any] = HttpBodyJsonpJsonPathCheckBuilder.parseJsonpString(_, jsonParsers)
def jsonpJsonPath(path: Expression[String], extender: Extender[AsyncCheck, String])(implicit extractorFactory: JsonPathExtractorFactory, jsonParsers: JsonParsers) =
new AsyncJsonpJsonPathCheckBuilder[String](path, extender, jsonParsers) with AsyncJsonpJsonPathOfType
}
class AsyncJsonpJsonPathCheckBuilder[X: JsonFilter](
private[async] val path: Expression[String],
private[async] val extender: Extender[AsyncCheck, String],
private[async] val jsonParsers: JsonParsers
)(implicit extractorFactory: JsonPathExtractorFactory)
extends DefaultMultipleFindCheckBuilder[AsyncCheck, String, Any, X](extender, AsyncJsonpJsonPathCheckBuilder.asyncJsonpPreparer(jsonParsers)) {
import extractorFactory._
def findExtractor(occurrence: Int) = path.map(newSingleExtractor[X](_, occurrence))
def findAllExtractor = path.map(newMultipleExtractor[X])
def countExtractor = path.map(newCountExtractor)
}
| {
"content_hash": "96a9131fd6430a7d196929a532d42f20",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 166,
"avg_line_length": 45.24324324324324,
"alnum_prop": 0.8148148148148148,
"repo_name": "GabrielPlassard/gatling",
"id": "24cdb66894b99672f49ce0e5754aa431381036e9",
"size": "2291",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "gatling-http/src/main/scala/io/gatling/http/check/async/AsyncJsonpJsonPathCheckBuilder.scala",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5236"
},
{
"name": "CSS",
"bytes": "10422"
},
{
"name": "HTML",
"bytes": "167248"
},
{
"name": "JavaScript",
"bytes": "3690"
},
{
"name": "Python",
"bytes": "7472"
},
{
"name": "Scala",
"bytes": "1777171"
},
{
"name": "Shell",
"bytes": "6122"
}
],
"symlink_target": ""
} |
import { encode as base64url } from '../../runtime/base64url.js';
import encrypt from '../../runtime/encrypt.js';
import { deflate } from '../../runtime/zlib.js';
import generateIv from '../../lib/iv.js';
import encryptKeyManagement from '../../lib/encrypt_key_management.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import isDisjoint from '../../lib/is_disjoint.js';
import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
import validateCrit from '../../lib/validate_crit.js';
class FlattenedEncrypt {
constructor(plaintext) {
if (!(plaintext instanceof Uint8Array)) {
throw new TypeError('plaintext must be an instance of Uint8Array');
}
this._plaintext = plaintext;
}
setKeyManagementParameters(parameters) {
if (this._keyManagementParameters) {
throw new TypeError('setKeyManagementParameters can only be called once');
}
this._keyManagementParameters = parameters;
return this;
}
setProtectedHeader(protectedHeader) {
if (this._protectedHeader) {
throw new TypeError('setProtectedHeader can only be called once');
}
this._protectedHeader = protectedHeader;
return this;
}
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
if (this._sharedUnprotectedHeader) {
throw new TypeError('setSharedUnprotectedHeader can only be called once');
}
this._sharedUnprotectedHeader = sharedUnprotectedHeader;
return this;
}
setUnprotectedHeader(unprotectedHeader) {
if (this._unprotectedHeader) {
throw new TypeError('setUnprotectedHeader can only be called once');
}
this._unprotectedHeader = unprotectedHeader;
return this;
}
setAdditionalAuthenticatedData(aad) {
this._aad = aad;
return this;
}
setContentEncryptionKey(cek) {
if (this._cek) {
throw new TypeError('setContentEncryptionKey can only be called once');
}
this._cek = cek;
return this;
}
setInitializationVector(iv) {
if (this._iv) {
throw new TypeError('setInitializationVector can only be called once');
}
this._iv = iv;
return this;
}
async encrypt(key, options) {
if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
}
if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
throw new JWEInvalid('JWE Shared Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
}
const joseHeader = {
...this._protectedHeader,
...this._unprotectedHeader,
...this._sharedUnprotectedHeader,
};
validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
if (joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value');
}
}
const { alg, enc } = joseHeader;
if (typeof alg !== 'string' || !alg) {
throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
}
if (typeof enc !== 'string' || !enc) {
throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
}
let encryptedKey;
if (alg === 'dir') {
if (this._cek) {
throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption');
}
}
else if (alg === 'ECDH-ES') {
if (this._cek) {
throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement');
}
}
let cek;
{
let parameters;
({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters));
if (parameters) {
if (!this._protectedHeader) {
this.setProtectedHeader(parameters);
}
else {
this._protectedHeader = { ...this._protectedHeader, ...parameters };
}
}
}
this._iv || (this._iv = generateIv(enc));
let additionalData;
let protectedHeader;
let aadMember;
if (this._protectedHeader) {
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
}
else {
protectedHeader = encoder.encode('');
}
if (this._aad) {
aadMember = base64url(this._aad);
additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));
}
else {
additionalData = protectedHeader;
}
let ciphertext;
let tag;
if (joseHeader.zip === 'DEF') {
const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext);
({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData));
}
else {
;
({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData));
}
const jwe = {
ciphertext: base64url(ciphertext),
iv: base64url(this._iv),
tag: base64url(tag),
};
if (encryptedKey) {
jwe.encrypted_key = base64url(encryptedKey);
}
if (aadMember) {
jwe.aad = aadMember;
}
if (this._protectedHeader) {
jwe.protected = decoder.decode(protectedHeader);
}
if (this._sharedUnprotectedHeader) {
jwe.unprotected = this._sharedUnprotectedHeader;
}
if (this._unprotectedHeader) {
jwe.header = this._unprotectedHeader;
}
return jwe;
}
}
export { FlattenedEncrypt };
export default FlattenedEncrypt;
| {
"content_hash": "70aa6a43a5165c5035c874402370f1d9",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 145,
"avg_line_length": 40.18072289156626,
"alnum_prop": 0.5835082458770615,
"repo_name": "cdnjs/cdnjs",
"id": "287856d3d3d38348160fdd10ac87744065a6678b",
"size": "6670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/jose/3.20.3/jwe/flattened/encrypt.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package executable
import (
"errors"
"testing"
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/testhelper"
"github.com/stretchr/testify/require"
)
type fakeOs struct {
OldExecutable func() (string, error)
Path string
Error error
}
func (f *fakeOs) Executable() (string, error) {
return f.Path, f.Error
}
func (f *fakeOs) Setup() {
f.OldExecutable = osExecutable
osExecutable = f.Executable
}
func (f *fakeOs) Cleanup() {
osExecutable = f.OldExecutable
}
func TestNewSuccess(t *testing.T) {
testCases := []struct {
desc string
fakeOs *fakeOs
environment map[string]string
expectedRootDir string
}{
{
desc: "GITLAB_SHELL_DIR env var is not defined",
fakeOs: &fakeOs{Path: "/tmp/bin/gitlab-shell"},
expectedRootDir: "/tmp",
},
{
desc: "GITLAB_SHELL_DIR env var is defined",
fakeOs: &fakeOs{Path: "/opt/bin/gitlab-shell"},
environment: map[string]string{
"GITLAB_SHELL_DIR": "/tmp",
},
expectedRootDir: "/tmp",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
restoreEnv := testhelper.TempEnv(tc.environment)
defer restoreEnv()
fake := tc.fakeOs
fake.Setup()
defer fake.Cleanup()
result, err := New("gitlab-shell")
require.NoError(t, err)
require.Equal(t, result.Name, "gitlab-shell")
require.Equal(t, result.RootDir, tc.expectedRootDir)
})
}
}
func TestNewFailure(t *testing.T) {
testCases := []struct {
desc string
fakeOs *fakeOs
environment map[string]string
}{
{
desc: "failed to determine executable",
fakeOs: &fakeOs{Path: "", Error: errors.New("error")},
},
{
desc: "GITLAB_SHELL_DIR doesn't exist",
fakeOs: &fakeOs{Path: "/tmp/bin/gitlab-shell"},
environment: map[string]string{
"GITLAB_SHELL_DIR": "/tmp/non/existing/directory",
},
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
restoreEnv := testhelper.TempEnv(tc.environment)
defer restoreEnv()
fake := tc.fakeOs
fake.Setup()
defer fake.Cleanup()
_, err := New("gitlab-shell")
require.Error(t, err)
})
}
}
| {
"content_hash": "db3decab8772e8ad6ee6bc6efdbfa1fc",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 62,
"avg_line_length": 20.817307692307693,
"alnum_prop": 0.6300230946882217,
"repo_name": "gitlabhq/gitlab-shell",
"id": "498f728e4a4a46bacdc6beed54ba26446e1c9e61",
"size": "2165",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "internal/executable/executable_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "89"
},
{
"name": "Go",
"bytes": "323279"
},
{
"name": "Makefile",
"bytes": "2289"
},
{
"name": "Ruby",
"bytes": "34551"
},
{
"name": "Shell",
"bytes": "506"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Tests\Bridge\Doctrine\Form\Fixtures;
/** @Entity */
class SingleIdentEntity
{
/** @Id @Column(type="integer") */
protected $id;
/** @Column(type="string") */
public $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
} | {
"content_hash": "e0c1ccdffaf48450e7aa2b938f92e5bb",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 54,
"avg_line_length": 17.944444444444443,
"alnum_prop": 0.56656346749226,
"repo_name": "who/symfony",
"id": "8f5e9a57ca17c7f3e2895e00c05df77604814f91",
"size": "323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Symfony/Tests/Bridge/Doctrine/Fixtures/SingleIdentEntity.php",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
static const int arr_size = 1024;
static const int iterations = 1000;
int count_if(int limit, int* array){
int temp = 0;
for (int i = 0; i < arr_size; ++i){
temp += (array[i] < limit)? 1 : 0;
}
return temp;
}
void measure_branch_predictions(){
std::cout << "Branch prediction benchmark.\n";
int array[arr_size];
for (int i = 0; i < arr_size; ++i){
array[i] = rand() % 10;
}
for (int boundary = 0; boundary <= 10; ++boundary){
auto start_time = std::chrono::steady_clock::now();
uint32_t temp = 0;
for (int iter = 0; iter < iterations; ++iter){
temp += count_if(boundary, array);
}
auto end_time = std::chrono::steady_clock::now();
std::cout << "Limit: " << boundary << " result: " << temp
<< " time (ns): " << (end_time - start_time).count() << '\n';
}
}
int main(){
measure_branch_predictions();
}
| {
"content_hash": "2c68e4cfa2e6a5919b4e84241048a149",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 79,
"avg_line_length": 24.894736842105264,
"alnum_prop": 0.5211416490486258,
"repo_name": "horenmar/cache-effect-benchmarks",
"id": "cde21e163e6caef0fcfb5eb1a07522a568d2c09a",
"size": "1023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "simple_branch_cond.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "31494"
},
{
"name": "Python",
"bytes": "510"
},
{
"name": "Shell",
"bytes": "286"
}
],
"symlink_target": ""
} |
/* Parser needs these defines always, even if USE_RAID is not defined */
#define RAID_TYPE_0 1 /* Striping */
#define RAID_TYPE_x 2 /* Some new modes */
#define RAID_TYPE_y 3
#define RAID_DEFAULT_CHUNKS 4
#define RAID_DEFAULT_CHUNKSIZE 256*1024 /* 256kB */
C_MODE_START
#define my_raid_type(raid_type) raid_type_string[(int)(raid_type)]
extern const char *raid_type_string[];
C_MODE_END
#ifdef DONT_USE_RAID
#undef USE_RAID
#endif
#if defined(USE_RAID)
#include "my_dir.h"
/* Trap all occurences of my_...() in source and use our wrapper around this function */
#ifdef MAP_TO_USE_RAID
#define my_read(A,B,C,D) my_raid_read(A,B,C,D)
#define my_write(A,B,C,D) my_raid_write(A,B,C,D)
#define my_pwrite(A,B,C,D,E) my_raid_pwrite(A,B,C,D,E)
#define my_pread(A,B,C,D,E) my_raid_pread(A,B,C,D,E)
#define my_chsize(A,B,C,D) my_raid_chsize(A,B,C,D)
#define my_close(A,B) my_raid_close(A,B)
#define my_tell(A,B) my_raid_tell(A,B)
#define my_seek(A,B,C,D) my_raid_seek(A,B,C,D)
#define my_lock(A,B,C,D,E) my_raid_lock(A,B,C,D,E)
#define my_fstat(A,B,C) my_raid_fstat(A,B,C)
#endif /* MAP_TO_USE_RAID */
#ifdef __cplusplus
extern "C" {
#endif
void init_raid(void);
void end_raid(void);
bool is_raid(File fd);
File my_raid_create(const char *FileName, int CreateFlags, int access_flags,
uint raid_type, uint raid_chunks, ulong raid_chunksize,
myf MyFlags);
File my_raid_open(const char *FileName, int Flags,
uint raid_type, uint raid_chunks, ulong raid_chunksize,
myf MyFlags);
int my_raid_rename(const char *from, const char *to, uint raid_chunks,
myf MyFlags);
int my_raid_delete(const char *from, uint raid_chunks, myf MyFlags);
int my_raid_redel(const char *old_name, const char *new_name,
uint raid_chunks, myf MyFlags);
my_off_t my_raid_seek(File fd, my_off_t pos, int whence, myf MyFlags);
my_off_t my_raid_tell(File fd, myf MyFlags);
uint my_raid_write(File,const byte *Buffer, uint Count, myf MyFlags);
uint my_raid_read(File Filedes, byte *Buffer, uint Count, myf MyFlags);
uint my_raid_pread(File Filedes, byte *Buffer, uint Count, my_off_t offset,
myf MyFlags);
uint my_raid_pwrite(int Filedes, const byte *Buffer, uint Count,
my_off_t offset, myf MyFlags);
int my_raid_lock(File,int locktype, my_off_t start, my_off_t length,
myf MyFlags);
int my_raid_chsize(File fd, my_off_t newlength, int filler, myf MyFlags);
int my_raid_close(File, myf MyFlags);
int my_raid_fstat(int Filedes, struct stat *buf, myf MyFlags);
#ifdef __cplusplus
}
#ifdef USE_PRAGMA_INTERFACE
#pragma interface /* gcc class implementation */
#endif
class RaidName {
public:
RaidName(const char *FileName);
~RaidName();
bool IsRaid();
int Rename(const char * from, const char * to, myf MyFlags);
private:
uint _raid_type; /* RAID_TYPE_0 or RAID_TYPE_1 or RAID_TYPE_5 */
uint _raid_chunks; /* 1..n */
ulong _raid_chunksize; /* 1..n in bytes */
};
class RaidFd {
public:
RaidFd(uint raid_type, uint raid_chunks , ulong raid_chunksize);
~RaidFd();
File Create(const char *FileName, int CreateFlags, int access_flags,
myf MyFlags);
File Open(const char *FileName, int Flags, myf MyFlags);
my_off_t Seek(my_off_t pos,int whence,myf MyFlags);
my_off_t Tell(myf MyFlags);
int Write(const byte *Buffer, uint Count, myf MyFlags);
int Read(const byte *Buffer, uint Count, myf MyFlags);
int Lock(int locktype, my_off_t start, my_off_t length, myf MyFlags);
int Chsize(File fd, my_off_t newlength, int filler, myf MyFlags);
int Fstat(int fd, MY_STAT *stat_area, myf MyFlags );
int Close(myf MyFlags);
static bool IsRaid(File fd);
static DYNAMIC_ARRAY _raid_map; /* Map of RaidFD* */
private:
uint _raid_type; /* RAID_TYPE_0 or RAID_TYPE_1 or RAID_TYPE_5 */
uint _raid_chunks; /* 1..n */
ulong _raid_chunksize; /* 1..n in bytes */
ulong _total_block; /* We are operating with block no x (can be 0..many). */
uint _this_block; /* can be 0.._raid_chunks */
uint _remaining_bytes; /* Maximum bytes that can be written in this block */
my_off_t _position;
my_off_t _size; /* Cached file size for faster seek(SEEK_END) */
File _fd;
File *_fd_vector; /* Array of File */
off_t *_seek_vector; /* Array of cached seek positions */
inline void Calculate()
{
DBUG_ENTER("RaidFd::_Calculate");
DBUG_PRINT("info",("_position: %lu _raid_chunksize: %lu _size: %lu",
(ulong) _position, _raid_chunksize, (ulong) _size));
_total_block = (ulong) (_position / _raid_chunksize);
_this_block = _total_block % _raid_chunks; /* can be 0.._raid_chunks */
_remaining_bytes = (uint) (_raid_chunksize -
(_position - _total_block * _raid_chunksize));
DBUG_PRINT("info",
("_total_block: %lu this_block: %d _remaining_bytes: %d",
_total_block, _this_block, _remaining_bytes));
DBUG_VOID_RETURN;
}
};
#endif /* __cplusplus */
#endif /* USE_RAID */
| {
"content_hash": "fd619936eb55c8ae265a9450246a547d",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 88,
"avg_line_length": 35.186206896551724,
"alnum_prop": 0.6454331634653078,
"repo_name": "Gamesjiazhi/rwproject",
"id": "9d098305d149ea23ff2100d3258dcd0bf65cc542",
"size": "5796",
"binary": false,
"copies": "109",
"ref": "refs/heads/master",
"path": "ResourceWar/LKEngine/Mysql/include/raid.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9905"
},
{
"name": "C",
"bytes": "4568748"
},
{
"name": "C#",
"bytes": "29913"
},
{
"name": "C++",
"bytes": "20989040"
},
{
"name": "CMake",
"bytes": "214599"
},
{
"name": "GLSL",
"bytes": "52884"
},
{
"name": "Java",
"bytes": "667273"
},
{
"name": "JavaScript",
"bytes": "49070"
},
{
"name": "Lua",
"bytes": "3857489"
},
{
"name": "Makefile",
"bytes": "53185"
},
{
"name": "Objective-C",
"bytes": "2902408"
},
{
"name": "Objective-C++",
"bytes": "509803"
},
{
"name": "PowerShell",
"bytes": "18747"
},
{
"name": "Python",
"bytes": "1153937"
},
{
"name": "Shell",
"bytes": "30186"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-finmap: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / mathcomp-finmap - 1.1.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-finmap
<small>
1.1.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2019-11-30 21:22:11 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2019-11-30 21:22:11 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0 Official release 4.09.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
name: "coq-mathcomp-finmap"
maintainer: "Cyril Cohen <cyril.cohen@inria.fr>"
homepage: "http://www.cyrilcohen.fr"
bug-reports: "Cyril Cohen <cyril.cohen@inria.fr>"
license: "CeCILL-B"
build: [ make "-j" "%{jobs}%" ]
install: [ make "install" ]
depends: [
"ocaml"
"coq-mathcomp-ssreflect" {>= "1.7.0" & < "1.8~"}
]
tags: [
"keyword:finmap"
"keyword:finset"
"keyword:multiset"
"keyword:order"
"logpath:mathcomp.finmap"
]
authors: [ "Cyril Cohen <cyril.cohen@inria.fr>" ]
synopsis: "Finite sets, finite maps, finitely supported functions, orders"
description: """
This library is an extension of mathematical component in order to
support finite sets and finite maps on choicetypes (rather that finite
types). This includes support for functions with finite support and
multisets. The library also contains a generic order and set libary,
which will be used to subsume notations for finite sets, eventually."""
url {
src: "https://github.com/math-comp/finmap/archive/1.1.0.tar.gz"
checksum: "md5=f8bca7e64d16fdc61bf6b09af5e0b99b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-finmap.1.1.0 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-mathcomp-finmap -> coq-mathcomp-ssreflect < 1.8~ -> coq < 8.10~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-finmap.1.1.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "e974d46c89baa91b66b138ce5b7a061c",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 157,
"avg_line_length": 41.325581395348834,
"alnum_prop": 0.5507878446820484,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "dbdb43bd51b513c5ec1abd51e9a0c6af42a7c2b1",
"size": "7110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.0-2.0.5/extra-dev/dev/mathcomp-finmap/1.1.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package sun.jvmstat.monitor.remote;
import sun.jvmstat.monitor.*;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.io.IOException;
/**
* Remote Interface for discovering and attaching to remote
* monitorable Java Virtual Machines.
*
* @author Brian Doherty
* @since 1.5
*/
public interface RemoteHost extends Remote {
/**
* Remote method to attach to a remote HotSpot Java Virtual Machine
* identified by <code>vmid</code>.
*
* @param vmid The identifier for the target virtual machine.
* @return RemoteVm - A remote object for accessing the remote Java
* Virtual Machine.
*
* @throws MonitorException Thrown when any other error is encountered
* while communicating with the target virtual
* machine.
* @throws RemoteException
*
*/
RemoteVm attachVm(int vmid, String mode) throws RemoteException,
MonitorException;
/**
* Remote method to detach from a remote HotSpot Java Virtual Machine
* identified by <code>vmid</code>.
*
* @param rvm The remote object for the target Java Virtual
* Machine.
*
* @throws MonitorException Thrown when any other error is encountered
* while communicating with the target virtual
* machine.
* @throws RemoteException
*/
void detachVm(RemoteVm rvm) throws RemoteException, MonitorException;
/**
* Get a list of Local Virtual Machine Identifiers for the active
* Java Virtual Machine the remote system. A Local Virtual Machine
* Identifier is also known as an <em>lvmid</em>.
*
* @return int[] - A array of <em>lvmid</em>s.
* @throws MonitorException Thrown when any other error is encountered
* while communicating with the target virtual
* machine.
* @throws RemoteException
*/
int[] activeVms() throws RemoteException, MonitorException;
}
| {
"content_hash": "7877ccfd2683fd6f46f911e30ede47ff",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 75,
"avg_line_length": 34.403225806451616,
"alnum_prop": 0.612751992498828,
"repo_name": "rokn/Count_Words_2015",
"id": "45d087e203f979a9b5d0b98b825ff296b087e0b8",
"size": "3339",
"binary": false,
"copies": "87",
"ref": "refs/heads/master",
"path": "testing/openjdk2/jdk/src/share/classes/sun/jvmstat/monitor/remote/RemoteHost.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.apimanagement.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The TenantAccessListSecretsHeaders model. */
@Fluent
public final class TenantAccessListSecretsHeaders {
/*
* The Etag property.
*/
@JsonProperty(value = "Etag")
private String etag;
/**
* Get the etag property: The Etag property.
*
* @return the etag value.
*/
public String etag() {
return this.etag;
}
/**
* Set the etag property: The Etag property.
*
* @param etag the etag value to set.
* @return the TenantAccessListSecretsHeaders object itself.
*/
public TenantAccessListSecretsHeaders withEtag(String etag) {
this.etag = etag;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| {
"content_hash": "5a7c65234e89175ec7860ef29abdf53d",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 76,
"avg_line_length": 25,
"alnum_prop": 0.6573913043478261,
"repo_name": "Azure/azure-sdk-for-java",
"id": "bcdcee1e0f9fd3b4dba3f49f72da88a6b1945ad1",
"size": "1150",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/apimanagement/azure-resourcemanager-apimanagement/src/main/java/com/azure/resourcemanager/apimanagement/models/TenantAccessListSecretsHeaders.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
@implementation PCSAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
MyController *controller = [[MyController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
self.window.rootViewController = nav;
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {
"content_hash": "525e4c33cc2abc5b3af297fb204674b9",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 280,
"avg_line_length": 50.34090909090909,
"alnum_prop": 0.7869074492099323,
"repo_name": "pchensoftware/PCSTableViewPeekaboo",
"id": "368f233f13c3591052763e83a2a506f5b6056234",
"size": "2420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PCSTableViewPeekabooExample/PCSTableViewPeekabooExample/PCSAppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "16745"
}
],
"symlink_target": ""
} |
import sys
import unittest
import libsbml
class TestModel_newSetters(unittest.TestCase):
global M
M = None
def setUp(self):
self.M = libsbml.Model(2,4)
if (self.M == None):
pass
pass
def tearDown(self):
_dummyList = [ self.M ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartment1(self):
m = libsbml.Model(2,2)
c = libsbml.Compartment(2,2)
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
c.setId( "c")
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumCompartments() == 1 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartment2(self):
m = libsbml.Model(2,2)
c = libsbml.Compartment(2,1)
c.setId( "c")
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumCompartments() == 0 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartment3(self):
m = libsbml.Model(2,2)
c = libsbml.Compartment(1,2)
c.setId( "c")
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumCompartments() == 0 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartment4(self):
m = libsbml.Model(2,2)
c = None
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumCompartments() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartment5(self):
m = libsbml.Model(2,2)
c = libsbml.Compartment(2,2)
c.setId( "c")
c1 = libsbml.Compartment(2,2)
c1.setId( "c")
i = m.addCompartment(c)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumCompartments() == 1 )
i = m.addCompartment(c1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumCompartments() == 1 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ c1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartmentType1(self):
m = libsbml.Model(2,2)
ct = libsbml.CompartmentType(2,2)
i = m.addCompartmentType(ct)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
ct.setId( "ct")
i = m.addCompartmentType(ct)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumCompartmentTypes() == 1 )
_dummyList = [ ct ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartmentType2(self):
m = libsbml.Model(2,2)
ct = libsbml.CompartmentType(2,3)
ct.setId( "ct")
i = m.addCompartmentType(ct)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumCompartmentTypes() == 0 )
_dummyList = [ ct ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartmentType3(self):
m = libsbml.Model(2,2)
ct = None
i = m.addCompartmentType(ct)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumCompartmentTypes() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addCompartmentType4(self):
m = libsbml.Model(2,2)
ct = libsbml.CompartmentType(2,2)
ct.setId( "ct")
ct1 = libsbml.CompartmentType(2,2)
ct1.setId( "ct")
i = m.addCompartmentType(ct)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumCompartmentTypes() == 1 )
i = m.addCompartmentType(ct1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumCompartmentTypes() == 1 )
_dummyList = [ ct ]; _dummyList[:] = []; del _dummyList
_dummyList = [ ct1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addConstraint1(self):
m = libsbml.Model(2,2)
c = libsbml.Constraint(2,2)
i = m.addConstraint(c)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
c.setMath(libsbml.parseFormula("a+b"))
i = m.addConstraint(c)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumConstraints() == 1 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addConstraint2(self):
m = libsbml.Model(2,2)
c = libsbml.Constraint(2,3)
c.setMath(libsbml.parseFormula("a+b"))
i = m.addConstraint(c)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumConstraints() == 0 )
_dummyList = [ c ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addConstraint3(self):
m = libsbml.Model(2,2)
c = None
i = m.addConstraint(c)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumConstraints() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addEvent1(self):
m = libsbml.Model(2,2)
e = libsbml.Event(2,2)
t = libsbml.Trigger(2,2)
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
t.setMath(libsbml.parseFormula("true"))
e.setTrigger(t)
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
e.createEventAssignment()
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumEvents() == 1 )
_dummyList = [ e ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addEvent2(self):
m = libsbml.Model(2,2)
e = libsbml.Event(2,1)
t = libsbml.Trigger(2,1)
t.setMath(libsbml.parseFormula("true"))
e.setTrigger(t)
e.createEventAssignment()
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumEvents() == 0 )
_dummyList = [ e ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addEvent3(self):
m = libsbml.Model(2,2)
e = None
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumEvents() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addEvent4(self):
m = libsbml.Model(2,2)
e = libsbml.Event(2,2)
t = libsbml.Trigger(2,2)
t.setMath(libsbml.parseFormula("true"))
e.setId( "e")
e.setTrigger(t)
e.createEventAssignment()
e1 = libsbml.Event(2,2)
e1.setId( "e")
e1.setTrigger(t)
e1.createEventAssignment()
i = m.addEvent(e)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumEvents() == 1 )
i = m.addEvent(e1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumEvents() == 1 )
_dummyList = [ e ]; _dummyList[:] = []; del _dummyList
_dummyList = [ e1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addFunctionDefinition1(self):
m = libsbml.Model(2,2)
fd = libsbml.FunctionDefinition(2,2)
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
fd.setId( "fd")
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
fd.setMath(libsbml.parseFormula("fd"))
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumFunctionDefinitions() == 1 )
_dummyList = [ fd ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addFunctionDefinition2(self):
m = libsbml.Model(2,2)
fd = libsbml.FunctionDefinition(2,1)
fd.setId( "fd")
fd.setMath(libsbml.parseFormula("fd"))
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumFunctionDefinitions() == 0 )
_dummyList = [ fd ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addFunctionDefinition3(self):
m = libsbml.Model(2,2)
fd = None
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumFunctionDefinitions() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addFunctionDefinition4(self):
m = libsbml.Model(2,2)
fd = libsbml.FunctionDefinition(2,2)
fd.setId( "fd")
fd.setMath(libsbml.parseFormula("fd"))
fd1 = libsbml.FunctionDefinition(2,2)
fd1.setId( "fd")
fd1.setMath(libsbml.parseFormula("fd"))
i = m.addFunctionDefinition(fd)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumFunctionDefinitions() == 1 )
i = m.addFunctionDefinition(fd1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumFunctionDefinitions() == 1 )
_dummyList = [ fd ]; _dummyList[:] = []; del _dummyList
_dummyList = [ fd1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addInitialAssignment1(self):
m = libsbml.Model(2,2)
ia = libsbml.InitialAssignment(2,2)
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
ia.setSymbol( "i")
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
ia.setMath(libsbml.parseFormula("gg"))
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumInitialAssignments() == 1 )
_dummyList = [ ia ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addInitialAssignment2(self):
m = libsbml.Model(2,2)
ia = libsbml.InitialAssignment(2,3)
ia.setSymbol( "i")
ia.setMath(libsbml.parseFormula("gg"))
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumInitialAssignments() == 0 )
_dummyList = [ ia ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addInitialAssignment3(self):
m = libsbml.Model(2,2)
ia = None
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumInitialAssignments() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addInitialAssignment4(self):
m = libsbml.Model(2,2)
ia = libsbml.InitialAssignment(2,2)
ia.setSymbol( "ia")
ia.setMath(libsbml.parseFormula("a+b"))
ia1 = libsbml.InitialAssignment(2,2)
ia1.setSymbol( "ia")
ia1.setMath(libsbml.parseFormula("a+b"))
i = m.addInitialAssignment(ia)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumInitialAssignments() == 1 )
i = m.addInitialAssignment(ia1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumInitialAssignments() == 1 )
_dummyList = [ ia ]; _dummyList[:] = []; del _dummyList
_dummyList = [ ia1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addParameter1(self):
m = libsbml.Model(2,2)
p = libsbml.Parameter(2,2)
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
p.setId( "p")
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumParameters() == 1 )
_dummyList = [ p ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addParameter2(self):
m = libsbml.Model(2,2)
p = libsbml.Parameter(2,1)
p.setId( "p")
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumParameters() == 0 )
_dummyList = [ p ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addParameter3(self):
m = libsbml.Model(2,2)
p = libsbml.Parameter(1,2)
p.setId( "p")
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumParameters() == 0 )
_dummyList = [ p ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addParameter4(self):
m = libsbml.Model(2,2)
p = None
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumParameters() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addParameter5(self):
m = libsbml.Model(2,2)
p = libsbml.Parameter(2,2)
p.setId( "p")
p1 = libsbml.Parameter(2,2)
p1.setId( "p")
i = m.addParameter(p)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumParameters() == 1 )
i = m.addParameter(p1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumParameters() == 1 )
_dummyList = [ p ]; _dummyList[:] = []; del _dummyList
_dummyList = [ p1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addReaction1(self):
m = libsbml.Model(2,2)
r = libsbml.Reaction(2,2)
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
r.setId( "r")
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumReactions() == 1 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addReaction2(self):
m = libsbml.Model(2,2)
r = libsbml.Reaction(2,1)
r.setId( "r")
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumReactions() == 0 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addReaction3(self):
m = libsbml.Model(2,2)
r = libsbml.Reaction(1,2)
r.setId( "r")
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumReactions() == 0 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addReaction4(self):
m = libsbml.Model(2,2)
r = None
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumReactions() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addReaction5(self):
m = libsbml.Model(2,2)
r = libsbml.Reaction(2,2)
r.setId( "r")
r1 = libsbml.Reaction(2,2)
r1.setId( "r")
i = m.addReaction(r)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumReactions() == 1 )
i = m.addReaction(r1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumReactions() == 1 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ r1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addRule1(self):
m = libsbml.Model(2,2)
r = libsbml.AssignmentRule(2,2)
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
r.setVariable( "f")
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
r.setMath(libsbml.parseFormula("a-n"))
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumRules() == 1 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addRule2(self):
m = libsbml.Model(2,2)
r = libsbml.AssignmentRule(2,1)
r.setVariable( "f")
r.setMath(libsbml.parseFormula("a-n"))
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumRules() == 0 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addRule3(self):
m = libsbml.Model(2,2)
r = libsbml.AssignmentRule(1,2)
r.setVariable( "f")
r.setMath(libsbml.parseFormula("a-n"))
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumRules() == 0 )
_dummyList = [ r ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addRule4(self):
m = libsbml.Model(2,2)
r = None
i = m.addRule(r)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumRules() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addRule5(self):
m = libsbml.Model(2,2)
ar = libsbml.AssignmentRule(2,2)
ar.setVariable( "ar")
ar.setMath(libsbml.parseFormula("a-j"))
ar1 = libsbml.AssignmentRule(2,2)
ar1.setVariable( "ar")
ar1.setMath(libsbml.parseFormula("a-j"))
i = m.addRule(ar)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumRules() == 1 )
i = m.addRule(ar1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumRules() == 1 )
_dummyList = [ ar ]; _dummyList[:] = []; del _dummyList
_dummyList = [ ar1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpecies1(self):
m = libsbml.Model(2,2)
s = libsbml.Species(2,2)
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
s.setId( "s")
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
s.setCompartment( "c")
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumSpecies() == 1 )
_dummyList = [ s ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpecies2(self):
m = libsbml.Model(2,2)
s = libsbml.Species(2,1)
s.setId( "s")
s.setCompartment( "c")
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumSpecies() == 0 )
_dummyList = [ s ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpecies3(self):
m = libsbml.Model(2,2)
s = libsbml.Species(1,2)
s.setId( "s")
s.setCompartment( "c")
s.setInitialAmount(2)
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumSpecies() == 0 )
_dummyList = [ s ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpecies4(self):
m = libsbml.Model(2,2)
s = None
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumSpecies() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpecies5(self):
m = libsbml.Model(2,2)
s = libsbml.Species(2,2)
s.setId( "s")
s.setCompartment( "c")
s1 = libsbml.Species(2,2)
s1.setId( "s")
s1.setCompartment( "c")
i = m.addSpecies(s)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumSpecies() == 1 )
i = m.addSpecies(s1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumSpecies() == 1 )
_dummyList = [ s ]; _dummyList[:] = []; del _dummyList
_dummyList = [ s1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpeciesType1(self):
m = libsbml.Model(2,2)
st = libsbml.SpeciesType(2,2)
i = m.addSpeciesType(st)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
st.setId( "st")
i = m.addSpeciesType(st)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumSpeciesTypes() == 1 )
_dummyList = [ st ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpeciesType2(self):
m = libsbml.Model(2,2)
st = libsbml.SpeciesType(2,3)
st.setId( "st")
i = m.addSpeciesType(st)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumSpeciesTypes() == 0 )
_dummyList = [ st ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpeciesType3(self):
m = libsbml.Model(2,2)
st = None
i = m.addSpeciesType(st)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumSpeciesTypes() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addSpeciesType4(self):
m = libsbml.Model(2,2)
st = libsbml.SpeciesType(2,2)
st.setId( "st")
st1 = libsbml.SpeciesType(2,2)
st1.setId( "st")
i = m.addSpeciesType(st)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumSpeciesTypes() == 1 )
i = m.addSpeciesType(st1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumSpeciesTypes() == 1 )
_dummyList = [ st ]; _dummyList[:] = []; del _dummyList
_dummyList = [ st1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addUnitDefinition1(self):
m = libsbml.Model(2,2)
ud = libsbml.UnitDefinition(2,2)
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
ud.createUnit()
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
ud.setId( "ud")
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumUnitDefinitions() == 1 )
_dummyList = [ ud ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addUnitDefinition2(self):
m = libsbml.Model(2,2)
ud = libsbml.UnitDefinition(2,1)
ud.createUnit()
ud.setId( "ud")
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_VERSION_MISMATCH )
self.assert_( m.getNumUnitDefinitions() == 0 )
_dummyList = [ ud ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addUnitDefinition3(self):
m = libsbml.Model(2,2)
ud = libsbml.UnitDefinition(1,2)
ud.createUnit()
ud.setId( "ud")
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
self.assert_( m.getNumUnitDefinitions() == 0 )
_dummyList = [ ud ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addUnitDefinition4(self):
m = libsbml.Model(2,2)
ud = None
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
self.assert_( m.getNumUnitDefinitions() == 0 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_addUnitDefinition5(self):
m = libsbml.Model(2,2)
ud = libsbml.UnitDefinition(2,2)
ud.setId( "ud")
ud.createUnit()
ud1 = libsbml.UnitDefinition(2,2)
ud1.setId( "ud")
ud1.createUnit()
i = m.addUnitDefinition(ud)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_( m.getNumUnitDefinitions() == 1 )
i = m.addUnitDefinition(ud1)
self.assert_( i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID )
self.assert_( m.getNumUnitDefinitions() == 1 )
_dummyList = [ ud ]; _dummyList[:] = []; del _dummyList
_dummyList = [ ud1 ]; _dummyList[:] = []; del _dummyList
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createCompartment(self):
m = libsbml.Model(2,2)
p = m.createCompartment()
self.assert_( m.getNumCompartments() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createCompartmentType(self):
m = libsbml.Model(2,2)
p = m.createCompartmentType()
self.assert_( m.getNumCompartmentTypes() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createConstraint(self):
m = libsbml.Model(2,2)
p = m.createConstraint()
self.assert_( m.getNumConstraints() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createEvent(self):
m = libsbml.Model(2,2)
p = m.createEvent()
self.assert_( m.getNumEvents() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createEventAssignment(self):
m = libsbml.Model(2,2)
p = m.createEvent()
ea = m.createEventAssignment()
self.assert_( p.getNumEventAssignments() == 1 )
self.assert_( (ea).getLevel() == 2 )
self.assert_( (ea).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createFunctionDefinition(self):
m = libsbml.Model(2,2)
p = m.createFunctionDefinition()
self.assert_( m.getNumFunctionDefinitions() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createInitialAssignment(self):
m = libsbml.Model(2,2)
p = m.createInitialAssignment()
self.assert_( m.getNumInitialAssignments() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createKineticLaw(self):
m = libsbml.Model(2,2)
p = m.createReaction()
kl = m.createKineticLaw()
self.assert_( p.isSetKineticLaw() == True )
self.assert_( (kl).getLevel() == 2 )
self.assert_( (kl).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createKineticLawParameters(self):
m = libsbml.Model(2,2)
r = m.createReaction()
kl = m.createKineticLaw()
p = m.createKineticLawParameter()
self.assert_( r.isSetKineticLaw() == True )
self.assert_( kl.getNumParameters() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createModifier(self):
m = libsbml.Model(2,2)
p = m.createReaction()
sr = m.createModifier()
self.assert_( p.getNumModifiers() == 1 )
self.assert_( (sr).getLevel() == 2 )
self.assert_( (sr).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createParameter(self):
m = libsbml.Model(2,2)
p = m.createParameter()
self.assert_( m.getNumParameters() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createProduct(self):
m = libsbml.Model(2,2)
p = m.createReaction()
sr = m.createProduct()
self.assert_( p.getNumProducts() == 1 )
self.assert_( (sr).getLevel() == 2 )
self.assert_( (sr).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createReactant(self):
m = libsbml.Model(2,2)
p = m.createReaction()
sr = m.createReactant()
self.assert_( p.getNumReactants() == 1 )
self.assert_( (sr).getLevel() == 2 )
self.assert_( (sr).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createReaction(self):
m = libsbml.Model(2,2)
p = m.createReaction()
self.assert_( m.getNumReactions() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createRule(self):
m = libsbml.Model(2,2)
p = m.createAssignmentRule()
self.assert_( m.getNumRules() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createSpecies(self):
m = libsbml.Model(2,2)
p = m.createSpecies()
self.assert_( m.getNumSpecies() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createSpeciesType(self):
m = libsbml.Model(2,2)
p = m.createSpeciesType()
self.assert_( m.getNumSpeciesTypes() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createUnit(self):
m = libsbml.Model(2,2)
p = m.createUnitDefinition()
u = m.createUnit()
self.assert_( p.getNumUnits() == 1 )
self.assert_( (u).getLevel() == 2 )
self.assert_( (u).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_createUnitDefinition(self):
m = libsbml.Model(2,2)
p = m.createUnitDefinition()
self.assert_( m.getNumUnitDefinitions() == 1 )
self.assert_( (p).getLevel() == 2 )
self.assert_( (p).getVersion() == 2 )
_dummyList = [ m ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_setId1(self):
id = "1e1";
i = self.M.setId(id)
self.assert_( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE )
self.assertEqual( False, self.M.isSetId() )
pass
def test_Model_setId2(self):
id = "e1";
i = self.M.setId(id)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_(( id == self.M.getId() ))
self.assertEqual( True, self.M.isSetId() )
i = self.M.setId("")
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetId() )
pass
def test_Model_setId3(self):
id = "e1";
i = self.M.setId(id)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_(( id == self.M.getId() ))
self.assertEqual( True, self.M.isSetId() )
i = self.M.unsetId()
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetId() )
pass
def test_Model_setModelHistory1(self):
self.M.setMetaId("_001")
mh = libsbml.ModelHistory()
i = self.M.setModelHistory(mh)
self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
self.assertEqual( False, self.M.isSetModelHistory() )
i = self.M.unsetModelHistory()
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetModelHistory() )
_dummyList = [ mh ]; _dummyList[:] = []; del _dummyList
pass
def test_Model_setModelHistory2(self):
self.M.setMetaId("_001")
i = self.M.setModelHistory(None)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetModelHistory() )
i = self.M.unsetModelHistory()
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetModelHistory() )
pass
def test_Model_setName1(self):
name = "3Set_k2";
i = self.M.setName(name)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( True, self.M.isSetName() )
pass
def test_Model_setName2(self):
name = "Set k2";
i = self.M.setName(name)
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assert_(( name == self.M.getName() ))
self.assertEqual( True, self.M.isSetName() )
i = self.M.unsetName()
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetName() )
pass
def test_Model_setName3(self):
i = self.M.setName("")
self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
self.assertEqual( False, self.M.isSetName() )
pass
def test_Model_setName4(self):
m = libsbml.Model(1,2)
i = m.setName( "11dd")
self.assert_( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE )
self.assertEqual( False, m.isSetName() )
pass
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestModel_newSetters))
return suite
if __name__ == "__main__":
if unittest.TextTestRunner(verbosity=1).run(suite()).wasSuccessful() :
sys.exit(0)
else:
sys.exit(1)
| {
"content_hash": "09d8a164ba13c6091411c7ab6e08fe1b",
"timestamp": "",
"source": "github",
"line_count": 991,
"max_line_length": 72,
"avg_line_length": 34.36629667003027,
"alnum_prop": 0.6057785477288076,
"repo_name": "TheCoSMoCompany/biopredyn",
"id": "52bfb95b8653fb8680e5455898da00c99e95fdd0",
"size": "35461",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Prototype/src/libsbml-5.10.0/src/bindings/python/test/sbml/TestModel_newSetters.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3535918"
},
{
"name": "C++",
"bytes": "26120778"
},
{
"name": "CMake",
"bytes": "455400"
},
{
"name": "CSS",
"bytes": "49020"
},
{
"name": "Gnuplot",
"bytes": "206"
},
{
"name": "HTML",
"bytes": "193068"
},
{
"name": "Java",
"bytes": "66517"
},
{
"name": "JavaScript",
"bytes": "3847"
},
{
"name": "Makefile",
"bytes": "30905"
},
{
"name": "Perl",
"bytes": "3018"
},
{
"name": "Python",
"bytes": "7891301"
},
{
"name": "Shell",
"bytes": "247654"
},
{
"name": "TeX",
"bytes": "22566"
},
{
"name": "XSLT",
"bytes": "55564"
}
],
"symlink_target": ""
} |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="cn.edu.njupt.tanksms.ui.MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/primary_color_green_light">
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/background_color_white"
android:layout_below="@+id/toolbar"
android:padding="12dp">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/MainlistView"
android:dividerHeight="12dp"
android:layoutAnimation="@anim/listview_item_in"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
| {
"content_hash": "de73c4d91419e4ce51d08e9776e66961",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 74,
"avg_line_length": 39.07692307692308,
"alnum_prop": 0.6633858267716536,
"repo_name": "HsingPeng/FireTanksMonitoringSystem",
"id": "0b1b39cb7f4d01f1930904dc00d75a45f0cf3cc7",
"size": "1524",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android_client/app/src/main/res/layout/activity_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "452718"
},
{
"name": "HTML",
"bytes": "1977"
},
{
"name": "Java",
"bytes": "112395"
},
{
"name": "JavaScript",
"bytes": "1570115"
},
{
"name": "PHP",
"bytes": "42083"
}
],
"symlink_target": ""
} |
layout: default
title: Search | Suriyaa Kudo
permalink: /search/
lang: en_US
---
<script>
(function() {
var cx = '018379229459056173049:ybssuaca-l8';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
| {
"content_hash": "b986c634b233bca2b99ee0cacfe8a5b3",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 78,
"avg_line_length": 27.842105263157894,
"alnum_prop": 0.6351606805293005,
"repo_name": "iSC-Host/suriyaa.me",
"id": "7601c1ea830a2723572c8f00267af33b0f42744b",
"size": "533",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "search.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "8940"
},
{
"name": "CSS",
"bytes": "458504"
},
{
"name": "HTML",
"bytes": "164881"
},
{
"name": "JavaScript",
"bytes": "188374"
},
{
"name": "PHP",
"bytes": "12919"
},
{
"name": "Shell",
"bytes": "392"
}
],
"symlink_target": ""
} |
/* icons */
[class^="cus-"],
[class*=" cus-"] {
display: inline-block;
width: 17px;
height: 16px;
*margin-right: .3em;
line-height: 14px;
vertical-align: text-top;
background-image: url("../img/fan-icons.png");
background-position: 14px 14px;
background-repeat: no-repeat;
}
[class^="cus-"]:last-child,
[class*=" cus-"]:last-child {
*margin-left: 0;
}
/* icons code below */
.cus-accept{ background-position: 0 0; }
.cus-add{ background-position: -21px 0; }
.cus-anchor{ background-position: -42px 0; }
.cus-application{ background-position: -63px 0; }
.cus-application_add{ background-position: -84px 0; }
.cus-application_cascade{ background-position: -105px 0; }
.cus-application_delete{ background-position: -126px 0; }
.cus-application_double{ background-position: -147px 0; }
.cus-application_edit{ background-position: -168px 0; }
.cus-application_error{ background-position: -189px 0; }
.cus-application_form{ background-position: -210px 0; }
.cus-application_form_add{ background-position: -231px 0; }
.cus-application_form_delete{ background-position: -252px 0; }
.cus-application_form_edit{ background-position: -273px 0; }
.cus-application_form_magnify{ background-position: -294px 0; }
.cus-application_get{ background-position: -315px 0; }
.cus-application_go{ background-position: -336px 0; }
.cus-application_home{ background-position: -357px 0; }
.cus-application_key{ background-position: -378px 0; }
.cus-application_lightning{ background-position: -399px 0; }
.cus-application_link{ background-position: -420px 0; }
.cus-application_osx{ background-position: -441px 0; }
.cus-application_osx_terminal{ background-position: -462px 0; }
.cus-application_put{ background-position: -483px 0; }
.cus-application_side_boxes{ background-position: -504px 0; }
.cus-application_side_contract{ background-position: -525px 0; }
.cus-application_side_expand{ background-position: -546px 0; }
.cus-application_side_list{ background-position: -567px 0; }
.cus-application_side_tree{ background-position: -588px 0; }
.cus-application_split{ background-position: -609px 0; }
.cus-application_tile_horizontal{ background-position: -630px 0; }
.cus-application_tile_vertical{ background-position: -651px 0; }
.cus-application_view_columns{ background-position: -672px 0; }
.cus-application_view_detail{ background-position: -693px 0; }
.cus-application_view_gallery{ background-position: -714px 0; }
.cus-application_view_icons{ background-position: -735px 0; }
.cus-application_view_list{ background-position: -756px 0; }
.cus-application_view_tile{ background-position: -777px 0; }
.cus-application_xp{ background-position: -798px 0; }
.cus-application_xp_terminal{ background-position: -819px 0; }
.cus-arrow_branch{ background-position: -840px 0; }
.cus-arrow_divide{ background-position: -861px 0; }
.cus-arrow_down{ background-position: -882px 0; }
.cus-arrow_in{ background-position: -903px 0; }
.cus-arrow_inout{ background-position: -924px 0; }
.cus-arrow_join{ background-position: -945px 0; }
.cus-arrow_left{ background-position: -966px 0; }
.cus-arrow_merge{ background-position: -987px 0; }
.cus-arrow_out{ background-position: -1008px 0; }
.cus-arrow_redo{ background-position: -1029px 0; }
.cus-arrow_refresh{ background-position: -1050px 0; }
.cus-arrow_refresh_small{ background-position: -1071px 0; }
.cus-arrow_right{ background-position: -1092px 0; }
.cus-arrow_rotate_anticlockwise{ background-position: -1113px 0; }
.cus-arrow_rotate_clockwise{ background-position: -1134px 0; }
.cus-arrow_switch{ background-position: -1155px 0; }
.cus-arrow_turn_left{ background-position: -1176px 0; }
.cus-arrow_turn_right{ background-position: -1197px 0; }
.cus-arrow_undo{ background-position: -1218px 0; }
.cus-arrow_up{ background-position: -1239px 0; }
.cus-asterisk_orange{ background-position: -1260px 0; }
.cus-asterisk_yellow{ background-position: -1281px 0; }
.cus-attach{ background-position: -1302px 0; }
.cus-award_star_add{ background-position: -1323px 0; }
.cus-award_star_bronze_1{ background-position: -1344px 0; }
.cus-award_star_bronze_2{ background-position: -1365px 0; }
.cus-award_star_bronze_3{ background-position: -1386px 0; }
.cus-award_star_delete{ background-position: -1407px 0; }
.cus-award_star_gold_1{ background-position: -1428px 0; }
.cus-award_star_gold_2{ background-position: -1449px 0; }
.cus-award_star_gold_3{ background-position: -1470px 0; }
.cus-award_star_silver_1{ background-position: -1491px 0; }
.cus-award_star_silver_2{ background-position: -1512px 0; }
.cus-award_star_silver_3{ background-position: -1533px 0; }
.cus-basket{ background-position: -1554px 0; }
.cus-basket_add{ background-position: -1575px 0; }
.cus-basket_delete{ background-position: -1596px 0; }
.cus-basket_edit{ background-position: -1617px 0; }
.cus-basket_error{ background-position: -1638px 0; }
.cus-basket_go{ background-position: -1659px 0; }
.cus-basket_put{ background-position: -1680px 0; }
.cus-basket_remove{ background-position: -1701px 0; }
.cus-bell{ background-position: -1722px 0; }
.cus-bell_add{ background-position: -1743px 0; }
.cus-bell_delete{ background-position: -1764px 0; }
.cus-bell_error{ background-position: -1785px 0; }
.cus-bell_go{ background-position: -1806px 0; }
.cus-bell_link{ background-position: -1827px 0; }
.cus-bin{ background-position: -1848px 0; }
.cus-bin_closed{ background-position: -1869px 0; }
.cus-bin_empty{ background-position: -1890px 0; }
.cus-bomb{ background-position: -1911px 0; }
.cus-book{ background-position: -1932px 0; }
.cus-book_add{ background-position: -1953px 0; }
.cus-book_addresses{ background-position: -1974px 0; }
.cus-book_delete{ background-position: 0 -21px; }
.cus-book_edit{ background-position: -21px -21px; }
.cus-book_error{ background-position: -42px -21px; }
.cus-book_go{ background-position: -63px -21px; }
.cus-book_key{ background-position: -84px -21px; }
.cus-book_link{ background-position: -105px -21px; }
.cus-book_next{ background-position: -126px -21px; }
.cus-book_open{ background-position: -147px -21px; }
.cus-book_previous{ background-position: -168px -21px; }
.cus-box{ background-position: -189px -21px; }
.cus-brick{ background-position: -210px -21px; }
.cus-brick_add{ background-position: -231px -21px; }
.cus-brick_delete{ background-position: -252px -21px; }
.cus-brick_edit{ background-position: -273px -21px; }
.cus-brick_error{ background-position: -294px -21px; }
.cus-brick_go{ background-position: -315px -21px; }
.cus-brick_link{ background-position: -336px -21px; }
.cus-bricks{ background-position: -357px -21px; }
.cus-briefcase{ background-position: -378px -21px; }
.cus-bug{ background-position: -399px -21px; }
.cus-bug_add{ background-position: -420px -21px; }
.cus-bug_delete{ background-position: -441px -21px; }
.cus-bug_edit{ background-position: -462px -21px; }
.cus-bug_error{ background-position: -483px -21px; }
.cus-bug_go{ background-position: -504px -21px; }
.cus-bug_link{ background-position: -525px -21px; }
.cus-building{ background-position: -546px -21px; }
.cus-building_add{ background-position: -567px -21px; }
.cus-building_delete{ background-position: -588px -21px; }
.cus-building_edit{ background-position: -609px -21px; }
.cus-building_error{ background-position: -630px -21px; }
.cus-building_go{ background-position: -651px -21px; }
.cus-building_key{ background-position: -672px -21px; }
.cus-building_link{ background-position: -693px -21px; }
.cus-bullet_add{ background-position: -714px -21px; }
.cus-bullet_arrow_bottom{ background-position: -735px -21px; }
.cus-bullet_arrow_down{ background-position: -756px -21px; }
.cus-bullet_arrow_top{ background-position: -777px -21px; }
.cus-bullet_arrow_up{ background-position: -798px -21px; }
.cus-bullet_black{ background-position: -819px -21px; }
.cus-bullet_blue{ background-position: -840px -21px; }
.cus-bullet_delete{ background-position: -861px -21px; }
.cus-bullet_disk{ background-position: -882px -21px; }
.cus-bullet_error{ background-position: -903px -21px; }
.cus-bullet_feed{ background-position: -924px -21px; }
.cus-bullet_go{ background-position: -945px -21px; }
.cus-bullet_green{ background-position: -966px -21px; }
.cus-bullet_key{ background-position: -987px -21px; }
.cus-bullet_orange{ background-position: -1008px -21px; }
.cus-bullet_picture{ background-position: -1029px -21px; }
.cus-bullet_pink{ background-position: -1050px -21px; }
.cus-bullet_purple{ background-position: -1071px -21px; }
.cus-bullet_red{ background-position: -1092px -21px; }
.cus-bullet_star{ background-position: -1113px -21px; }
.cus-bullet_toggle_minus{ background-position: -1134px -21px; }
.cus-bullet_toggle_plus{ background-position: -1155px -21px; }
.cus-bullet_white{ background-position: -1176px -21px; }
.cus-bullet_wrench{ background-position: -1197px -21px; }
.cus-bullet_yellow{ background-position: -1218px -21px; }
.cus-cake{ background-position: -1239px -21px; }
.cus-calculator{ background-position: -1260px -21px; }
.cus-calculator_add{ background-position: -1281px -21px; }
.cus-calculator_delete{ background-position: -1302px -21px; }
.cus-calculator_edit{ background-position: -1323px -21px; }
.cus-calculator_error{ background-position: -1344px -21px; }
.cus-calculator_link{ background-position: -1365px -21px; }
.cus-calendar{ background-position: -1386px -21px; }
.cus-calendar_add{ background-position: -1407px -21px; }
.cus-calendar_delete{ background-position: -1428px -21px; }
.cus-calendar_edit{ background-position: -1449px -21px; }
.cus-calendar_link{ background-position: -1470px -21px; }
.cus-calendar_view_day{ background-position: -1491px -21px; }
.cus-calendar_view_month{ background-position: -1512px -21px; }
.cus-calendar_view_week{ background-position: -1533px -21px; }
.cus-camera{ background-position: -1554px -21px; }
.cus-camera_add{ background-position: -1575px -21px; }
.cus-camera_delete{ background-position: -1596px -21px; }
.cus-camera_edit{ background-position: -1617px -21px; }
.cus-camera_error{ background-position: -1638px -21px; }
.cus-camera_go{ background-position: -1659px -21px; }
.cus-camera_link{ background-position: -1680px -21px; }
.cus-camera_small{ background-position: -1701px -21px; }
.cus-cancel{ background-position: -1722px -21px; }
.cus-car{ background-position: -1743px -21px; }
.cus-car_add{ background-position: -1764px -21px; }
.cus-car_delete{ background-position: -1785px -21px; }
.cus-cart{ background-position: -1806px -21px; }
.cus-cart_add{ background-position: -1827px -21px; }
.cus-cart_delete{ background-position: -1848px -21px; }
.cus-cart_edit{ background-position: -1869px -21px; }
.cus-cart_error{ background-position: -1890px -21px; }
.cus-cart_go{ background-position: -1911px -21px; }
.cus-cart_put{ background-position: -1932px -21px; }
.cus-cart_remove{ background-position: -1953px -21px; }
.cus-cd{ background-position: -1974px -21px; }
.cus-cd_add{ background-position: 0 -42px; }
.cus-cd_burn{ background-position: -21px -42px; }
.cus-cd_delete{ background-position: -42px -42px; }
.cus-cd_edit{ background-position: -63px -42px; }
.cus-cd_eject{ background-position: -84px -42px; }
.cus-cd_go{ background-position: -105px -42px; }
.cus-chart_bar{ background-position: -126px -42px; }
.cus-chart_bar_add{ background-position: -147px -42px; }
.cus-chart_bar_delete{ background-position: -168px -42px; }
.cus-chart_bar_edit{ background-position: -189px -42px; }
.cus-chart_bar_error{ background-position: -210px -42px; }
.cus-chart_bar_link{ background-position: -231px -42px; }
.cus-chart_curve{ background-position: -252px -42px; }
.cus-chart_curve_add{ background-position: -273px -42px; }
.cus-chart_curve_delete{ background-position: -294px -42px; }
.cus-chart_curve_edit{ background-position: -315px -42px; }
.cus-chart_curve_error{ background-position: -336px -42px; }
.cus-chart_curve_go{ background-position: -357px -42px; }
.cus-chart_curve_link{ background-position: -378px -42px; }
.cus-chart_line{ background-position: -399px -42px; }
.cus-chart_line_add{ background-position: -420px -42px; }
.cus-chart_line_delete{ background-position: -441px -42px; }
.cus-chart_line_edit{ background-position: -462px -42px; }
.cus-chart_line_error{ background-position: -483px -42px; }
.cus-chart_line_link{ background-position: -504px -42px; }
.cus-chart_organisation{ background-position: -525px -42px; }
.cus-chart_organisation_add{ background-position: -546px -42px; }
.cus-chart_organisation_delete{ background-position: -567px -42px; }
.cus-chart_pie{ background-position: -588px -42px; }
.cus-chart_pie_add{ background-position: -609px -42px; }
.cus-chart_pie_delete{ background-position: -630px -42px; }
.cus-chart_pie_edit{ background-position: -651px -42px; }
.cus-chart_pie_error{ background-position: -672px -42px; }
.cus-chart_pie_link{ background-position: -693px -42px; }
.cus-clock{ background-position: -714px -42px; }
.cus-clock_add{ background-position: -735px -42px; }
.cus-clock_delete{ background-position: -756px -42px; }
.cus-clock_edit{ background-position: -777px -42px; }
.cus-clock_error{ background-position: -798px -42px; }
.cus-clock_go{ background-position: -819px -42px; }
.cus-clock_link{ background-position: -840px -42px; }
.cus-clock_pause{ background-position: -861px -42px; }
.cus-clock_play{ background-position: -882px -42px; }
.cus-clock_red{ background-position: -903px -42px; }
.cus-clock_stop{ background-position: -924px -42px; }
.cus-cog{ background-position: -945px -42px; }
.cus-cog_add{ background-position: -966px -42px; }
.cus-cog_delete{ background-position: -987px -42px; }
.cus-cog_edit{ background-position: -1008px -42px; }
.cus-cog_error{ background-position: -1029px -42px; }
.cus-cog_go{ background-position: -1050px -42px; }
.cus-coins{ background-position: -1071px -42px; }
.cus-coins_add{ background-position: -1092px -42px; }
.cus-coins_delete{ background-position: -1113px -42px; }
.cus-color_swatch{ background-position: -1134px -42px; }
.cus-color_wheel{ background-position: -1155px -42px; }
.cus-comment{ background-position: -1176px -42px; }
.cus-comment_add{ background-position: -1197px -42px; }
.cus-comment_delete{ background-position: -1218px -42px; }
.cus-comment_edit{ background-position: -1239px -42px; }
.cus-comments{ background-position: -1260px -42px; }
.cus-comments_add{ background-position: -1281px -42px; }
.cus-comments_delete{ background-position: -1302px -42px; }
.cus-compress{ background-position: -1323px -42px; }
.cus-computer{ background-position: -1344px -42px; }
.cus-computer_add{ background-position: -1365px -42px; }
.cus-computer_delete{ background-position: -1386px -42px; }
.cus-computer_edit{ background-position: -1407px -42px; }
.cus-computer_error{ background-position: -1428px -42px; }
.cus-computer_go{ background-position: -1449px -42px; }
.cus-computer_key{ background-position: -1470px -42px; }
.cus-computer_link{ background-position: -1491px -42px; }
.cus-connect{ background-position: -1512px -42px; }
.cus-contrast{ background-position: -1533px -42px; }
.cus-contrast_decrease{ background-position: -1554px -42px; }
.cus-contrast_high{ background-position: -1575px -42px; }
.cus-contrast_increase{ background-position: -1596px -42px; }
.cus-contrast_low{ background-position: -1617px -42px; }
.cus-control_eject{ background-position: -1638px -42px; }
.cus-control_eject_blue{ background-position: -1659px -42px; }
.cus-control_end{ background-position: -1680px -42px; }
.cus-control_end_blue{ background-position: -1701px -42px; }
.cus-control_equalizer{ background-position: -1722px -42px; }
.cus-control_equalizer_blue{ background-position: -1743px -42px; }
.cus-control_fastforward{ background-position: -1764px -42px; }
.cus-control_fastforward_blue{ background-position: -1785px -42px; }
.cus-control_pause{ background-position: -1806px -42px; }
.cus-control_pause_blue{ background-position: -1827px -42px; }
.cus-control_play{ background-position: -1848px -42px; }
.cus-control_play_blue{ background-position: -1869px -42px; }
.cus-control_repeat{ background-position: -1890px -42px; }
.cus-control_repeat_blue{ background-position: -1911px -42px; }
.cus-control_rewind{ background-position: -1932px -42px; }
.cus-control_rewind_blue{ background-position: -1953px -42px; }
.cus-control_start{ background-position: -1974px -42px; }
.cus-control_start_blue{ background-position: 0 -63px; }
.cus-control_stop{ background-position: -21px -63px; }
.cus-control_stop_blue{ background-position: -42px -63px; }
.cus-controller{ background-position: -63px -63px; }
.cus-controller_add{ background-position: -84px -63px; }
.cus-controller_delete{ background-position: -105px -63px; }
.cus-controller_error{ background-position: -126px -63px; }
.cus-creditcards{ background-position: -147px -63px; }
.cus-cross{ background-position: -168px -63px; }
.cus-css{ background-position: -189px -63px; }
.cus-css_add{ background-position: -210px -63px; }
.cus-css_delete{ background-position: -231px -63px; }
.cus-css_go{ background-position: -252px -63px; }
.cus-css_valid{ background-position: -273px -63px; }
.cus-cup{ background-position: -294px -63px; }
.cus-cup_add{ background-position: -315px -63px; }
.cus-cup_delete{ background-position: -336px -63px; }
.cus-cup_edit{ background-position: -357px -63px; }
.cus-cup_error{ background-position: -378px -63px; }
.cus-cup_go{ background-position: -399px -63px; }
.cus-cup_key{ background-position: -420px -63px; }
.cus-cup_link{ background-position: -441px -63px; }
.cus-cursor{ background-position: -462px -63px; }
.cus-cut{ background-position: -483px -63px; }
.cus-cut_red{ background-position: -504px -63px; }
.cus-database{ background-position: -525px -63px; }
.cus-database_add{ background-position: -546px -63px; }
.cus-database_connect{ background-position: -567px -63px; }
.cus-database_delete{ background-position: -588px -63px; }
.cus-database_edit{ background-position: -609px -63px; }
.cus-database_error{ background-position: -630px -63px; }
.cus-database_gear{ background-position: -651px -63px; }
.cus-database_go{ background-position: -672px -63px; }
.cus-database_key{ background-position: -693px -63px; }
.cus-database_lightning{ background-position: -714px -63px; }
.cus-database_link{ background-position: -735px -63px; }
.cus-database_refresh{ background-position: -756px -63px; }
.cus-database_save{ background-position: -777px -63px; }
.cus-database_table{ background-position: -798px -63px; }
.cus-date{ background-position: -819px -63px; }
.cus-date_add{ background-position: -840px -63px; }
.cus-date_delete{ background-position: -861px -63px; }
.cus-date_edit{ background-position: -882px -63px; }
.cus-date_error{ background-position: -903px -63px; }
.cus-date_go{ background-position: -924px -63px; }
.cus-date_link{ background-position: -945px -63px; }
.cus-date_magnify{ background-position: -966px -63px; }
.cus-date_next{ background-position: -987px -63px; }
.cus-date_previous{ background-position: -1008px -63px; }
.cus-delete{ background-position: -1029px -63px; }
.cus-disconnect{ background-position: -1050px -63px; }
.cus-disk{ background-position: -1071px -63px; }
.cus-disk_multiple{ background-position: -1092px -63px; }
.cus-door{ background-position: -1113px -63px; }
.cus-door_in{ background-position: -1134px -63px; }
.cus-door_open{ background-position: -1155px -63px; }
.cus-door_out{ background-position: -1176px -63px; }
.cus-drink{ background-position: -1197px -63px; }
.cus-drink_empty{ background-position: -1218px -63px; }
.cus-drive{ background-position: -1239px -63px; }
.cus-drive_add{ background-position: -1260px -63px; }
.cus-drive_burn{ background-position: -1281px -63px; }
.cus-drive_cd{ background-position: -1302px -63px; }
.cus-drive_cd_empty{ background-position: -1323px -63px; }
.cus-drive_delete{ background-position: -1344px -63px; }
.cus-drive_disk{ background-position: -1365px -63px; }
.cus-drive_edit{ background-position: -1386px -63px; }
.cus-drive_error{ background-position: -1407px -63px; }
.cus-drive_go{ background-position: -1428px -63px; }
.cus-drive_key{ background-position: -1449px -63px; }
.cus-drive_link{ background-position: -1470px -63px; }
.cus-drive_magnify{ background-position: -1491px -63px; }
.cus-drive_network{ background-position: -1512px -63px; }
.cus-drive_rename{ background-position: -1533px -63px; }
.cus-drive_user{ background-position: -1554px -63px; }
.cus-drive_web{ background-position: -1575px -63px; }
.cus-dvd{ background-position: -1596px -63px; }
.cus-dvd_add{ background-position: -1617px -63px; }
.cus-dvd_delete{ background-position: -1638px -63px; }
.cus-dvd_edit{ background-position: -1659px -63px; }
.cus-dvd_error{ background-position: -1680px -63px; }
.cus-dvd_go{ background-position: -1701px -63px; }
.cus-dvd_key{ background-position: -1722px -63px; }
.cus-dvd_link{ background-position: -1743px -63px; }
.cus-email{ background-position: -1764px -63px; }
.cus-email_add{ background-position: -1785px -63px; }
.cus-email_attach{ background-position: -1806px -63px; }
.cus-email_delete{ background-position: -1827px -63px; }
.cus-email_edit{ background-position: -1848px -63px; }
.cus-email_error{ background-position: -1869px -63px; }
.cus-email_go{ background-position: -1890px -63px; }
.cus-email_link{ background-position: -1911px -63px; }
.cus-email_open{ background-position: -1932px -63px; }
.cus-email_open_image{ background-position: -1953px -63px; }
.cus-emoticon_evilgrin{ background-position: -1974px -63px; }
.cus-emoticon_grin{ background-position: 0 -84px; }
.cus-emoticon_happy{ background-position: -21px -84px; }
.cus-emoticon_smile{ background-position: -42px -84px; }
.cus-emoticon_surprised{ background-position: -63px -84px; }
.cus-emoticon_tongue{ background-position: -84px -84px; }
.cus-emoticon_unhappy{ background-position: -105px -84px; }
.cus-emoticon_waii{ background-position: -126px -84px; }
.cus-emoticon_wink{ background-position: -147px -84px; }
.cus-error{ background-position: -168px -84px; }
.cus-error_add{ background-position: -189px -84px; }
.cus-error_delete{ background-position: -210px -84px; }
.cus-error_go{ background-position: -231px -84px; }
.cus-exclamation{ background-position: -252px -84px; }
.cus-eye{ background-position: -273px -84px; }
.cus-feed{ background-position: -294px -84px; }
.cus-feed_add{ background-position: -315px -84px; }
.cus-feed_delete{ background-position: -336px -84px; }
.cus-feed_disk{ background-position: -357px -84px; }
.cus-feed_edit{ background-position: -378px -84px; }
.cus-feed_error{ background-position: -399px -84px; }
.cus-feed_go{ background-position: -420px -84px; }
.cus-feed_key{ background-position: -441px -84px; }
.cus-feed_link{ background-position: -462px -84px; }
.cus-feed_magnify{ background-position: -483px -84px; }
.cus-female{ background-position: -504px -84px; }
.cus-film{ background-position: -525px -84px; }
.cus-film_add{ background-position: -546px -84px; }
.cus-film_delete{ background-position: -567px -84px; }
.cus-film_edit{ background-position: -588px -84px; }
.cus-film_error{ background-position: -609px -84px; }
.cus-film_go{ background-position: -630px -84px; }
.cus-film_key{ background-position: -651px -84px; }
.cus-film_link{ background-position: -672px -84px; }
.cus-film_save{ background-position: -693px -84px; }
.cus-find{ background-position: -714px -84px; }
.cus-flag_blue{ background-position: -735px -84px; }
.cus-flag_green{ background-position: -756px -84px; }
.cus-flag_orange{ background-position: -777px -84px; }
.cus-flag_pink{ background-position: -798px -84px; }
.cus-flag_purple{ background-position: -819px -84px; }
.cus-flag_red{ background-position: -840px -84px; }
.cus-flag_yellow{ background-position: -861px -84px; }
.cus-folder{ background-position: -882px -84px; }
.cus-folder_add{ background-position: -903px -84px; }
.cus-folder_bell{ background-position: -924px -84px; }
.cus-folder_brick{ background-position: -945px -84px; }
.cus-folder_bug{ background-position: -966px -84px; }
.cus-folder_camera{ background-position: -987px -84px; }
.cus-folder_database{ background-position: -1008px -84px; }
.cus-folder_delete{ background-position: -1029px -84px; }
.cus-folder_edit{ background-position: -1050px -84px; }
.cus-folder_error{ background-position: -1071px -84px; }
.cus-folder_explore{ background-position: -1092px -84px; }
.cus-folder_feed{ background-position: -1113px -84px; }
.cus-folder_find{ background-position: -1134px -84px; }
.cus-folder_go{ background-position: -1155px -84px; }
.cus-folder_heart{ background-position: -1176px -84px; }
.cus-folder_image{ background-position: -1197px -84px; }
.cus-folder_key{ background-position: -1218px -84px; }
.cus-folder_lightbulb{ background-position: -1239px -84px; }
.cus-folder_link{ background-position: -1260px -84px; }
.cus-folder_magnify{ background-position: -1281px -84px; }
.cus-folder_page{ background-position: -1302px -84px; }
.cus-folder_page_white{ background-position: -1323px -84px; }
.cus-folder_palette{ background-position: -1344px -84px; }
.cus-folder_picture{ background-position: -1365px -84px; }
.cus-folder_star{ background-position: -1386px -84px; }
.cus-folder_table{ background-position: -1407px -84px; }
.cus-folder_user{ background-position: -1428px -84px; }
.cus-folder_wrench{ background-position: -1449px -84px; }
.cus-font{ background-position: -1470px -84px; }
.cus-font_add{ background-position: -1491px -84px; }
.cus-font_delete{ background-position: -1512px -84px; }
.cus-font_go{ background-position: -1533px -84px; }
.cus-group{ background-position: -1554px -84px; }
.cus-group_add{ background-position: -1575px -84px; }
.cus-group_delete{ background-position: -1596px -84px; }
.cus-group_edit{ background-position: -1617px -84px; }
.cus-group_error{ background-position: -1638px -84px; }
.cus-group_gear{ background-position: -1659px -84px; }
.cus-group_go{ background-position: -1680px -84px; }
.cus-group_key{ background-position: -1701px -84px; }
.cus-group_link{ background-position: -1722px -84px; }
.cus-heart{ background-position: -1743px -84px; }
.cus-heart_add{ background-position: -1764px -84px; }
.cus-heart_delete{ background-position: -1785px -84px; }
.cus-help{ background-position: -1806px -84px; }
.cus-hourglass{ background-position: -1827px -84px; }
.cus-hourglass_add{ background-position: -1848px -84px; }
.cus-hourglass_delete{ background-position: -1869px -84px; }
.cus-hourglass_go{ background-position: -1890px -84px; }
.cus-hourglass_link{ background-position: -1911px -84px; }
.cus-house{ background-position: -1932px -84px; }
.cus-house_go{ background-position: -1953px -84px; }
.cus-house_link{ background-position: -1974px -84px; }
.cus-html{ background-position: 0 -105px; }
.cus-html_add{ background-position: -21px -105px; }
.cus-html_delete{ background-position: -42px -105px; }
.cus-html_go{ background-position: -63px -105px; }
.cus-html_valid{ background-position: -84px -105px; }
.cus-image{ background-position: -105px -105px; }
.cus-image_add{ background-position: -126px -105px; }
.cus-image_delete{ background-position: -147px -105px; }
.cus-image_edit{ background-position: -168px -105px; }
.cus-image_link{ background-position: -189px -105px; }
.cus-images{ background-position: -210px -105px; }
.cus-information{ background-position: -231px -105px; }
.cus-ipod{ background-position: -252px -105px; }
.cus-ipod_cast{ background-position: -273px -105px; }
.cus-ipod_cast_add{ background-position: -294px -105px; }
.cus-ipod_cast_delete{ background-position: -315px -105px; }
.cus-ipod_sound{ background-position: -336px -105px; }
.cus-joystick{ background-position: -357px -105px; }
.cus-joystick_add{ background-position: -378px -105px; }
.cus-joystick_delete{ background-position: -399px -105px; }
.cus-joystick_error{ background-position: -420px -105px; }
.cus-key{ background-position: -441px -105px; }
.cus-key_add{ background-position: -462px -105px; }
.cus-key_delete{ background-position: -483px -105px; }
.cus-key_go{ background-position: -504px -105px; }
.cus-keyboard{ background-position: -525px -105px; }
.cus-keyboard_add{ background-position: -546px -105px; }
.cus-keyboard_delete{ background-position: -567px -105px; }
.cus-keyboard_magnify{ background-position: -588px -105px; }
.cus-layers{ background-position: -609px -105px; }
.cus-layout{ background-position: -630px -105px; }
.cus-layout_add{ background-position: -651px -105px; }
.cus-layout_content{ background-position: -672px -105px; }
.cus-layout_delete{ background-position: -693px -105px; }
.cus-layout_edit{ background-position: -714px -105px; }
.cus-layout_error{ background-position: -735px -105px; }
.cus-layout_header{ background-position: -756px -105px; }
.cus-layout_link{ background-position: -777px -105px; }
.cus-layout_sidebar{ background-position: -798px -105px; }
.cus-lightbulb{ background-position: -819px -105px; }
.cus-lightbulb_add{ background-position: -840px -105px; }
.cus-lightbulb_delete{ background-position: -861px -105px; }
.cus-lightbulb_off{ background-position: -882px -105px; }
.cus-lightning{ background-position: -903px -105px; }
.cus-lightning_add{ background-position: -924px -105px; }
.cus-lightning_delete{ background-position: -945px -105px; }
.cus-lightning_go{ background-position: -966px -105px; }
.cus-link{ background-position: -987px -105px; }
.cus-link_add{ background-position: -1008px -105px; }
.cus-link_break{ background-position: -1029px -105px; }
.cus-link_delete{ background-position: -1050px -105px; }
.cus-link_edit{ background-position: -1071px -105px; }
.cus-link_error{ background-position: -1092px -105px; }
.cus-link_go{ background-position: -1113px -105px; }
.cus-lock{ background-position: -1134px -105px; }
.cus-lock_add{ background-position: -1155px -105px; }
.cus-lock_break{ background-position: -1176px -105px; }
.cus-lock_delete{ background-position: -1197px -105px; }
.cus-lock_edit{ background-position: -1218px -105px; }
.cus-lock_go{ background-position: -1239px -105px; }
.cus-lock_open{ background-position: -1260px -105px; }
.cus-lorry{ background-position: -1281px -105px; }
.cus-lorry_add{ background-position: -1302px -105px; }
.cus-lorry_delete{ background-position: -1323px -105px; }
.cus-lorry_error{ background-position: -1344px -105px; }
.cus-lorry_flatbed{ background-position: -1365px -105px; }
.cus-lorry_go{ background-position: -1386px -105px; }
.cus-lorry_link{ background-position: -1407px -105px; }
.cus-magifier_zoom_out{ background-position: -1428px -105px; }
.cus-magnifier{ background-position: -1449px -105px; }
.cus-magnifier_zoom_in{ background-position: -1470px -105px; }
.cus-male{ background-position: -1491px -105px; }
.cus-map{ background-position: -1512px -105px; }
.cus-map_add{ background-position: -1533px -105px; }
.cus-map_delete{ background-position: -1554px -105px; }
.cus-map_edit{ background-position: -1575px -105px; }
.cus-map_go{ background-position: -1596px -105px; }
.cus-map_magnify{ background-position: -1617px -105px; }
.cus-medal_bronze_1{ background-position: -1638px -105px; }
.cus-medal_bronze_2{ background-position: -1659px -105px; }
.cus-medal_bronze_3{ background-position: -1680px -105px; }
.cus-medal_bronze_add{ background-position: -1701px -105px; }
.cus-medal_bronze_delete{ background-position: -1722px -105px; }
.cus-medal_gold_1{ background-position: -1743px -105px; }
.cus-medal_gold_2{ background-position: -1764px -105px; }
.cus-medal_gold_3{ background-position: -1785px -105px; }
.cus-medal_gold_add{ background-position: -1806px -105px; }
.cus-medal_gold_delete{ background-position: -1827px -105px; }
.cus-medal_silver_1{ background-position: -1848px -105px; }
.cus-medal_silver_2{ background-position: -1869px -105px; }
.cus-medal_silver_3{ background-position: -1890px -105px; }
.cus-medal_silver_add{ background-position: -1911px -105px; }
.cus-medal_silver_delete{ background-position: -1932px -105px; }
.cus-money{ background-position: -1953px -105px; }
.cus-money_add{ background-position: -1974px -105px; }
.cus-money_delete{ background-position: 0 -126px; }
.cus-money_dollar{ background-position: -21px -126px; }
.cus-money_euro{ background-position: -42px -126px; }
.cus-money_pound{ background-position: -63px -126px; }
.cus-money_yen{ background-position: -84px -126px; }
.cus-monitor{ background-position: -105px -126px; }
.cus-monitor_add{ background-position: -126px -126px; }
.cus-monitor_delete{ background-position: -147px -126px; }
.cus-monitor_edit{ background-position: -168px -126px; }
.cus-monitor_error{ background-position: -189px -126px; }
.cus-monitor_go{ background-position: -210px -126px; }
.cus-monitor_lightning{ background-position: -231px -126px; }
.cus-monitor_link{ background-position: -252px -126px; }
.cus-mouse{ background-position: -273px -126px; }
.cus-mouse_add{ background-position: -294px -126px; }
.cus-mouse_delete{ background-position: -315px -126px; }
.cus-mouse_error{ background-position: -336px -126px; }
.cus-music{ background-position: -357px -126px; }
.cus-new{ background-position: -378px -126px; }
.cus-newspaper{ background-position: -399px -126px; }
.cus-newspaper_add{ background-position: -420px -126px; }
.cus-newspaper_delete{ background-position: -441px -126px; }
.cus-newspaper_go{ background-position: -462px -126px; }
.cus-newspaper_link{ background-position: -483px -126px; }
.cus-note{ background-position: -504px -126px; }
.cus-note_add{ background-position: -525px -126px; }
.cus-note_delete{ background-position: -546px -126px; }
.cus-note_edit{ background-position: -567px -126px; }
.cus-note_error{ background-position: -588px -126px; }
.cus-note_go{ background-position: -609px -126px; }
.cus-overlays{ background-position: -630px -126px; }
.cus-package{ background-position: -651px -126px; }
.cus-package_add{ background-position: -672px -126px; }
.cus-package_delete{ background-position: -693px -126px; }
.cus-package_go{ background-position: -714px -126px; }
.cus-package_green{ background-position: -735px -126px; }
.cus-package_link{ background-position: -756px -126px; }
.cus-page{ background-position: -777px -126px; }
.cus-page_add{ background-position: -798px -126px; }
.cus-page_attach{ background-position: -819px -126px; }
.cus-page_code{ background-position: -840px -126px; }
.cus-page_copy{ background-position: -861px -126px; }
.cus-page_delete{ background-position: -882px -126px; }
.cus-page_edit{ background-position: -903px -126px; }
.cus-page_error{ background-position: -924px -126px; }
.cus-page_excel{ background-position: -945px -126px; }
.cus-page_find{ background-position: -966px -126px; }
.cus-page_gear{ background-position: -987px -126px; }
.cus-page_go{ background-position: -1008px -126px; }
.cus-page_green{ background-position: -1029px -126px; }
.cus-page_key{ background-position: -1050px -126px; }
.cus-page_lightning{ background-position: -1071px -126px; }
.cus-page_link{ background-position: -1092px -126px; }
.cus-page_paintbrush{ background-position: -1113px -126px; }
.cus-page_paste{ background-position: -1134px -126px; }
.cus-page_red{ background-position: -1155px -126px; }
.cus-page_refresh{ background-position: -1176px -126px; }
.cus-page_save{ background-position: -1197px -126px; }
.cus-page_white{ background-position: -1218px -126px; }
.cus-page_white_acrobat{ background-position: -1239px -126px; }
.cus-page_white_actionscript{ background-position: -1260px -126px; }
.cus-page_white_add{ background-position: -1281px -126px; }
.cus-page_white_c{ background-position: -1302px -126px; }
.cus-page_white_camera{ background-position: -1323px -126px; }
.cus-page_white_cd{ background-position: -1344px -126px; }
.cus-page_white_code{ background-position: -1365px -126px; }
.cus-page_white_code_red{ background-position: -1386px -126px; }
.cus-page_white_coldfusion{ background-position: -1407px -126px; }
.cus-page_white_compressed{ background-position: -1428px -126px; }
.cus-page_white_copy{ background-position: -1449px -126px; }
.cus-page_white_cplusplus{ background-position: -1470px -126px; }
.cus-page_white_csharp{ background-position: -1491px -126px; }
.cus-page_white_cup{ background-position: -1512px -126px; }
.cus-page_white_database{ background-position: -1533px -126px; }
.cus-page_white_delete{ background-position: -1554px -126px; }
.cus-page_white_dvd{ background-position: -1575px -126px; }
.cus-page_white_edit{ background-position: -1596px -126px; }
.cus-page_white_error{ background-position: -1617px -126px; }
.cus-page_white_excel{ background-position: -1638px -126px; }
.cus-page_white_find{ background-position: -1659px -126px; }
.cus-page_white_flash{ background-position: -1680px -126px; }
.cus-page_white_freehand{ background-position: -1701px -126px; }
.cus-page_white_gear{ background-position: -1722px -126px; }
.cus-page_white_get{ background-position: -1743px -126px; }
.cus-page_white_go{ background-position: -1764px -126px; }
.cus-page_white_h{ background-position: -1785px -126px; }
.cus-page_white_horizontal{ background-position: -1806px -126px; }
.cus-page_white_key{ background-position: -1827px -126px; }
.cus-page_white_lightning{ background-position: -1848px -126px; }
.cus-page_white_link{ background-position: -1869px -126px; }
.cus-page_white_magnify{ background-position: -1890px -126px; }
.cus-page_white_medal{ background-position: -1911px -126px; }
.cus-page_white_office{ background-position: -1932px -126px; }
.cus-page_white_paint{ background-position: -1953px -126px; }
.cus-page_white_paintbrush{ background-position: -1974px -126px; }
.cus-page_white_paste{ background-position: 0 -147px; }
.cus-page_white_php{ background-position: -21px -147px; }
.cus-page_white_picture{ background-position: -42px -147px; }
.cus-page_white_powerpoint{ background-position: -63px -147px; }
.cus-page_white_put{ background-position: -84px -147px; }
.cus-page_white_ruby{ background-position: -105px -147px; }
.cus-page_white_stack{ background-position: -126px -147px; }
.cus-page_white_star{ background-position: -147px -147px; }
.cus-page_white_swoosh{ background-position: -168px -147px; }
.cus-page_white_text{ background-position: -189px -147px; }
.cus-page_white_text_width{ background-position: -210px -147px; }
.cus-page_white_tux{ background-position: -231px -147px; }
.cus-page_white_vector{ background-position: -252px -147px; }
.cus-page_white_visualstudio{ background-position: -273px -147px; }
.cus-page_white_width{ background-position: -294px -147px; }
.cus-page_white_word{ background-position: -315px -147px; }
.cus-page_white_world{ background-position: -336px -147px; }
.cus-page_white_wrench{ background-position: -357px -147px; }
.cus-page_white_zip{ background-position: -378px -147px; }
.cus-page_word{ background-position: -399px -147px; }
.cus-page_world{ background-position: -420px -147px; }
.cus-paintbrush{ background-position: -441px -147px; }
.cus-paintcan{ background-position: -462px -147px; }
.cus-palette{ background-position: -483px -147px; }
.cus-paste_plain{ background-position: -504px -147px; }
.cus-paste_word{ background-position: -525px -147px; }
.cus-pencil{ background-position: -546px -147px; }
.cus-pencil_add{ background-position: -567px -147px; }
.cus-pencil_delete{ background-position: -588px -147px; }
.cus-pencil_go{ background-position: -609px -147px; }
.cus-phone{ background-position: -630px -147px; }
.cus-phone_add{ background-position: -651px -147px; }
.cus-phone_delete{ background-position: -672px -147px; }
.cus-phone_sound{ background-position: -693px -147px; }
.cus-photo{ background-position: -714px -147px; }
.cus-photo_add{ background-position: -735px -147px; }
.cus-photo_delete{ background-position: -756px -147px; }
.cus-photo_link{ background-position: -777px -147px; }
.cus-photos{ background-position: -798px -147px; }
.cus-picture{ background-position: -819px -147px; }
.cus-picture_add{ background-position: -840px -147px; }
.cus-picture_delete{ background-position: -861px -147px; }
.cus-picture_edit{ background-position: -882px -147px; }
.cus-picture_empty{ background-position: -903px -147px; }
.cus-picture_error{ background-position: -924px -147px; }
.cus-picture_go{ background-position: -945px -147px; }
.cus-picture_key{ background-position: -966px -147px; }
.cus-picture_link{ background-position: -987px -147px; }
.cus-picture_save{ background-position: -1008px -147px; }
.cus-pictures{ background-position: -1029px -147px; }
.cus-pilcrow{ background-position: -1050px -147px; }
.cus-pill{ background-position: -1071px -147px; }
.cus-pill_add{ background-position: -1092px -147px; }
.cus-pill_delete{ background-position: -1113px -147px; }
.cus-pill_go{ background-position: -1134px -147px; }
.cus-plugin{ background-position: -1155px -147px; }
.cus-plugin_add{ background-position: -1176px -147px; }
.cus-plugin_delete{ background-position: -1197px -147px; }
.cus-plugin_disabled{ background-position: -1218px -147px; }
.cus-plugin_edit{ background-position: -1239px -147px; }
.cus-plugin_error{ background-position: -1260px -147px; }
.cus-plugin_go{ background-position: -1281px -147px; }
.cus-plugin_link{ background-position: -1302px -147px; }
.cus-printer{ background-position: -1323px -147px; }
.cus-printer_add{ background-position: -1344px -147px; }
.cus-printer_delete{ background-position: -1365px -147px; }
.cus-printer_empty{ background-position: -1386px -147px; }
.cus-printer_error{ background-position: -1407px -147px; }
.cus-rainbow{ background-position: -1428px -147px; }
.cus-report{ background-position: -1449px -147px; }
.cus-report_add{ background-position: -1470px -147px; }
.cus-report_delete{ background-position: -1491px -147px; }
.cus-report_disk{ background-position: -1512px -147px; }
.cus-report_edit{ background-position: -1533px -147px; }
.cus-report_go{ background-position: -1554px -147px; }
.cus-report_key{ background-position: -1575px -147px; }
.cus-report_link{ background-position: -1596px -147px; }
.cus-report_magnify{ background-position: -1617px -147px; }
.cus-report_picture{ background-position: -1638px -147px; }
.cus-report_user{ background-position: -1659px -147px; }
.cus-report_word{ background-position: -1680px -147px; }
.cus-resultset_first{ background-position: -1701px -147px; }
.cus-resultset_last{ background-position: -1722px -147px; }
.cus-resultset_next{ background-position: -1743px -147px; }
.cus-resultset_previous{ background-position: -1764px -147px; }
.cus-rosette{ background-position: -1785px -147px; }
.cus-rss{ background-position: -1806px -147px; }
.cus-rss_add{ background-position: -1827px -147px; }
.cus-rss_delete{ background-position: -1848px -147px; }
.cus-rss_go{ background-position: -1869px -147px; }
.cus-rss_valid{ background-position: -1890px -147px; }
.cus-ruby{ background-position: -1911px -147px; }
.cus-ruby_add{ background-position: -1932px -147px; }
.cus-ruby_delete{ background-position: -1953px -147px; }
.cus-ruby_gear{ background-position: -1974px -147px; }
.cus-ruby_get{ background-position: 0 -168px; }
.cus-ruby_go{ background-position: -21px -168px; }
.cus-ruby_key{ background-position: -42px -168px; }
.cus-ruby_link{ background-position: -63px -168px; }
.cus-ruby_put{ background-position: -84px -168px; }
.cus-script{ background-position: -105px -168px; }
.cus-script_add{ background-position: -126px -168px; }
.cus-script_code{ background-position: -147px -168px; }
.cus-script_code_red{ background-position: -168px -168px; }
.cus-script_delete{ background-position: -189px -168px; }
.cus-script_edit{ background-position: -210px -168px; }
.cus-script_error{ background-position: -231px -168px; }
.cus-script_gear{ background-position: -252px -168px; }
.cus-script_go{ background-position: -273px -168px; }
.cus-script_key{ background-position: -294px -168px; }
.cus-script_lightning{ background-position: -315px -168px; }
.cus-script_link{ background-position: -336px -168px; }
.cus-script_palette{ background-position: -357px -168px; }
.cus-script_save{ background-position: -378px -168px; }
.cus-server{ background-position: -399px -168px; }
.cus-server_add{ background-position: -420px -168px; }
.cus-server_chart{ background-position: -441px -168px; }
.cus-server_compressed{ background-position: -462px -168px; }
.cus-server_connect{ background-position: -483px -168px; }
.cus-server_database{ background-position: -504px -168px; }
.cus-server_delete{ background-position: -525px -168px; }
.cus-server_edit{ background-position: -546px -168px; }
.cus-server_error{ background-position: -567px -168px; }
.cus-server_go{ background-position: -588px -168px; }
.cus-server_key{ background-position: -609px -168px; }
.cus-server_lightning{ background-position: -630px -168px; }
.cus-server_link{ background-position: -651px -168px; }
.cus-server_uncompressed{ background-position: -672px -168px; }
.cus-shading{ background-position: -693px -168px; }
.cus-shape_align_bottom{ background-position: -714px -168px; }
.cus-shape_align_center{ background-position: -735px -168px; }
.cus-shape_align_left{ background-position: -756px -168px; }
.cus-shape_align_middle{ background-position: -777px -168px; }
.cus-shape_align_right{ background-position: -798px -168px; }
.cus-shape_align_top{ background-position: -819px -168px; }
.cus-shape_flip_horizontal{ background-position: -840px -168px; }
.cus-shape_flip_vertical{ background-position: -861px -168px; }
.cus-shape_group{ background-position: -882px -168px; }
.cus-shape_handles{ background-position: -903px -168px; }
.cus-shape_move_back{ background-position: -924px -168px; }
.cus-shape_move_backwards{ background-position: -945px -168px; }
.cus-shape_move_forwards{ background-position: -966px -168px; }
.cus-shape_move_front{ background-position: -987px -168px; }
.cus-shape_rotate_anticlockwise{ background-position: -1008px -168px; }
.cus-shape_rotate_clockwise{ background-position: -1029px -168px; }
.cus-shape_square{ background-position: -1050px -168px; }
.cus-shape_square_add{ background-position: -1071px -168px; }
.cus-shape_square_delete{ background-position: -1092px -168px; }
.cus-shape_square_edit{ background-position: -1113px -168px; }
.cus-shape_square_error{ background-position: -1134px -168px; }
.cus-shape_square_go{ background-position: -1155px -168px; }
.cus-shape_square_key{ background-position: -1176px -168px; }
.cus-shape_square_link{ background-position: -1197px -168px; }
.cus-shape_ungroup{ background-position: -1218px -168px; }
.cus-shield{ background-position: -1239px -168px; }
.cus-shield_add{ background-position: -1260px -168px; }
.cus-shield_delete{ background-position: -1281px -168px; }
.cus-shield_go{ background-position: -1302px -168px; }
.cus-sitemap{ background-position: -1323px -168px; }
.cus-sitemap_color{ background-position: -1344px -168px; }
.cus-sound{ background-position: -1365px -168px; }
.cus-sound_add{ background-position: -1386px -168px; }
.cus-sound_delete{ background-position: -1407px -168px; }
.cus-sound_low{ background-position: -1428px -168px; }
.cus-sound_mute{ background-position: -1449px -168px; }
.cus-sound_none{ background-position: -1470px -168px; }
.cus-spellcheck{ background-position: -1491px -168px; }
.cus-sport_8ball{ background-position: -1512px -168px; }
.cus-sport_basketball{ background-position: -1533px -168px; }
.cus-sport_football{ background-position: -1554px -168px; }
.cus-sport_golf{ background-position: -1575px -168px; }
.cus-sport_raquet{ background-position: -1596px -168px; }
.cus-sport_shuttlecock{ background-position: -1617px -168px; }
.cus-sport_soccer{ background-position: -1638px -168px; }
.cus-sport_tennis{ background-position: -1659px -168px; }
.cus-star{ background-position: -1680px -168px; }
.cus-status_away{ background-position: -1701px -168px; }
.cus-status_busy{ background-position: -1722px -168px; }
.cus-status_offline{ background-position: -1743px -168px; }
.cus-status_online{ background-position: -1764px -168px; }
.cus-stop{ background-position: -1785px -168px; }
.cus-style{ background-position: -1806px -168px; }
.cus-style_add{ background-position: -1827px -168px; }
.cus-style_delete{ background-position: -1848px -168px; }
.cus-style_edit{ background-position: -1869px -168px; }
.cus-style_go{ background-position: -1890px -168px; }
.cus-sum{ background-position: -1911px -168px; }
.cus-tab{ background-position: -1932px -168px; }
.cus-tab_add{ background-position: -1953px -168px; }
.cus-tab_delete{ background-position: -1974px -168px; }
.cus-tab_edit{ background-position: 0 -189px; }
.cus-tab_go{ background-position: -21px -189px; }
.cus-table{ background-position: -42px -189px; }
.cus-table_add{ background-position: -63px -189px; }
.cus-table_delete{ background-position: -84px -189px; }
.cus-table_edit{ background-position: -105px -189px; }
.cus-table_error{ background-position: -126px -189px; }
.cus-table_gear{ background-position: -147px -189px; }
.cus-table_go{ background-position: -168px -189px; }
.cus-table_key{ background-position: -189px -189px; }
.cus-table_lightning{ background-position: -210px -189px; }
.cus-table_link{ background-position: -231px -189px; }
.cus-table_multiple{ background-position: -252px -189px; }
.cus-table_refresh{ background-position: -273px -189px; }
.cus-table_relationship{ background-position: -294px -189px; }
.cus-table_row_delete{ background-position: -315px -189px; }
.cus-table_row_insert{ background-position: -336px -189px; }
.cus-table_save{ background-position: -357px -189px; }
.cus-table_sort{ background-position: -378px -189px; }
.cus-tag{ background-position: -399px -189px; }
.cus-tag_blue{ background-position: -420px -189px; }
.cus-tag_blue_add{ background-position: -441px -189px; }
.cus-tag_blue_delete{ background-position: -462px -189px; }
.cus-tag_blue_edit{ background-position: -483px -189px; }
.cus-tag_green{ background-position: -504px -189px; }
.cus-tag_orange{ background-position: -525px -189px; }
.cus-tag_pink{ background-position: -546px -189px; }
.cus-tag_purple{ background-position: -567px -189px; }
.cus-tag_red{ background-position: -588px -189px; }
.cus-tag_yellow{ background-position: -609px -189px; }
.cus-telephone{ background-position: -630px -189px; }
.cus-telephone_add{ background-position: -651px -189px; }
.cus-telephone_delete{ background-position: -672px -189px; }
.cus-telephone_edit{ background-position: -693px -189px; }
.cus-telephone_error{ background-position: -714px -189px; }
.cus-telephone_go{ background-position: -735px -189px; }
.cus-telephone_key{ background-position: -756px -189px; }
.cus-telephone_link{ background-position: -777px -189px; }
.cus-television{ background-position: -798px -189px; }
.cus-television_add{ background-position: -819px -189px; }
.cus-television_delete{ background-position: -840px -189px; }
.cus-text_align_center{ background-position: -861px -189px; }
.cus-text_align_justify{ background-position: -882px -189px; }
.cus-text_align_left{ background-position: -903px -189px; }
.cus-text_align_right{ background-position: -924px -189px; }
.cus-text_allcaps{ background-position: -945px -189px; }
.cus-text_bold{ background-position: -966px -189px; }
.cus-text_columns{ background-position: -987px -189px; }
.cus-text_dropcaps{ background-position: -1008px -189px; }
.cus-text_heading_1{ background-position: -1029px -189px; }
.cus-text_heading_2{ background-position: -1050px -189px; }
.cus-text_heading_3{ background-position: -1071px -189px; }
.cus-text_heading_4{ background-position: -1092px -189px; }
.cus-text_heading_5{ background-position: -1113px -189px; }
.cus-text_heading_6{ background-position: -1134px -189px; }
.cus-text_horizontalrule{ background-position: -1155px -189px; }
.cus-text_indent{ background-position: -1176px -189px; }
.cus-text_indent_remove{ background-position: -1197px -189px; }
.cus-text_italic{ background-position: -1218px -189px; }
.cus-text_kerning{ background-position: -1239px -189px; }
.cus-text_letter_omega{ background-position: -1260px -189px; }
.cus-text_letterspacing{ background-position: -1281px -189px; }
.cus-text_linespacing{ background-position: -1302px -189px; }
.cus-text_list_bullets{ background-position: -1323px -189px; }
.cus-text_list_numbers{ background-position: -1344px -189px; }
.cus-text_lowercase{ background-position: -1365px -189px; }
.cus-text_padding_bottom{ background-position: -1386px -189px; }
.cus-text_padding_left{ background-position: -1407px -189px; }
.cus-text_padding_right{ background-position: -1428px -189px; }
.cus-text_padding_top{ background-position: -1449px -189px; }
.cus-text_replace{ background-position: -1470px -189px; }
.cus-text_signature{ background-position: -1491px -189px; }
.cus-text_smallcaps{ background-position: -1512px -189px; }
.cus-text_strikethrough{ background-position: -1533px -189px; }
.cus-text_subscript{ background-position: -1554px -189px; }
.cus-text_superscript{ background-position: -1575px -189px; }
.cus-text_underline{ background-position: -1596px -189px; }
.cus-text_uppercase{ background-position: -1617px -189px; }
.cus-textfield{ background-position: -1638px -189px; }
.cus-textfield_add{ background-position: -1659px -189px; }
.cus-textfield_delete{ background-position: -1680px -189px; }
.cus-textfield_key{ background-position: -1701px -189px; }
.cus-textfield_rename{ background-position: -1722px -189px; }
.cus-thumb_down{ background-position: -1743px -189px; }
.cus-thumb_up{ background-position: -1764px -189px; }
.cus-tick{ background-position: -1785px -189px; }
.cus-time{ background-position: -1806px -189px; }
.cus-time_add{ background-position: -1827px -189px; }
.cus-time_delete{ background-position: -1848px -189px; }
.cus-time_go{ background-position: -1869px -189px; }
.cus-timeline_marker{ background-position: -1890px -189px; }
.cus-transmit{ background-position: -1911px -189px; }
.cus-transmit_add{ background-position: -1932px -189px; }
.cus-transmit_blue{ background-position: -1953px -189px; }
.cus-transmit_delete{ background-position: -1974px -189px; }
.cus-transmit_edit{ background-position: 0 -210px; }
.cus-transmit_error{ background-position: -21px -210px; }
.cus-transmit_go{ background-position: -42px -210px; }
.cus-tux{ background-position: -63px -210px; }
.cus-user{ background-position: -84px -210px; }
.cus-user_add{ background-position: -105px -210px; }
.cus-user_comment{ background-position: -126px -210px; }
.cus-user_delete{ background-position: -147px -210px; }
.cus-user_edit{ background-position: -168px -210px; }
.cus-user_female{ background-position: -189px -210px; }
.cus-user_go{ background-position: -210px -210px; }
.cus-user_gray{ background-position: -231px -210px; }
.cus-user_green{ background-position: -252px -210px; }
.cus-user_orange{ background-position: -273px -210px; }
.cus-user_red{ background-position: -294px -210px; }
.cus-user_suit{ background-position: -315px -210px; }
.cus-vcard{ background-position: -336px -210px; }
.cus-vcard_add{ background-position: -357px -210px; }
.cus-vcard_delete{ background-position: -378px -210px; }
.cus-vcard_edit{ background-position: -399px -210px; }
.cus-vector{ background-position: -420px -210px; }
.cus-vector_add{ background-position: -441px -210px; }
.cus-vector_delete{ background-position: -462px -210px; }
.cus-wand{ background-position: -483px -210px; }
.cus-weather_clouds{ background-position: -504px -210px; }
.cus-weather_cloudy{ background-position: -525px -210px; }
.cus-weather_lightning{ background-position: -546px -210px; }
.cus-weather_rain{ background-position: -567px -210px; }
.cus-weather_snow{ background-position: -588px -210px; }
.cus-weather_sun{ background-position: -609px -210px; }
.cus-webcam{ background-position: -630px -210px; }
.cus-webcam_add{ background-position: -651px -210px; }
.cus-webcam_delete{ background-position: -672px -210px; }
.cus-webcam_error{ background-position: -693px -210px; }
.cus-world{ background-position: -714px -210px; }
.cus-world_add{ background-position: -735px -210px; }
.cus-world_delete{ background-position: -756px -210px; }
.cus-world_edit{ background-position: -777px -210px; }
.cus-world_go{ background-position: -798px -210px; }
.cus-world_link{ background-position: -819px -210px; }
.cus-wrench{ background-position: -840px -210px; }
.cus-wrench_orange{ background-position: -861px -210px; }
.cus-xhtml{ background-position: -882px -210px; }
.cus-xhtml_add{ background-position: -903px -210px; }
.cus-xhtml_delete{ background-position: -924px -210px; }
.cus-xhtml_go{ background-position: -945px -210px; }
.cus-xhtml_valid{ background-position: -966px -210px; }
.cus-zoom{ background-position: -987px -210px; }
.cus-zoom_in{ background-position: -1008px -210px; }
.cus-zoom_out{ background-position: -1029px -210px; }
| {
"content_hash": "a3c02e2ac492b1992a82caf4c2e6bcb4",
"timestamp": "",
"source": "github",
"line_count": 1018,
"max_line_length": 73,
"avg_line_length": 57.524557956778,
"alnum_prop": 0.7077868852459016,
"repo_name": "selboo/starl-mangle",
"id": "516bffe4c670a648a2b89d5351abedd9492163f1",
"size": "58560",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "template/css/fam-icons.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1463"
},
{
"name": "CSS",
"bytes": "197524"
},
{
"name": "HTML",
"bytes": "792119"
},
{
"name": "JavaScript",
"bytes": "517786"
},
{
"name": "PHP",
"bytes": "613053"
},
{
"name": "Python",
"bytes": "312293"
},
{
"name": "Shell",
"bytes": "4409"
}
],
"symlink_target": ""
} |
package org.interledger.ilp;
import org.interledger.InterledgerAddress;
import org.interledger.InterledgerPacket;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Objects;
/**
* <p>Interledger Payments moves assets of one party to another that consists of one or more ledger
* transfers, potentially across multiple ledgers.</p>
*
* <p>Interledger Payments have three major consumers:</p>
* <ul>
* <li>Connectors utilize the Interledger Address contained in the payment to route the
* payment.</li>
* <li>The receiver of a payment uses it to identify the recipient and which condition to
* fulfill.</li>
* <li>Interledger sub-protocols utilize custom data encoded in a payment to facilitate
* sub-protocol operations.</li>
* </ul>
*
* <p>When a sender prepares a transfer to start a payment, the sender attaches an ILP Payment to
* the transfer, in the memo field if possible. If a ledger does not support attaching the entire
* ILP Payment to a transfer as a memo, users of that ledger can transmit the ILP Payment using
* another authenticated messaging channel, but MUST be able to correlate transfers and ILP
* Payments.</p>
*
* <p>When a connector sees an incoming prepared transfer with an ILP Payment, the receiver reads
* the ILP Payment to confirm the details of the packet. For example, the connector reads the
* InterledgerAddress of the payment's receiver, and if the connector has a route to the receiver's
* account, the connector prepares a transfer to continue the payment, and attaches the same ILP
* Payment to the new transfer. Likewise, the receiver confirms that the amount of the ILP Payment
* Packet matches the amount actually delivered by the transfer. And finally, the receiver decodes
* the data portion of the Payment and matches the condition to the payment.</p>
*
* <p>The receiver MUST confirm the integrity of the ILP Payment, for example with a hash-based
* message authentication code (HMAC). If the receiver finds the transfer acceptable, the receiver
* releases the fulfillment for the transfer, which can be used to execute all prepared transfers
* that were established prior to the receiver accepting the payment.</p>
*/
public interface InterledgerPayment extends InterledgerPacket {
/**
* Get the default builder.
*
* @return a {@link Builder} instance.
*/
static Builder builder() {
return new Builder();
}
/**
* The Interledger address of the account where the receiver should ultimately receive the
* payment.
*
* @return An instance of {@link InterledgerAddress}.
*/
InterledgerAddress getDestinationAccount();
/**
* The amount to deliver, in discrete units of the destination ledger's asset type. The scale of
* the units is determined by the destination ledger's smallest indivisible unit.
*
* @return An instance of {@link BigInteger}.
*/
BigInteger getDestinationAmount();
/**
* Arbitrary data for the receiver that is set by the transport layer of a payment (for example,
* this may contain PSK data).
*
* @return A byte array.
*/
byte[] getData();
/**
* A builder for instances of {@link InterledgerPayment}.
*/
class Builder {
private InterledgerAddress destinationAccount;
private BigInteger destinationAmount;
private byte[] data;
/**
* Set the destination account address into this builder.
*
* @param destinationAccount An instance of {@link InterledgerAddress}.
* @return This {@link Builder} instance.
*/
public Builder destinationAccount(final InterledgerAddress destinationAccount) {
this.destinationAccount = Objects.requireNonNull(destinationAccount);
return this;
}
/**
* Set the destination amount into this builder.
*
* @param destinationAmount An instance of {@link BigInteger}.
*
* @return This {@link Builder} instance.
*/
public Builder destinationAmount(final BigInteger destinationAmount) {
this.destinationAmount = Objects.requireNonNull(destinationAmount);
return this;
}
/**
* Set the data payload for this payment.
*
* @param data An instance of {@link byte[]}. May be empty but may not be null.
* @return This {@link Builder} instance.
*/
public Builder data(final byte[] data) {
this.data = Objects.requireNonNull(data);
return this;
}
/**
* The method that actually constructs a payment.
*
* @return An instance of {@link InterledgerPayment}.
*/
public InterledgerPayment build() {
return new Impl(this);
}
/**
* A private, immutable implementation of {@link InterledgerPayment}.
*/
private static final class Impl implements InterledgerPayment {
private final InterledgerAddress destinationAccount;
private final BigInteger destinationAmount;
private final byte[] data;
/**
* No-args Constructor.
*/
private Impl(final Builder builder) {
Objects.requireNonNull(builder);
this.destinationAccount = Objects.requireNonNull(builder.destinationAccount,
"destinationAccount must not be null!");
this.destinationAmount = Objects.requireNonNull(builder.destinationAmount,
"destinationAmount must not be null!");
this.data = Objects.requireNonNull(builder.data, "data must not be null!");
}
@Override
public InterledgerAddress getDestinationAccount() {
return this.destinationAccount;
}
@Override
public BigInteger getDestinationAmount() {
return this.destinationAmount;
}
@Override
public byte[] getData() {
return Arrays.copyOf(this.data, this.data.length);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Impl impl = (Impl) obj;
return destinationAccount.equals(impl.destinationAccount)
&& destinationAmount.equals(impl.destinationAmount)
&& Arrays.equals(data, impl.data);
}
@Override
public int hashCode() {
int result = destinationAccount.hashCode();
result = 31 * result + destinationAmount.hashCode();
result = 31 * result + Arrays.hashCode(data);
return result;
}
@Override
public String toString() {
return "InterledgerPayment.Impl{"
+ "destinationAccount=" + destinationAccount
+ ", destinationAmount=" + destinationAmount
+ ", data=" + Arrays.toString(data)
+ '}';
}
}
}
}
| {
"content_hash": "73408f216505c7898eaebebdfc92acc9",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 99,
"avg_line_length": 33.915,
"alnum_prop": 0.6777237210673743,
"repo_name": "rizwantanoli/quilt",
"id": "9f88ee121c5274bc5cdf6a2f172ccc3aa9980ba5",
"size": "6783",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ilp-core/src/main/java/org/interledger/ilp/InterledgerPayment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "644189"
},
{
"name": "Kotlin",
"bytes": "113"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<container>
<alias id="alias_1" service="service_1" public="true"/>
<alias id="alias_2" service="service_2" public="false"/>
<definition id="definition_1" class="Full\Qualified\Class1" scope="container" public="true" synthetic="false" lazy="true" shared="true" synchronized="false" abstract="true" autowired="false" file="">
<factory class="Full\Qualified\FactoryClass" method="get"/>
</definition>
<definition id="definition_2" class="Full\Qualified\Class2" scope="container" public="false" synthetic="true" lazy="false" shared="true" synchronized="false" abstract="false" autowired="false" file="/path/to/file">
<factory service="factory.service" method="get"/>
<tags>
<tag name="tag1">
<parameter name="attr1">val1</parameter>
<parameter name="attr2">val2</parameter>
</tag>
<tag name="tag1">
<parameter name="attr3">val3</parameter>
</tag>
<tag name="tag2"/>
</tags>
</definition>
<service id="service_container" class="Symfony\Component\DependencyInjection\ContainerBuilder"/>
</container>
| {
"content_hash": "3e2f25382caffe64dd2a69b842f4fdc3",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 216,
"avg_line_length": 51.81818181818182,
"alnum_prop": 0.6622807017543859,
"repo_name": "Condors/TunisiaMall",
"id": "0dc252d1dadc6dc3fb189ea812a9a41ce7e47f33",
"size": "1140",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "16927"
},
{
"name": "ApacheConf",
"bytes": "3688"
},
{
"name": "Batchfile",
"bytes": "690"
},
{
"name": "CSS",
"bytes": "836798"
},
{
"name": "HTML",
"bytes": "917753"
},
{
"name": "JavaScript",
"bytes": "1079135"
},
{
"name": "PHP",
"bytes": "196744"
},
{
"name": "Shell",
"bytes": "4247"
}
],
"symlink_target": ""
} |
package com.triangleleft.flashcards.di.main;
import com.triangleleft.flashcards.di.ApplicationComponent;
import com.triangleleft.flashcards.di.scope.ActivityScope;
import com.triangleleft.flashcards.ui.main.DrawerPresenter;
import com.triangleleft.flashcards.ui.main.MainActivity;
import com.triangleleft.flashcards.ui.main.MainPageModule;
import com.triangleleft.flashcards.ui.main.MainPresenter;
import com.triangleleft.flashcards.ui.main.drawer.NavigationView;
import com.triangleleft.flashcards.ui.vocabular.VocabularyNavigator;
import dagger.Component;
@ActivityScope
@Component(dependencies = ApplicationComponent.class, modules = MainPageModule.class)
public interface MainPageComponent extends ApplicationComponent {
MainPresenter mainPresenter();
DrawerPresenter drawerPresenter();
VocabularyNavigator vocabularNavigator();
void inject(MainActivity mainView);
void inject(NavigationView navigationView);
}
| {
"content_hash": "5b914f9c0082b64a53cbe0dc07133449",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 85,
"avg_line_length": 34.925925925925924,
"alnum_prop": 0.8356309650053022,
"repo_name": "TriangleLeft/Flashcards",
"id": "51b363549469717caf6eb5acfe2fd1c40d4b64db",
"size": "943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/triangleleft/flashcards/di/main/MainPageComponent.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "335591"
},
{
"name": "Makefile",
"bytes": "5515"
},
{
"name": "Objective-C",
"bytes": "10267"
},
{
"name": "Ruby",
"bytes": "990"
},
{
"name": "Shell",
"bytes": "218"
},
{
"name": "Swift",
"bytes": "61313"
}
],
"symlink_target": ""
} |
<?php declare(strict_types=1);
namespace Monolog\Handler;
use Gelf\Message;
use Monolog\Test\TestCase;
use Monolog\Level;
use Monolog\Formatter\GelfMessageFormatter;
class GelfHandlerTest extends TestCase
{
public function setUp(): void
{
if (!class_exists('Gelf\Publisher') || !class_exists('Gelf\Message')) {
$this->markTestSkipped("graylog2/gelf-php not installed");
}
}
/**
* @covers Monolog\Handler\GelfHandler::__construct
*/
public function testConstruct()
{
$handler = new GelfHandler($this->getMessagePublisher());
$this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler);
}
protected function getHandler($messagePublisher)
{
$handler = new GelfHandler($messagePublisher);
return $handler;
}
protected function getMessagePublisher()
{
return $this->getMockBuilder('Gelf\Publisher')
->onlyMethods(['publish'])
->disableOriginalConstructor()
->getMock();
}
public function testDebug()
{
$record = $this->getRecord(Level::Debug, "A test debug message");
$expectedMessage = new Message();
$expectedMessage
->setLevel(7)
->setAdditional('facility', 'test')
->setShortMessage($record->message)
->setTimestamp($record->datetime)
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->handle($record);
}
public function testWarning()
{
$record = $this->getRecord(Level::Warning, "A test warning message");
$expectedMessage = new Message();
$expectedMessage
->setLevel(4)
->setAdditional('facility', 'test')
->setShortMessage($record->message)
->setTimestamp($record->datetime)
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->handle($record);
}
public function testInjectedGelfMessageFormatter()
{
$record = $this->getRecord(
Level::Warning,
"A test warning message",
extra: ['blarg' => 'yep'],
context: ['from' => 'logger'],
);
$expectedMessage = new Message();
$expectedMessage
->setLevel(4)
->setAdditional('facility', 'test')
->setHost("mysystem")
->setShortMessage($record->message)
->setTimestamp($record->datetime)
->setAdditional("EXTblarg", 'yep')
->setAdditional("CTXfrom", 'logger')
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX'));
$handler->handle($record);
}
}
| {
"content_hash": "9aeca2604a4f1c712d1a95b8fa3f8246",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 83,
"avg_line_length": 28.655172413793103,
"alnum_prop": 0.5764139590854392,
"repo_name": "Seldaek/monolog",
"id": "e96f116608ea282c51ba252fd1666c401ff685ed",
"size": "3551",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/Monolog/Handler/GelfHandlerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "823138"
}
],
"symlink_target": ""
} |
8.12 Logs are stored differently and rotated
============================================
Verify that the logs are stored on a different partition than the application is running with proper log rotation.
Levels: 3
| {
"content_hash": "9131f90bddae1386f79b9802b7c89731",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 114,
"avg_line_length": 31.142857142857142,
"alnum_prop": 0.6376146788990825,
"repo_name": "ibuildingsnl/owasp-aasvs",
"id": "8d0789da2f3ec574df64838e93cf978de53d5b10",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/requirement-8.12.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "4337"
}
],
"symlink_target": ""
} |
FROM balenalib/kitra520-debian:bullseye-build
ENV NODE_VERSION 15.7.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "aa65f287bfe060321ee5e0b4f7134bd17690abb911c6fc1173ddbedddbf2c060 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
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@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.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 Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \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": "a514411ee61262ffd0877f736d83c8fb",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 695,
"avg_line_length": 67.46341463414635,
"alnum_prop": 0.7096890817064353,
"repo_name": "nghiant2710/base-images",
"id": "0b794ba6a7f46e25b02966b92e86beb57128c51d",
"size": "2787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/kitra520/debian/bullseye/15.7.0/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Interactivity;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Avalonia.Controls
{
/// <summary>
/// A control to allow the user to select a date
/// </summary>
[PseudoClasses(":hasnodate")]
public class DatePicker : TemplatedControl
{
/// <summary>
/// Define the <see cref="DayFormat"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, string> DayFormatProperty =
AvaloniaProperty.RegisterDirect<DatePicker, string>(nameof(DayFormat),
x => x.DayFormat, (x, v) => x.DayFormat = v);
/// <summary>
/// Defines the <see cref="DayVisible"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, bool> DayVisibleProperty =
AvaloniaProperty.RegisterDirect<DatePicker, bool>(nameof(DayVisible),
x => x.DayVisible, (x, v) => x.DayVisible = v);
/// <summary>
/// Defines the <see cref="Header"/> Property
/// </summary>
public static readonly StyledProperty<object> HeaderProperty =
AvaloniaProperty.Register<DatePicker, object>(nameof(Header));
/// <summary>
/// Defines the <see cref="HeaderTemplate"/> Property
/// </summary>
public static readonly StyledProperty<IDataTemplate> HeaderTemplateProperty =
AvaloniaProperty.Register<DatePicker, IDataTemplate>(nameof(HeaderTemplate));
/// <summary>
/// Defines the <see cref="MaxYear"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, DateTimeOffset> MaxYearProperty =
AvaloniaProperty.RegisterDirect<DatePicker, DateTimeOffset>(nameof(MaxYear),
x => x.MaxYear, (x, v) => x.MaxYear = v);
/// <summary>
/// Defines the <see cref="MinYear"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, DateTimeOffset> MinYearProperty =
AvaloniaProperty.RegisterDirect<DatePicker, DateTimeOffset>(nameof(MinYear),
x => x.MinYear, (x, v) => x.MinYear = v);
/// <summary>
/// Defines the <see cref="MonthFormat"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, string> MonthFormatProperty =
AvaloniaProperty.RegisterDirect<DatePicker, string>(nameof(MonthFormat),
x => x.MonthFormat, (x, v) => x.MonthFormat = v);
/// <summary>
/// Defines the <see cref="MonthVisible"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, bool> MonthVisibleProperty =
AvaloniaProperty.RegisterDirect<DatePicker, bool>(nameof(MonthVisible),
x => x.MonthVisible, (x, v) => x.MonthVisible = v);
/// <summary>
/// Defiens the <see cref="YearFormat"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, string> YearFormatProperty =
AvaloniaProperty.RegisterDirect<DatePicker, string>(nameof(YearFormat),
x => x.YearFormat, (x, v) => x.YearFormat = v);
/// <summary>
/// Defines the <see cref="YearVisible"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, bool> YearVisibleProperty =
AvaloniaProperty.RegisterDirect<DatePicker, bool>(nameof(YearVisible),
x => x.YearVisible, (x, v) => x.YearVisible = v);
/// <summary>
/// Defines the <see cref="SelectedDate"/> Property
/// </summary>
public static readonly DirectProperty<DatePicker, DateTimeOffset?> SelectedDateProperty =
AvaloniaProperty.RegisterDirect<DatePicker, DateTimeOffset?>(nameof(SelectedDate),
x => x.SelectedDate, (x, v) => x.SelectedDate = v);
// Template Items
private Button _flyoutButton;
private TextBlock _dayText;
private TextBlock _monthText;
private TextBlock _yearText;
private Grid _container;
private Rectangle _spacer1;
private Rectangle _spacer2;
private Popup _popup;
private DatePickerPresenter _presenter;
private bool _areControlsAvailable;
private string _dayFormat = "%d";
private bool _dayVisible = true;
private DateTimeOffset _maxYear;
private DateTimeOffset _minYear;
private string _monthFormat = "MMMM";
private bool _monthVisible = true;
private string _yearFormat = "yyyy";
private bool _yearVisible = true;
private DateTimeOffset? _selectedDate;
public DatePicker()
{
PseudoClasses.Set(":hasnodate", true);
var now = DateTimeOffset.Now;
_minYear = new DateTimeOffset(now.Date.Year - 100, 1, 1, 0, 0, 0, now.Offset);
_maxYear = new DateTimeOffset(now.Date.Year + 100, 12, 31, 0, 0, 0, now.Offset);
}
public string DayFormat
{
get => _dayFormat;
set => SetAndRaise(DayFormatProperty, ref _dayFormat, value);
}
/// <summary>
/// Gets or sets whether the day is visible
/// </summary>
public bool DayVisible
{
get => _dayVisible;
set
{
SetAndRaise(DayVisibleProperty, ref _dayVisible, value);
SetGrid();
}
}
/// <summary>
/// Gets or sets the DatePicker header
/// </summary>
public object Header
{
get => GetValue(HeaderProperty);
set => SetValue(HeaderProperty, value);
}
/// <summary>
/// Gets or sets the header template
/// </summary>
public IDataTemplate HeaderTemplate
{
get => GetValue(HeaderTemplateProperty);
set => SetValue(HeaderTemplateProperty, value);
}
/// <summary>
/// Gets or sets the maximum year for the picker
/// </summary>
public DateTimeOffset MaxYear
{
get => _maxYear;
set
{
if (value < MinYear)
throw new InvalidOperationException("MaxDate cannot be less than MinDate");
SetAndRaise(MaxYearProperty, ref _maxYear, value);
if (SelectedDate.HasValue && SelectedDate.Value > value)
SelectedDate = value;
}
}
/// <summary>
/// Gets or sets the minimum year for the picker
/// </summary>
public DateTimeOffset MinYear
{
get => _minYear;
set
{
if (value > MaxYear)
throw new InvalidOperationException("MinDate cannot be greater than MaxDate");
SetAndRaise(MinYearProperty, ref _minYear, value);
if (SelectedDate.HasValue && SelectedDate.Value < value)
SelectedDate = value;
}
}
/// <summary>
/// Gets or sets the month format
/// </summary>
public string MonthFormat
{
get => _monthFormat;
set => SetAndRaise(MonthFormatProperty, ref _monthFormat, value);
}
/// <summary>
/// Gets or sets whether the month is visible
/// </summary>
public bool MonthVisible
{
get => _monthVisible;
set
{
SetAndRaise(MonthVisibleProperty, ref _monthVisible, value);
SetGrid();
}
}
/// <summary>
/// Gets or sets the year format
/// </summary>
public string YearFormat
{
get => _yearFormat;
set => SetAndRaise(YearFormatProperty, ref _yearFormat, value);
}
/// <summary>
/// Gets or sets whether the year is visible
/// </summary>
public bool YearVisible
{
get => _yearVisible;
set
{
SetAndRaise(YearVisibleProperty, ref _yearVisible, value);
SetGrid();
}
}
/// <summary>
/// Gets or sets the Selected Date for the picker, can be null
/// </summary>
public DateTimeOffset? SelectedDate
{
get => _selectedDate;
set
{
var old = _selectedDate;
SetAndRaise(SelectedDateProperty, ref _selectedDate, value);
SetSelectedDateText();
OnSelectedDateChanged(this, new DatePickerSelectedValueChangedEventArgs(old, value));
}
}
/// <summary>
/// Raised when the <see cref="SelectedDate"/> changes
/// </summary>
public event EventHandler<DatePickerSelectedValueChangedEventArgs> SelectedDateChanged;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_areControlsAvailable = false;
if (_flyoutButton != null)
_flyoutButton.Click -= OnFlyoutButtonClicked;
if (_presenter != null)
{
_presenter.Confirmed -= OnConfirmed;
_presenter.Dismissed -= OnDismissPicker;
}
base.OnApplyTemplate(e);
_flyoutButton = e.NameScope.Find<Button>("FlyoutButton");
_dayText = e.NameScope.Find<TextBlock>("DayText");
_monthText = e.NameScope.Find<TextBlock>("MonthText");
_yearText = e.NameScope.Find<TextBlock>("YearText");
_container = e.NameScope.Find<Grid>("ButtonContentGrid");
_spacer1 = e.NameScope.Find<Rectangle>("FirstSpacer");
_spacer2 = e.NameScope.Find<Rectangle>("SecondSpacer");
_popup = e.NameScope.Find<Popup>("Popup");
_presenter = e.NameScope.Find<DatePickerPresenter>("PickerPresenter");
_areControlsAvailable = true;
SetGrid();
SetSelectedDateText();
if (_flyoutButton != null)
_flyoutButton.Click += OnFlyoutButtonClicked;
if (_presenter != null)
{
_presenter.Confirmed += OnConfirmed;
_presenter.Dismissed += OnDismissPicker;
_presenter[!DatePickerPresenter.MaxYearProperty] = this[!MaxYearProperty];
_presenter[!DatePickerPresenter.MinYearProperty] = this[!MinYearProperty];
_presenter[!DatePickerPresenter.MonthVisibleProperty] = this[!MonthVisibleProperty];
_presenter[!DatePickerPresenter.MonthFormatProperty] = this[!MonthFormatProperty];
_presenter[!DatePickerPresenter.DayVisibleProperty] = this[!DayVisibleProperty];
_presenter[!DatePickerPresenter.DayFormatProperty] = this[!DayFormatProperty];
_presenter[!DatePickerPresenter.YearVisibleProperty] = this[!YearVisibleProperty];
_presenter[!DatePickerPresenter.YearFormatProperty] = this[!YearFormatProperty];
}
}
private void OnDismissPicker(object sender, EventArgs e)
{
_popup.Close();
Focus();
}
private void OnConfirmed(object sender, EventArgs e)
{
_popup.Close();
SelectedDate = _presenter.Date;
}
private void SetGrid()
{
if (_container == null)
return;
var fmt = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
var columns = new List<(TextBlock, int)>
{
(_monthText, MonthVisible ? fmt.IndexOf("m", StringComparison.OrdinalIgnoreCase) : -1),
(_yearText, YearVisible ? fmt.IndexOf("y", StringComparison.OrdinalIgnoreCase) : -1),
(_dayText, DayVisible ? fmt.IndexOf("d", StringComparison.OrdinalIgnoreCase) : -1),
};
columns.Sort((x, y) => x.Item2 - y.Item2);
_container.ColumnDefinitions.Clear();
var columnIndex = 0;
foreach (var column in columns)
{
if (column.Item1 is null)
continue;
column.Item1.IsVisible = column.Item2 != -1;
if (column.Item2 != -1)
{
if (columnIndex > 0)
{
_container.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
}
_container.ColumnDefinitions.Add(
new ColumnDefinition(column.Item1 == _monthText ? 138 : 78, GridUnitType.Star));
if (column.Item1.Parent is null)
{
_container.Children.Add(column.Item1);
}
Grid.SetColumn(column.Item1, (columnIndex++ * 2));
}
}
var isSpacer1Visible = columnIndex > 1;
var isSpacer2Visible = columnIndex > 2;
// ternary conditional operator is used to make sure grid cells will be validated
Grid.SetColumn(_spacer1, isSpacer1Visible ? 1 : 0);
Grid.SetColumn(_spacer2, isSpacer2Visible ? 3 : 0);
_spacer1.IsVisible = isSpacer1Visible;
_spacer2.IsVisible = isSpacer2Visible;
}
private void SetSelectedDateText()
{
if (!_areControlsAvailable)
return;
if (SelectedDate.HasValue)
{
PseudoClasses.Set(":hasnodate", false);
var selDate = SelectedDate.Value;
_monthText.Text = selDate.ToString(MonthFormat);
_yearText.Text = selDate.ToString(YearFormat);
_dayText.Text = selDate.ToString(DayFormat);
}
else
{
PseudoClasses.Set(":hasnodate", true);
_monthText.Text = "month";
_yearText.Text = "year";
_dayText.Text = "day";
}
}
private void OnFlyoutButtonClicked(object sender, RoutedEventArgs e)
{
if (_presenter == null)
throw new InvalidOperationException("No DatePickerPresenter found");
_presenter.Date = SelectedDate ?? DateTimeOffset.Now;
_popup.IsOpen = true;
var deltaY = _presenter.GetOffsetForPopup();
// The extra 5 px I think is related to default popup placement behavior
_popup.Host.ConfigurePosition(_popup.PlacementTarget, PlacementMode.AnchorAndGravity, new Point(0, deltaY + 5),
Primitives.PopupPositioning.PopupAnchor.Bottom, Primitives.PopupPositioning.PopupGravity.Bottom,
Primitives.PopupPositioning.PopupPositionerConstraintAdjustment.SlideY);
}
protected virtual void OnSelectedDateChanged(object sender, DatePickerSelectedValueChangedEventArgs e)
{
SelectedDateChanged?.Invoke(sender, e);
}
}
}
| {
"content_hash": "40e19da7aa278b3696f91d8d66b6dcc9",
"timestamp": "",
"source": "github",
"line_count": 418,
"max_line_length": 123,
"avg_line_length": 36.81818181818182,
"alnum_prop": 0.563417803768681,
"repo_name": "akrisiun/Perspex",
"id": "8d893154eb886e74d26ddf66fc4aecd6398f1a09",
"size": "15392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Avalonia.Controls/DateTimePickers/DatePicker.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "120"
},
{
"name": "C#",
"bytes": "2397160"
},
{
"name": "PowerShell",
"bytes": "4386"
},
{
"name": "Smalltalk",
"bytes": "58936"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationFieldInfo
{
private static readonly ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo> s_fieldToInfoMap =
new ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo>();
private readonly bool _isUnsafe;
private readonly bool _isWithEvents;
private readonly SyntaxNode _initializer;
private CodeGenerationFieldInfo(
bool isUnsafe,
bool isWithEvents,
SyntaxNode initializer)
{
_isUnsafe = isUnsafe;
_isWithEvents = isWithEvents;
_initializer = initializer;
}
public static void Attach(
IFieldSymbol field,
bool isUnsafe,
bool isWithEvents,
SyntaxNode initializer)
{
var info = new CodeGenerationFieldInfo(isUnsafe, isWithEvents, initializer);
s_fieldToInfoMap.Add(field, info);
}
private static CodeGenerationFieldInfo GetInfo(IFieldSymbol field)
{
s_fieldToInfoMap.TryGetValue(field, out var info);
return info;
}
private static bool GetIsUnsafe(CodeGenerationFieldInfo info)
=> info != null && info._isUnsafe;
public static bool GetIsUnsafe(IFieldSymbol field)
=> GetIsUnsafe(GetInfo(field));
private static bool GetIsWithEvents(CodeGenerationFieldInfo info)
=> info != null && info._isWithEvents;
public static bool GetIsWithEvents(IFieldSymbol field)
=> GetIsWithEvents(GetInfo(field));
private static SyntaxNode GetInitializer(CodeGenerationFieldInfo info)
=> info?._initializer;
public static SyntaxNode GetInitializer(IFieldSymbol field)
=> GetInitializer(GetInfo(field));
}
}
| {
"content_hash": "f46b3b1477bb55eb9c08fa3a5de75513",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 110,
"avg_line_length": 34.58064516129032,
"alnum_prop": 0.6539179104477612,
"repo_name": "jmarolf/roslyn",
"id": "6e335b7b069a24164dcc204eec057d42eddb4e9f",
"size": "2146",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "139027042"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "243026"
},
{
"name": "Shell",
"bytes": "92965"
},
{
"name": "Visual Basic .NET",
"bytes": "71729344"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->text('body');
$table->unsignedInteger('commentable_id');//多态关联id
$table->string('commentable_type');//多态关联类型
$table->unsignedInteger('parent_id')->nullable();//嵌套评论中父级评论
$table->smallInteger('level')->default(1);//嵌套层级
$table->string('is_hidden',8)->default('F');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
| {
"content_hash": "6137705805bbd8b8a6adc94b7e48dc5d",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 72,
"avg_line_length": 25.973684210526315,
"alnum_prop": 0.5663627152988855,
"repo_name": "Leocher/col-xs-learning-notes",
"id": "73151970b78effa1c81c01a52747d34b9ae518eb",
"size": "1033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Laravel/zhihuapp/database/migrations/2017_06_19_222739_create_comments_table.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "3448"
},
{
"name": "CSS",
"bytes": "20480"
},
{
"name": "HTML",
"bytes": "153513"
},
{
"name": "JavaScript",
"bytes": "16747"
},
{
"name": "PHP",
"bytes": "590704"
},
{
"name": "Vue",
"bytes": "38836"
}
],
"symlink_target": ""
} |
layout: contributor-profile
credit-name: Amber Bird
first-name: Amber
last-name: Bird
file-as: b
role: Author
role-2:
role-3:
title: Amber Bird — Work in Fireside
description:
twitter-handle:
profile-pic: amber-bird.jpg
website-url:
short-name: amber-bird
permalink: amber-bird
bio-spanish:
---
Amber Bird is a writer, a rockstar, and a science fiction simulacrum. Zie is the author of the hopepunk dystopian science fiction book _Peace Fire_, the front of post-punk/post-glam band Varnish, one half of transatlantic Autistic musical duo The Companions, and an unabashed geek. An Autistic introvert who found that music, books, and gaming saved zir in many ways throughout zir life, zie writes (books, poems, lyrics, blogs) and makes music in hopes of adding to someone else's escape or rescue. And, yes, zie was on that _Magic: The Gathering_ card.
| {
"content_hash": "a8df00e843d4582cd06c40c06ebe856e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 554,
"avg_line_length": 47.22222222222222,
"alnum_prop": 0.7788235294117647,
"repo_name": "firesidefiction/magazine",
"id": "1e4053549fb9f9027ed04c96d7af35e1655fd8a7",
"size": "856",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_contributors/amber-bird.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20043"
},
{
"name": "HTML",
"bytes": "86907"
},
{
"name": "Ruby",
"bytes": "6079"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.yarn.server.resourcemanager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.yarn.MockApps;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AsyncDispatcher;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppMetrics;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AMLivelinessMonitor;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Testing applications being retired from RM.
*
*/
public class TestAppManager{
private Log LOG = LogFactory.getLog(TestAppManager.class);
private static RMAppEventType appEventType = RMAppEventType.KILL;
public synchronized RMAppEventType getAppEventType() {
return appEventType;
}
public synchronized void setAppEventType(RMAppEventType newType) {
appEventType = newType;
}
public static List<RMApp> newRMApps(int n, long time, RMAppState state) {
List<RMApp> list = Lists.newArrayList();
for (int i = 0; i < n; ++i) {
list.add(new MockRMApp(i, time, state));
}
return list;
}
public RMContext mockRMContext(int n, long time) {
final List<RMApp> apps = newRMApps(n, time, RMAppState.FINISHED);
final ConcurrentMap<ApplicationId, RMApp> map = Maps.newConcurrentMap();
for (RMApp app : apps) {
map.put(app.getApplicationId(), app);
}
Dispatcher rmDispatcher = new AsyncDispatcher();
ContainerAllocationExpirer containerAllocationExpirer = new ContainerAllocationExpirer(
rmDispatcher);
AMLivelinessMonitor amLivelinessMonitor = new AMLivelinessMonitor(
rmDispatcher);
AMLivelinessMonitor amFinishingMonitor = new AMLivelinessMonitor(
rmDispatcher);
RMApplicationHistoryWriter writer = mock(RMApplicationHistoryWriter.class);
RMContext context = new RMContextImpl(rmDispatcher,
containerAllocationExpirer, amLivelinessMonitor, amFinishingMonitor,
null, null, null, null, null, writer) {
@Override
public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
return map;
}
};
((RMContextImpl)context).setStateStore(mock(RMStateStore.class));
metricsPublisher = mock(SystemMetricsPublisher.class);
((RMContextImpl)context).setSystemMetricsPublisher(metricsPublisher);
return context;
}
public class TestAppManagerDispatcher implements
EventHandler<RMAppManagerEvent> {
public TestAppManagerDispatcher() {
}
@Override
public void handle(RMAppManagerEvent event) {
// do nothing
}
}
public class TestDispatcher implements
EventHandler<RMAppEvent> {
public TestDispatcher() {
}
@Override
public void handle(RMAppEvent event) {
//RMApp rmApp = this.rmContext.getRMApps().get(appID);
setAppEventType(event.getType());
System.out.println("in handle routine " + getAppEventType().toString());
}
}
// Extend and make the functions we want to test public
public class TestRMAppManager extends RMAppManager {
public TestRMAppManager(RMContext context, Configuration conf) {
super(context, null, null, new ApplicationACLsManager(conf), conf);
}
public TestRMAppManager(RMContext context,
ClientToAMTokenSecretManagerInRM clientToAMSecretManager,
YarnScheduler scheduler, ApplicationMasterService masterService,
ApplicationACLsManager applicationACLsManager, Configuration conf) {
super(context, scheduler, masterService, applicationACLsManager, conf);
}
public void checkAppNumCompletedLimit() {
super.checkAppNumCompletedLimit();
}
public void finishApplication(ApplicationId appId) {
super.finishApplication(appId);
}
public int getCompletedAppsListSize() {
return super.getCompletedAppsListSize();
}
public int getCompletedAppsInStateStore() {
return this.completedAppsInStateStore;
}
public void submitApplication(
ApplicationSubmissionContext submissionContext, String user)
throws YarnException {
super.submitApplication(submissionContext, System.currentTimeMillis(),
user);
}
}
protected void addToCompletedApps(TestRMAppManager appMonitor, RMContext rmContext) {
for (RMApp app : rmContext.getRMApps().values()) {
if (app.getState() == RMAppState.FINISHED
|| app.getState() == RMAppState.KILLED
|| app.getState() == RMAppState.FAILED) {
appMonitor.finishApplication(app.getApplicationId());
}
}
}
private RMContext rmContext;
private SystemMetricsPublisher metricsPublisher;
private TestRMAppManager appMonitor;
private ApplicationSubmissionContext asContext;
private ApplicationId appId;
@SuppressWarnings("deprecation")
@Before
public void setUp() {
long now = System.currentTimeMillis();
rmContext = mockRMContext(1, now - 10);
ResourceScheduler scheduler = mockResourceScheduler();
Configuration conf = new Configuration();
ApplicationMasterService masterService =
new ApplicationMasterService(rmContext, scheduler);
appMonitor = new TestRMAppManager(rmContext,
new ClientToAMTokenSecretManagerInRM(), scheduler, masterService,
new ApplicationACLsManager(conf), conf);
appId = MockApps.newAppID(1);
RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null);
asContext =
recordFactory.newRecordInstance(ApplicationSubmissionContext.class);
asContext.setApplicationId(appId);
asContext.setAMContainerSpec(mockContainerLaunchContext(recordFactory));
asContext.setResource(mockResource());
setupDispatcher(rmContext, conf);
}
@After
public void tearDown() {
setAppEventType(RMAppEventType.KILL);
((Service)rmContext.getDispatcher()).stop();
}
@Test
public void testRMAppRetireNone() throws Exception {
long now = System.currentTimeMillis();
// Create such that none of the applications will retire since
// haven't hit max #
RMContext rmContext = mockRMContext(10, now - 10);
Configuration conf = new YarnConfiguration();
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 10);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext,conf);
Assert.assertEquals("Number of apps incorrect before checkAppTimeLimit",
10, rmContext.getRMApps().size());
// add them to completed apps list
addToCompletedApps(appMonitor, rmContext);
// shouldn't have to many apps
appMonitor.checkAppNumCompletedLimit();
Assert.assertEquals("Number of apps incorrect after # completed check", 10,
rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check", 10,
appMonitor.getCompletedAppsListSize());
verify(rmContext.getStateStore(), never()).removeApplication(
isA(RMApp.class));
}
@Test
public void testRMAppRetireSome() throws Exception {
long now = System.currentTimeMillis();
RMContext rmContext = mockRMContext(10, now - 20000);
Configuration conf = new YarnConfiguration();
conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 3);
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 3);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf);
Assert.assertEquals("Number of apps incorrect before", 10, rmContext
.getRMApps().size());
// add them to completed apps list
addToCompletedApps(appMonitor, rmContext);
// shouldn't have to many apps
appMonitor.checkAppNumCompletedLimit();
Assert.assertEquals("Number of apps incorrect after # completed check", 3,
rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check", 3,
appMonitor.getCompletedAppsListSize());
verify(rmContext.getStateStore(), times(7)).removeApplication(
isA(RMApp.class));
}
@Test
public void testRMAppRetireSomeDifferentStates() throws Exception {
long now = System.currentTimeMillis();
// these parameters don't matter, override applications below
RMContext rmContext = mockRMContext(10, now - 20000);
Configuration conf = new YarnConfiguration();
conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 2);
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 2);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf);
// clear out applications map
rmContext.getRMApps().clear();
Assert.assertEquals("map isn't empty", 0, rmContext.getRMApps().size());
// 6 applications are in final state, 4 are not in final state.
// / set with various finished states
RMApp app = new MockRMApp(0, now - 20000, RMAppState.KILLED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(1, now - 200000, RMAppState.FAILED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(2, now - 30000, RMAppState.FINISHED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(3, now - 20000, RMAppState.RUNNING);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(4, now - 20000, RMAppState.NEW);
rmContext.getRMApps().put(app.getApplicationId(), app);
// make sure it doesn't expire these since still running
app = new MockRMApp(5, now - 10001, RMAppState.KILLED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(6, now - 30000, RMAppState.ACCEPTED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(7, now - 20000, RMAppState.SUBMITTED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(8, now - 10001, RMAppState.FAILED);
rmContext.getRMApps().put(app.getApplicationId(), app);
app = new MockRMApp(9, now - 20000, RMAppState.FAILED);
rmContext.getRMApps().put(app.getApplicationId(), app);
Assert.assertEquals("Number of apps incorrect before", 10, rmContext
.getRMApps().size());
// add them to completed apps list
addToCompletedApps(appMonitor, rmContext);
// shouldn't have to many apps
appMonitor.checkAppNumCompletedLimit();
Assert.assertEquals("Number of apps incorrect after # completed check", 6,
rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check", 2,
appMonitor.getCompletedAppsListSize());
// 6 applications in final state, 4 of them are removed
verify(rmContext.getStateStore(), times(4)).removeApplication(
isA(RMApp.class));
}
@Test
public void testRMAppRetireNullApp() throws Exception {
long now = System.currentTimeMillis();
RMContext rmContext = mockRMContext(10, now - 20000);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, new Configuration());
Assert.assertEquals("Number of apps incorrect before", 10, rmContext
.getRMApps().size());
appMonitor.finishApplication(null);
Assert.assertEquals("Number of completed apps incorrect after check", 0,
appMonitor.getCompletedAppsListSize());
}
@Test
public void testRMAppRetireZeroSetting() throws Exception {
long now = System.currentTimeMillis();
RMContext rmContext = mockRMContext(10, now - 20000);
Configuration conf = new YarnConfiguration();
conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 0);
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 0);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf);
Assert.assertEquals("Number of apps incorrect before", 10, rmContext
.getRMApps().size());
addToCompletedApps(appMonitor, rmContext);
Assert.assertEquals("Number of completed apps incorrect", 10,
appMonitor.getCompletedAppsListSize());
appMonitor.checkAppNumCompletedLimit();
Assert.assertEquals("Number of apps incorrect after # completed check", 0,
rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check", 0,
appMonitor.getCompletedAppsListSize());
verify(rmContext.getStateStore(), times(10)).removeApplication(
isA(RMApp.class));
}
@Test
public void testStateStoreAppLimitLessThanMemoryAppLimit() {
long now = System.currentTimeMillis();
RMContext rmContext = mockRMContext(10, now - 20000);
Configuration conf = new YarnConfiguration();
int maxAppsInMemory = 8;
int maxAppsInStateStore = 4;
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, maxAppsInMemory);
conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS,
maxAppsInStateStore);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf);
addToCompletedApps(appMonitor, rmContext);
Assert.assertEquals("Number of completed apps incorrect", 10,
appMonitor.getCompletedAppsListSize());
appMonitor.checkAppNumCompletedLimit();
Assert.assertEquals("Number of apps incorrect after # completed check",
maxAppsInMemory, rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check",
maxAppsInMemory, appMonitor.getCompletedAppsListSize());
int numRemoveAppsFromStateStore = 10 - maxAppsInStateStore;
verify(rmContext.getStateStore(), times(numRemoveAppsFromStateStore))
.removeApplication(isA(RMApp.class));
Assert.assertEquals(maxAppsInStateStore,
appMonitor.getCompletedAppsInStateStore());
}
@Test
public void testStateStoreAppLimitLargerThanMemoryAppLimit() {
long now = System.currentTimeMillis();
RMContext rmContext = mockRMContext(10, now - 20000);
Configuration conf = new YarnConfiguration();
int maxAppsInMemory = 8;
conf.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, maxAppsInMemory);
// larger than maxCompletedAppsInMemory, reset to RM_MAX_COMPLETED_APPLICATIONS.
conf.setInt(YarnConfiguration.RM_STATE_STORE_MAX_COMPLETED_APPLICATIONS, 1000);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext, conf);
addToCompletedApps(appMonitor, rmContext);
Assert.assertEquals("Number of completed apps incorrect", 10,
appMonitor.getCompletedAppsListSize());
appMonitor.checkAppNumCompletedLimit();
int numRemoveApps = 10 - maxAppsInMemory;
Assert.assertEquals("Number of apps incorrect after # completed check",
maxAppsInMemory, rmContext.getRMApps().size());
Assert.assertEquals("Number of completed apps incorrect after check",
maxAppsInMemory, appMonitor.getCompletedAppsListSize());
verify(rmContext.getStateStore(), times(numRemoveApps)).removeApplication(
isA(RMApp.class));
Assert.assertEquals(maxAppsInMemory,
appMonitor.getCompletedAppsInStateStore());
}
protected void setupDispatcher(RMContext rmContext, Configuration conf) {
TestDispatcher testDispatcher = new TestDispatcher();
TestAppManagerDispatcher testAppManagerDispatcher =
new TestAppManagerDispatcher();
rmContext.getDispatcher().register(RMAppEventType.class, testDispatcher);
rmContext.getDispatcher().register(RMAppManagerEventType.class, testAppManagerDispatcher);
((Service)rmContext.getDispatcher()).init(conf);
((Service)rmContext.getDispatcher()).start();
Assert.assertEquals("app event type is wrong before", RMAppEventType.KILL, appEventType);
}
@Test
public void testRMAppSubmit() throws Exception {
appMonitor.submitApplication(asContext, "test");
RMApp app = rmContext.getRMApps().get(appId);
Assert.assertNotNull("app is null", app);
Assert.assertEquals("app id doesn't match", appId, app.getApplicationId());
Assert.assertEquals("app state doesn't match", RMAppState.NEW, app.getState());
verify(metricsPublisher).appACLsUpdated(
any(RMApp.class), any(String.class), anyLong());
// wait for event to be processed
int timeoutSecs = 0;
while ((getAppEventType() == RMAppEventType.KILL) &&
timeoutSecs++ < 20) {
Thread.sleep(1000);
}
Assert.assertEquals("app event type sent is wrong", RMAppEventType.START,
getAppEventType());
}
@Test (timeout = 30000)
public void testRMAppSubmitMaxAppAttempts() throws Exception {
int[] globalMaxAppAttempts = new int[] { 10, 1 };
int[][] individualMaxAppAttempts = new int[][]{
new int[]{ 9, 10, 11, 0 },
new int[]{ 1, 10, 0, -1 }};
int[][] expectedNums = new int[][]{
new int[]{ 9, 10, 10, 10 },
new int[]{ 1, 1, 1, 1 }};
for (int i = 0; i < globalMaxAppAttempts.length; ++i) {
for (int j = 0; j < individualMaxAppAttempts.length; ++j) {
ResourceScheduler scheduler = mockResourceScheduler();
Configuration conf = new Configuration();
conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, globalMaxAppAttempts[i]);
ApplicationMasterService masterService =
new ApplicationMasterService(rmContext, scheduler);
TestRMAppManager appMonitor = new TestRMAppManager(rmContext,
new ClientToAMTokenSecretManagerInRM(), scheduler, masterService,
new ApplicationACLsManager(conf), conf);
ApplicationId appID = MockApps.newAppID(i * 4 + j + 1);
asContext.setApplicationId(appID);
if (individualMaxAppAttempts[i][j] != 0) {
asContext.setMaxAppAttempts(individualMaxAppAttempts[i][j]);
}
appMonitor.submitApplication(asContext, "test");
RMApp app = rmContext.getRMApps().get(appID);
Assert.assertEquals("max application attempts doesn't match",
expectedNums[i][j], app.getMaxAppAttempts());
// wait for event to be processed
int timeoutSecs = 0;
while ((getAppEventType() == RMAppEventType.KILL) &&
timeoutSecs++ < 20) {
Thread.sleep(1000);
}
setAppEventType(RMAppEventType.KILL);
}
}
}
@Test (timeout = 30000)
public void testRMAppSubmitDuplicateApplicationId() throws Exception {
ApplicationId appId = MockApps.newAppID(0);
asContext.setApplicationId(appId);
RMApp appOrig = rmContext.getRMApps().get(appId);
Assert.assertTrue("app name matches but shouldn't", "testApp1" != appOrig.getName());
// our testApp1 should be rejected and original app with same id should be left in place
try {
appMonitor.submitApplication(asContext, "test");
Assert.fail("Exception is expected when applicationId is duplicate.");
} catch (YarnException e) {
Assert.assertTrue("The thrown exception is not the expectd one.",
e.getMessage().contains("Cannot add a duplicate!"));
}
// make sure original app didn't get removed
RMApp app = rmContext.getRMApps().get(appId);
Assert.assertNotNull("app is null", app);
Assert.assertEquals("app id doesn't match", appId, app.getApplicationId());
Assert.assertEquals("app state doesn't match", RMAppState.FINISHED, app.getState());
}
@SuppressWarnings("deprecation")
@Test (timeout = 30000)
public void testRMAppSubmitInvalidResourceRequest() throws Exception {
asContext.setResource(Resources.createResource(
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB + 1));
// submit an app
try {
appMonitor.submitApplication(asContext, "test");
Assert.fail("Application submission should fail because resource" +
" request is invalid.");
} catch (YarnException e) {
// Exception is expected
// TODO Change this to assert the expected exception type - post YARN-142
// sub-task related to specialized exceptions.
Assert.assertTrue("The thrown exception is not" +
" InvalidResourceRequestException",
e.getMessage().contains("Invalid resource request"));
}
}
@Test (timeout = 30000)
public void testEscapeApplicationSummary() {
RMApp app = mock(RMAppImpl.class);
when(app.getApplicationId()).thenReturn(
ApplicationId.newInstance(100L, 1));
when(app.getName()).thenReturn("Multiline\n\n\r\rAppName");
when(app.getUser()).thenReturn("Multiline\n\n\r\rUserName");
when(app.getQueue()).thenReturn("Multiline\n\n\r\rQueueName");
when(app.getState()).thenReturn(RMAppState.RUNNING);
when(app.getApplicationType()).thenReturn("MAPREDUCE");
RMAppMetrics metrics =
new RMAppMetrics(Resource.newInstance(1234, 56), 10, 1, 16384, 64);
when(app.getRMAppMetrics()).thenReturn(metrics);
RMAppManager.ApplicationSummary.SummaryBuilder summary =
new RMAppManager.ApplicationSummary().createAppSummary(app);
String msg = summary.toString();
LOG.info("summary: " + msg);
Assert.assertFalse(msg.contains("\n"));
Assert.assertFalse(msg.contains("\r"));
String escaped = "\\n\\n\\r\\r";
Assert.assertTrue(msg.contains("Multiline" + escaped +"AppName"));
Assert.assertTrue(msg.contains("Multiline" + escaped +"UserName"));
Assert.assertTrue(msg.contains("Multiline" + escaped +"QueueName"));
Assert.assertTrue(msg.contains("memorySeconds=16384"));
Assert.assertTrue(msg.contains("vcoreSeconds=64"));
Assert.assertTrue(msg.contains("preemptedAMContainers=1"));
Assert.assertTrue(msg.contains("preemptedNonAMContainers=10"));
Assert.assertTrue(msg.contains("preemptedResources=<memory:1234\\, vCores:56>"));
Assert.assertTrue(msg.contains("applicationType=MAPREDUCE"));
}
private static ResourceScheduler mockResourceScheduler() {
ResourceScheduler scheduler = mock(ResourceScheduler.class);
when(scheduler.getMinimumResourceCapability()).thenReturn(
Resources.createResource(
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB));
when(scheduler.getMaximumResourceCapability()).thenReturn(
Resources.createResource(
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB));
return scheduler;
}
private static ContainerLaunchContext mockContainerLaunchContext(
RecordFactory recordFactory) {
ContainerLaunchContext amContainer = recordFactory.newRecordInstance(
ContainerLaunchContext.class);
amContainer.setApplicationACLs(new HashMap<ApplicationAccessType, String>());;
return amContainer;
}
private static Resource mockResource() {
return Resources.createResource(
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB);
}
}
| {
"content_hash": "51f0f795febaf0a2c3f9709365ce6341",
"timestamp": "",
"source": "github",
"line_count": 607,
"max_line_length": 95,
"avg_line_length": 41.15815485996705,
"alnum_prop": 0.7300964655966057,
"repo_name": "Wajihulhassan/Hadoop-2.7.0",
"id": "d2ac4efb9572b24f94c99801628d1e08bcdc063f",
"size": "25789",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestAppManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "31146"
},
{
"name": "Batchfile",
"bytes": "65911"
},
{
"name": "C",
"bytes": "1394654"
},
{
"name": "C++",
"bytes": "88380"
},
{
"name": "CMake",
"bytes": "40065"
},
{
"name": "CSS",
"bytes": "50572"
},
{
"name": "HTML",
"bytes": "412552"
},
{
"name": "Java",
"bytes": "49979252"
},
{
"name": "JavaScript",
"bytes": "26078"
},
{
"name": "Perl",
"bytes": "18992"
},
{
"name": "Protocol Buffer",
"bytes": "234278"
},
{
"name": "Python",
"bytes": "18556"
},
{
"name": "Shell",
"bytes": "188969"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "20949"
}
],
"symlink_target": ""
} |
/* Includes ------------------------------------------------------------------*/
#include "usbd_core.h"
#include "usbd_req.h"
#include "usbd_ioreq.h"
#include "usb_dcd_int.h"
#include "usb_bsp.h"
/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_CORE
* @brief usbd core module
* @{
*/
/** @defgroup USBD_CORE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Private_FunctionPrototypes
* @{
*/
static uint8_t USBD_SetupStage(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_DataOutStage(USB_OTG_CORE_HANDLE *pdev , uint8_t epnum);
static uint8_t USBD_DataInStage(USB_OTG_CORE_HANDLE *pdev , uint8_t epnum);
static uint8_t USBD_SOF(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_Reset(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_Suspend(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_Resume(USB_OTG_CORE_HANDLE *pdev);
#ifdef VBUS_SENSING_ENABLED
static uint8_t USBD_DevConnected(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_DevDisconnected(USB_OTG_CORE_HANDLE *pdev);
#endif
static uint8_t USBD_IsoINIncomplete(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_IsoOUTIncomplete(USB_OTG_CORE_HANDLE *pdev);
static uint8_t USBD_RunTestMode (USB_OTG_CORE_HANDLE *pdev) ;
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Variables
* @{
*/
__IO USB_OTG_DCTL_TypeDef SET_TEST_MODE;
USBD_DCD_INT_cb_TypeDef USBD_DCD_INT_cb =
{
USBD_DataOutStage,
USBD_DataInStage,
USBD_SetupStage,
USBD_SOF,
USBD_Reset,
USBD_Suspend,
USBD_Resume,
USBD_IsoINIncomplete,
USBD_IsoOUTIncomplete,
#ifdef VBUS_SENSING_ENABLED
USBD_DevConnected,
USBD_DevDisconnected,
#endif
};
USBD_DCD_INT_cb_TypeDef *USBD_DCD_INT_fops = &USBD_DCD_INT_cb;
/**
* @}
*/
/** @defgroup USBD_CORE_Private_Functions
* @{
*/
/**
* @brief USBD_Init
* Initailizes the device stack and load the class driver
* @param pdev: device instance
* @param core_address: USB OTG core ID
* @param class_cb: Class callback structure address
* @param usr_cb: User callback structure address
* @retval None
*/
void USBD_Init(USB_OTG_CORE_HANDLE *pdev,
USB_OTG_CORE_ID_TypeDef coreID,
USBD_DEVICE *pDevice,
USBD_Class_cb_TypeDef *class_cb,
USBD_Usr_cb_TypeDef *usr_cb)
{
/* Hardware Init */
pdev->cfg.coreID = coreID;
USB_OTG_BSP_Init(pdev);
USBD_DeInit(pdev);
/*Register class and user callbacks */
pdev->dev.class_cb = class_cb;
pdev->dev.usr_cb = usr_cb;
pdev->dev.usr_device = pDevice;
/* set USB OTG core params */
DCD_Init(pdev , coreID);
/* Upon Init call usr callback */
pdev->dev.usr_cb->Init();
/* Enable Interrupts */
USB_OTG_BSP_EnableInterrupt(pdev);
}
/**
* @brief USBD_DeInit
* Re-Initialize th device library
* @param pdev: device instance
* @retval status: status
*/
USBD_Status USBD_DeInit(USB_OTG_CORE_HANDLE *pdev)
{
/* Software Init */
return USBD_OK;
}
/**
* @brief USBD_SetupStage
* Handle the setup stage
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_SetupStage(USB_OTG_CORE_HANDLE *pdev)
{
USB_SETUP_REQ req;
USBD_ParseSetupRequest(pdev , &req);
switch (req.bmRequest & 0x1F)
{
case USB_REQ_RECIPIENT_DEVICE:
USBD_StdDevReq (pdev, &req);
break;
case USB_REQ_RECIPIENT_INTERFACE:
USBD_StdItfReq(pdev, &req);
break;
case USB_REQ_RECIPIENT_ENDPOINT:
USBD_StdEPReq(pdev, &req);
break;
default:
DCD_EP_Stall(pdev , req.bmRequest & 0x80);
break;
}
return USBD_OK;
}
/**
* @brief USBD_DataOutStage
* Handle data out stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_DataOutStage(USB_OTG_CORE_HANDLE *pdev , uint8_t epnum)
{
USB_OTG_EP *ep;
if(epnum == 0)
{
ep = &pdev->dev.out_ep[0];
if ( pdev->dev.device_state == USB_OTG_EP0_DATA_OUT)
{
if(ep->rem_data_len > ep->maxpacket)
{
ep->rem_data_len -= ep->maxpacket;
if(pdev->cfg.dma_enable == 1)
{
/* in slave mode this, is handled by the RxSTSQLvl ISR */
ep->xfer_buff += ep->maxpacket;
}
USBD_CtlContinueRx (pdev,
ep->xfer_buff,
MIN(ep->rem_data_len ,ep->maxpacket));
}
else
{
if((pdev->dev.class_cb->EP0_RxReady != NULL)&&
(pdev->dev.device_status == USB_OTG_CONFIGURED))
{
pdev->dev.class_cb->EP0_RxReady(pdev);
}
USBD_CtlSendStatus(pdev);
}
}
}
else if((pdev->dev.class_cb->DataOut != NULL)&&
(pdev->dev.device_status == USB_OTG_CONFIGURED))
{
pdev->dev.class_cb->DataOut(pdev, epnum);
}
return USBD_OK;
}
/**
* @brief USBD_DataInStage
* Handle data in stage
* @param pdev: device instance
* @param epnum: endpoint index
* @retval status
*/
static uint8_t USBD_DataInStage(USB_OTG_CORE_HANDLE *pdev , uint8_t epnum)
{
USB_OTG_EP *ep;
if(epnum == 0)
{
ep = &pdev->dev.in_ep[0];
if ( pdev->dev.device_state == USB_OTG_EP0_DATA_IN)
{
if(ep->rem_data_len > ep->maxpacket)
{
ep->rem_data_len -= ep->maxpacket;
if(pdev->cfg.dma_enable == 1)
{
/* in slave mode this, is handled by the TxFifoEmpty ISR */
ep->xfer_buff += ep->maxpacket;
}
USBD_CtlContinueSendData (pdev,
ep->xfer_buff,
ep->rem_data_len);
}
else
{ /* last packet is MPS multiple, so send ZLP packet */
if((ep->total_data_len % ep->maxpacket == 0) &&
(ep->total_data_len >= ep->maxpacket) &&
(ep->total_data_len < ep->ctl_data_len ))
{
USBD_CtlContinueSendData(pdev , NULL, 0);
ep->ctl_data_len = 0;
}
else
{
if((pdev->dev.class_cb->EP0_TxSent != NULL)&&
(pdev->dev.device_status == USB_OTG_CONFIGURED))
{
pdev->dev.class_cb->EP0_TxSent(pdev);
}
USBD_CtlReceiveStatus(pdev);
}
}
}
if (pdev->dev.test_mode == 1)
{
USBD_RunTestMode(pdev);
pdev->dev.test_mode = 0;
}
}
else if((pdev->dev.class_cb->DataIn != NULL)&&
(pdev->dev.device_status == USB_OTG_CONFIGURED))
{
pdev->dev.class_cb->DataIn(pdev, epnum);
}
return USBD_OK;
}
/**
* @brief USBD_RunTestMode
* Launch test mode process
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_RunTestMode (USB_OTG_CORE_HANDLE *pdev)
{
USB_OTG_WRITE_REG32(&pdev->regs.DREGS->DCTL, SET_TEST_MODE.d32);
return USBD_OK;
}
/**
* @brief USBD_Reset
* Handle Reset event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_Reset(USB_OTG_CORE_HANDLE *pdev)
{
/* Open EP0 OUT */
DCD_EP_Open(pdev,
0x00,
USB_OTG_MAX_EP0_SIZE,
EP_TYPE_CTRL);
/* Open EP0 IN */
DCD_EP_Open(pdev,
0x80,
USB_OTG_MAX_EP0_SIZE,
EP_TYPE_CTRL);
/* Upon Reset call usr call back */
pdev->dev.device_status = USB_OTG_DEFAULT;
pdev->dev.usr_cb->DeviceReset(pdev->cfg.speed);
return USBD_OK;
}
/**
* @brief USBD_Resume
* Handle Resume event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_Resume(USB_OTG_CORE_HANDLE *pdev)
{
/* Upon Resume call usr call back */
pdev->dev.usr_cb->DeviceResumed();
pdev->dev.device_status = pdev->dev.device_old_status;
pdev->dev.device_status = USB_OTG_CONFIGURED;
return USBD_OK;
}
/**
* @brief USBD_Suspend
* Handle Suspend event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_Suspend(USB_OTG_CORE_HANDLE *pdev)
{
pdev->dev.device_old_status = pdev->dev.device_status;
pdev->dev.device_status = USB_OTG_SUSPENDED;
/* Upon Resume call usr call back */
pdev->dev.usr_cb->DeviceSuspended();
return USBD_OK;
}
/**
* @brief USBD_SOF
* Handle SOF event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_SOF(USB_OTG_CORE_HANDLE *pdev)
{
if(pdev->dev.class_cb->SOF)
{
pdev->dev.class_cb->SOF(pdev);
}
return USBD_OK;
}
/**
* @brief USBD_SetCfg
* Configure device and start the interface
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status
*/
USBD_Status USBD_SetCfg(USB_OTG_CORE_HANDLE *pdev, uint8_t cfgidx)
{
pdev->dev.class_cb->Init(pdev, cfgidx);
/* Upon set config call usr call back */
pdev->dev.usr_cb->DeviceConfigured();
return USBD_OK;
}
/**
* @brief USBD_ClrCfg
* Clear current configuration
* @param pdev: device instance
* @param cfgidx: configuration index
* @retval status: USBD_Status
*/
USBD_Status USBD_ClrCfg(USB_OTG_CORE_HANDLE *pdev, uint8_t cfgidx)
{
pdev->dev.class_cb->DeInit(pdev, cfgidx);
return USBD_OK;
}
/**
* @brief USBD_IsoINIncomplete
* Handle iso in incomplete event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_IsoINIncomplete(USB_OTG_CORE_HANDLE *pdev)
{
pdev->dev.class_cb->IsoINIncomplete(pdev);
return USBD_OK;
}
/**
* @brief USBD_IsoOUTIncomplete
* Handle iso out incomplete event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_IsoOUTIncomplete(USB_OTG_CORE_HANDLE *pdev)
{
pdev->dev.class_cb->IsoOUTIncomplete(pdev);
return USBD_OK;
}
#ifdef VBUS_SENSING_ENABLED
/**
* @brief USBD_DevConnected
* Handle device connection event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_DevConnected(USB_OTG_CORE_HANDLE *pdev)
{
pdev->dev.usr_cb->DeviceConnected();
pdev->dev.connection_status = 1;
return USBD_OK;
}
/**
* @brief USBD_DevDisconnected
* Handle device disconnection event
* @param pdev: device instance
* @retval status
*/
static uint8_t USBD_DevDisconnected(USB_OTG_CORE_HANDLE *pdev)
{
pdev->dev.usr_cb->DeviceDisconnected();
pdev->dev.class_cb->DeInit(pdev, 0);
pdev->dev.connection_status = 0;
return USBD_OK;
}
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"content_hash": "ed2399269fe60231b714961af442f81d",
"timestamp": "",
"source": "github",
"line_count": 483,
"max_line_length": 80,
"avg_line_length": 21.908902691511386,
"alnum_prop": 0.5986580986580986,
"repo_name": "linuxfans/escX4",
"id": "13f5bcef71d0904613dbf277b8a5f5d877b2c3ba",
"size": "11691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Libraries/STM32_USB_Device_Library/Core/src/usbd_core.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "230885"
},
{
"name": "C",
"bytes": "3441687"
},
{
"name": "C++",
"bytes": "85388"
}
],
"symlink_target": ""
} |
ActiveRecord::Schema.define(version: 20160615090320) do
create_table "options", force: :cascade do |t|
t.integer "poll_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "content"
end
add_index "options", ["id"], name: "index_options_on_id"
create_table "polls", force: :cascade do |t|
t.integer "staff_id", null: false
t.string "content", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "polls", ["id"], name: "index_polls_on_id", unique: true
create_table "staff_polls", force: :cascade do |t|
t.integer "staff_id"
t.integer "poll_id"
t.integer "option_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "staffs", force: :cascade do |t|
t.integer "manager_id", default: 0
t.string "email"
t.string "name"
t.integer "key_person", default: 0
t.string "department"
t.string "division"
t.boolean "actived", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "provider"
t.string "uid"
t.string "oauth_token"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
add_index "staffs", ["id"], name: "index_staffs_on_id", unique: true
end
| {
"content_hash": "e93da771e4d68b34139496170e30f569",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 70,
"avg_line_length": 30.32,
"alnum_prop": 0.5949868073878628,
"repo_name": "tungbt94/ladder-poll",
"id": "17a944a481e4c51ecc0c29f7e9ad8d38d8f1b4ba",
"size": "2257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/schema.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6465"
},
{
"name": "HTML",
"bytes": "14142"
},
{
"name": "JavaScript",
"bytes": "1419"
},
{
"name": "Ruby",
"bytes": "63903"
}
],
"symlink_target": ""
} |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileDiameterEndpointBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence))]
public partial class LocalLBProfileDiameterEndpoint : iControlInterface {
public LocalLBProfileDiameterEndpoint() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_destination_host(
string [] profile_names
) {
object [] results = this.Invoke("get_destination_host", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_destination_host(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_host", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_destination_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_destination_realm(
string [] profile_names
) {
object [] results = this.Invoke("get_destination_realm", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_destination_realm(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_realm", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_destination_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_fatal_grace_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_fatal_grace_time(
string [] profile_names
) {
object [] results = this.Invoke("get_fatal_grace_time", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_fatal_grace_time(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_fatal_grace_time", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_fatal_grace_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_fatal_grace_time_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_fatal_grace_time_state(
string [] profile_names
) {
object [] results = this.Invoke("get_fatal_grace_time_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_fatal_grace_time_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_fatal_grace_time_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_fatal_grace_time_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_retransmit_attempts
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_retransmit_attempts(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_retransmit_attempts", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_retransmit_attempts(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_retransmit_attempts", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_retransmit_attempts(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_host(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_host", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_host(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_host", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_origin_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_origin_realm(
string [] profile_names
) {
object [] results = this.Invoke("get_origin_realm", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_origin_realm(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_origin_realm", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_origin_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_product_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_product_name(
string [] profile_names
) {
object [] results = this.Invoke("get_product_name", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_product_name(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_product_name", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_product_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_retransmit_delay
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_retransmit_delay(
string [] profile_names
) {
object [] results = this.Invoke("get_retransmit_delay", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_retransmit_delay(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_retransmit_delay", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_retransmit_delay(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics get_statistics(
string [] profile_names
) {
object [] results = this.Invoke("get_statistics", new object [] {
profile_names});
return ((LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
object [] results = this.Invoke("get_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
//-----------------------------------------------------------------------
// get_supported_application_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [] get_supported_application_type(
string [] profile_names
) {
object [] results = this.Invoke("get_supported_application_type", new object [] {
profile_names});
return ((LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [])(results[0]));
}
public System.IAsyncResult Beginget_supported_application_type(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_supported_application_type", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [] Endget_supported_application_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// replace_supported_application_types
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void replace_supported_application_types(
string [] profile_names,
LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [] types
) {
this.Invoke("replace_supported_application_types", new object [] {
profile_names,
types});
}
public System.IAsyncResult Beginreplace_supported_application_types(string [] profile_names,LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("replace_supported_application_types", new object[] {
profile_names,
types}, callback, asyncState);
}
public void Endreplace_supported_application_types(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void reset_statistics(
string [] profile_names
) {
this.Invoke("reset_statistics", new object [] {
profile_names});
}
public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
profile_names}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void reset_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
this.Invoke("reset_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
}
public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_destination_host(
string [] profile_names,
LocalLBProfileString [] hosts
) {
this.Invoke("set_destination_host", new object [] {
profile_names,
hosts});
}
public System.IAsyncResult Beginset_destination_host(string [] profile_names,LocalLBProfileString [] hosts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_host", new object[] {
profile_names,
hosts}, callback, asyncState);
}
public void Endset_destination_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_destination_realm(
string [] profile_names,
LocalLBProfileString [] realms
) {
this.Invoke("set_destination_realm", new object [] {
profile_names,
realms});
}
public System.IAsyncResult Beginset_destination_realm(string [] profile_names,LocalLBProfileString [] realms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_realm", new object[] {
profile_names,
realms}, callback, asyncState);
}
public void Endset_destination_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_fatal_grace_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_fatal_grace_time(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_fatal_grace_time", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_fatal_grace_time(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_fatal_grace_time", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_fatal_grace_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_fatal_grace_time_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_fatal_grace_time_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_fatal_grace_time_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_fatal_grace_time_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_fatal_grace_time_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_fatal_grace_time_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_retransmit_attempts
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_maximum_retransmit_attempts(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_maximum_retransmit_attempts", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_maximum_retransmit_attempts(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_retransmit_attempts", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_maximum_retransmit_attempts(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_host
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_origin_host(
string [] profile_names,
LocalLBProfileString [] hosts
) {
this.Invoke("set_origin_host", new object [] {
profile_names,
hosts});
}
public System.IAsyncResult Beginset_origin_host(string [] profile_names,LocalLBProfileString [] hosts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_host", new object[] {
profile_names,
hosts}, callback, asyncState);
}
public void Endset_origin_host(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_origin_realm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_origin_realm(
string [] profile_names,
LocalLBProfileString [] realms
) {
this.Invoke("set_origin_realm", new object [] {
profile_names,
realms});
}
public System.IAsyncResult Beginset_origin_realm(string [] profile_names,LocalLBProfileString [] realms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_origin_realm", new object[] {
profile_names,
realms}, callback, asyncState);
}
public void Endset_origin_realm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_product_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_product_name(
string [] profile_names,
LocalLBProfileString [] products
) {
this.Invoke("set_product_name", new object [] {
profile_names,
products});
}
public System.IAsyncResult Beginset_product_name(string [] profile_names,LocalLBProfileString [] products, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_product_name", new object[] {
profile_names,
products}, callback, asyncState);
}
public void Endset_product_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_retransmit_delay
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileDiameterEndpoint",
RequestNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint", ResponseNamespace="urn:iControl:LocalLB/ProfileDiameterEndpoint")]
public void set_retransmit_delay(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_retransmit_delay", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_retransmit_delay(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_retransmit_delay", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_retransmit_delay(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterEndpoint.DiameterApplicationType", Namespace = "urn:iControl")]
public enum LocalLBProfileDiameterEndpointDiameterApplicationType
{
DIAMETER_APPLICATION_TYPE_UNKNOWN,
DIAMETER_APPLICATION_TYPE_GX,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterEndpoint.DiameterEndpointProfileStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterEndpointDiameterEndpointProfileStatisticEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterEndpoint.DiameterEndpointProfileStatistics", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterEndpointDiameterEndpointProfileStatistics
{
private LocalLBProfileDiameterEndpointDiameterEndpointProfileStatisticEntry [] statisticsField;
public LocalLBProfileDiameterEndpointDiameterEndpointProfileStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileDiameterEndpoint.ProfileDiameterApplicationTypeSequence", Namespace = "urn:iControl")]
public partial class LocalLBProfileDiameterEndpointProfileDiameterApplicationTypeSequence
{
private LocalLBProfileDiameterEndpointDiameterApplicationType [] valueField;
public LocalLBProfileDiameterEndpointDiameterApplicationType [] value
{
get { return this.valueField; }
set { this.valueField = value; }
}
private bool default_flagField;
public bool default_flag
{
get { return this.default_flagField; }
set { this.default_flagField = value; }
}
};
}
| {
"content_hash": "b95f3ad81d1bf8f6e2a7afc18bc3487f",
"timestamp": "",
"source": "github",
"line_count": 849,
"max_line_length": 223,
"avg_line_length": 48.111896348645466,
"alnum_prop": 0.6712365657208608,
"repo_name": "F5Networks/f5-icontrol-library-dotnet",
"id": "fa3906e66931e5b438dd74c04f49010af00d93f6",
"size": "40847",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iControl/Interfaces/LocalLB/LocalLBProfileDiameterEndpoint.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "16922"
},
{
"name": "C#",
"bytes": "10827739"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="alexclin.httplite.MainActivity" >
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
| {
"content_hash": "52ae4526ad81a286e7c4cc7af164a0f3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 64,
"avg_line_length": 44.333333333333336,
"alnum_prop": 0.6892230576441103,
"repo_name": "alexclin0188/httplite",
"id": "a8171c7c4ee0116ca618651c23079bf08b8cbb54",
"size": "399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/menu/menu_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "412776"
}
],
"symlink_target": ""
} |
"use strict";
require('../configure');
const opsgenie = require('../../');
let identifier = {
identifier: "686db572-d4de-4950-90d3-1a43e8969b29", // should be custom to your created incident
identifierType: "id"
};
let body = {
note: "testing note",
};
opsgenie.incident.addNote(identifier, body, function (error, incident) {
if (error) {
console.error(error);
} else {
console.log("Add Incident Note Response");
console.log(incident);
}
}); | {
"content_hash": "825576fa85ac4e07027937562cf596b8",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 100,
"avg_line_length": 22.40909090909091,
"alnum_prop": 0.6288032454361054,
"repo_name": "opsgenie/opsgenie-nodejs-sdk",
"id": "cd3f86a3739de44890e41c87a837979fda628131",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/incident/addNotes.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "44171"
}
],
"symlink_target": ""
} |
package io.bootique.command;
import java.util.Objects;
/**
* A wrapper around the command instance that provides contextual attributes for that command within Bootique.
*
* @since 0.25
*/
public class ManagedCommand {
private boolean hidden;
private boolean _default;
private boolean help;
private Command command;
protected ManagedCommand() {
}
public static Builder builder(Command command) {
return new Builder(command);
}
public static ManagedCommand forCommand(Command command) {
return builder(command).build();
}
public Command getCommand() {
return command;
}
public boolean isHidden() {
return hidden;
}
public boolean isDefault() {
return _default;
}
public boolean isHelp() {
return help;
}
public static class Builder {
private ManagedCommand managedCommand;
public Builder(Command command) {
managedCommand = new ManagedCommand();
managedCommand.command = Objects.requireNonNull(command);
managedCommand.hidden = command.getMetadata().isHidden();
}
public Builder asDefault() {
managedCommand._default = true;
return this;
}
public Builder asHidden() {
managedCommand.hidden = true;
return this;
}
public Builder asHelp() {
managedCommand.help = true;
return this;
}
public ManagedCommand build() {
return managedCommand;
}
}
}
| {
"content_hash": "d47df87cbb6f1eeb3706538658167bda",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 110,
"avg_line_length": 21.06578947368421,
"alnum_prop": 0.6021236727045597,
"repo_name": "ebondareva/bootique",
"id": "1d28c76a42bd4297d9ab334e7ff0814e200b1594",
"size": "2399",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bootique/src/main/java/io/bootique/command/ManagedCommand.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "643016"
}
],
"symlink_target": ""
} |
package net.sf.mmm.util.lang.api.attribute;
/**
* This interface gives read and write access to the {@link #isDisposed() disposed} attribute of an object. It is
* extended or implemented by objects that can be {@link #dispose() disposed}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 3.0.0
*/
public interface AttributeWriteDisposed extends AttributeReadDisposed {
/**
* This method disposes this object. The resources of the object are deallocated and the object can not be used or
* displayed anymore. If this is an object of the UI (user interface) it will be detached.
*/
void dispose();
}
| {
"content_hash": "1cb9c76579d893d8ec105748ee00a5a5",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 116,
"avg_line_length": 33.94736842105263,
"alnum_prop": 0.7302325581395349,
"repo_name": "m-m-m/util",
"id": "174561b16a09f9ce585fcd94d3483dd86e3a61f6",
"size": "773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lang/src/main/java/net/sf/mmm/util/lang/api/attribute/AttributeWriteDisposed.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "116"
},
{
"name": "HTML",
"bytes": "57"
},
{
"name": "Java",
"bytes": "4988376"
}
],
"symlink_target": ""
} |
package org.teavm.metaprogramming.impl;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.teavm.dependency.AbstractDependencyListener;
import org.teavm.dependency.DependencyAgent;
import org.teavm.dependency.MethodDependency;
import org.teavm.dependency.MethodDependencyInfo;
import org.teavm.metaprogramming.impl.model.MethodDescriber;
import org.teavm.metaprogramming.impl.model.MethodModel;
import org.teavm.metaprogramming.impl.optimization.Optimizations;
import org.teavm.metaprogramming.impl.reflect.ReflectContext;
import org.teavm.model.CallLocation;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
import org.teavm.model.emit.ProgramEmitter;
import org.teavm.model.emit.StringChooseEmitter;
import org.teavm.model.emit.ValueEmitter;
public class MetaprogrammingDependencyListener extends AbstractDependencyListener {
private MethodDescriber describer;
private Set<MethodModel> installedProxies = new HashSet<>();
private MetaprogrammingClassLoader proxyClassLoader;
@Override
public void started(DependencyAgent agent) {
proxyClassLoader = new MetaprogrammingClassLoader(agent.getClassLoader());
describer = new MethodDescriber(agent.getDiagnostics(), agent.getClassSource());
MetaprogrammingImpl.classLoader = proxyClassLoader;
MetaprogrammingImpl.classSource = agent.getClassSource();
MetaprogrammingImpl.agent = agent;
MetaprogrammingImpl.reflectContext = new ReflectContext(agent.getClassSource(), proxyClassLoader);
}
@Override
public void methodReached(DependencyAgent agent, MethodDependency methodDep, CallLocation location) {
MethodModel proxy = describer.getMethod(methodDep.getReference());
if (proxy != null && installedProxies.add(proxy)) {
new UsageGenerator(agent, proxy, methodDep, location, proxyClassLoader).installProxyEmitter();
}
}
@Override
public void completing(DependencyAgent agent) {
for (MethodModel model : describer.getKnownMethods()) {
ProgramEmitter pe = ProgramEmitter.create(model.getMethod().getDescriptor(), agent.getClassSource());
ValueEmitter[] paramVars = new ValueEmitter[model.getMetaParameterCount()];
int offset = model.isStatic() ? 1 : 0;
for (int i = 0; i < paramVars.length; ++i) {
paramVars[i] = pe.var(i + offset, model.getMetaParameterType(i));
}
if (model.getUsages().size() == 1) {
emitSingleUsage(model, pe, agent, paramVars);
} else if (model.getUsages().isEmpty()) {
if (model.getMethod().getReturnType() == ValueType.VOID) {
pe.exit();
} else {
pe.constantNull(Object.class).returnValue();
}
} else {
emitMultipleUsage(model, pe, agent, paramVars);
}
}
}
private void emitSingleUsage(MethodModel model, ProgramEmitter pe, DependencyAgent agent,
ValueEmitter[] paramVars) {
MethodReference usage = model.getUsages().values().stream().findFirst().orElse(null);
ValueEmitter result = pe.invoke(usage, paramVars);
if (usage.getReturnType() == ValueType.VOID) {
pe.exit();
} else {
assert result != null : "Expected non-null result at " + model.getMethod();
result.returnValue();
}
agent.submitMethod(model.getMethod(), new Optimizations().apply(pe.getProgram(), model.getMethod()));
}
private void emitMultipleUsage(MethodModel model, ProgramEmitter pe, DependencyAgent agent,
ValueEmitter[] paramVars) {
MethodDependencyInfo methodDep = agent.getMethod(model.getMethod());
ValueEmitter paramVar = paramVars[model.getMetaClassParameterIndex()];
ValueEmitter tag = paramVar.invokeVirtual("getName", String.class);
StringChooseEmitter choice = pe.stringChoice(tag);
for (Map.Entry<ValueType, MethodReference> usageEntry : model.getUsages().entrySet()) {
ValueType type = usageEntry.getKey();
String typeName = type instanceof ValueType.Object
? ((ValueType.Object) type).getClassName()
: type.toString().replace('/', '.');
choice.option(typeName, () -> {
MethodReference implMethod = usageEntry.getValue();
ValueEmitter[] castParamVars = new ValueEmitter[paramVars.length];
for (int i = 0; i < castParamVars.length; ++i) {
castParamVars[i] = paramVars[i].cast(implMethod.parameterType(i));
}
ValueEmitter result = pe.invoke(implMethod, castParamVars);
if (implMethod.getReturnType() == ValueType.VOID) {
pe.exit();
} else {
assert result != null : "Expected non-null result at " + model.getMethod();
result.returnValue();
}
});
}
choice.otherwise(() -> {
if (methodDep.getReference().getReturnType() == ValueType.VOID) {
pe.exit();
} else {
pe.constantNull(Object.class).returnValue();
}
});
agent.submitMethod(model.getMethod(), new Optimizations().apply(pe.getProgram(), model.getMethod()));
}
}
| {
"content_hash": "aa2bd12e835670991ace65d563d124bd",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 113,
"avg_line_length": 44.5609756097561,
"alnum_prop": 0.6445904032110928,
"repo_name": "jtulach/teavm",
"id": "359a305d65f2a5ade71f8bbcbe8df1d2b406eed2",
"size": "6090",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "metaprogramming/impl/src/main/java/org/teavm/metaprogramming/impl/MetaprogrammingDependencyListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1533"
},
{
"name": "HTML",
"bytes": "990"
},
{
"name": "Java",
"bytes": "6763529"
},
{
"name": "JavaScript",
"bytes": "33156"
},
{
"name": "Shell",
"bytes": "1158"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="no-js" lang="">
<head>
<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
<meta name="description" content="">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>
</head>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>
<div class="content">
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>
<div class="main">
<div class="location">
<p class="breadcrumbs">Essays > A New Friend</p>
<p class="expandcollapse">
<a href="">Expand All</a> | <a href="">Collapse All</a>
</p>
</div>
<!-- begin essay -->
<h1>A New Friend</h1>
<p>Benjamin's sister apologized to Sandra and scolded Benjamin saying, "Benjamin, apologize! Why did you do that?" Benjamin replied yelling, "Because she killed my men and stepped on castle!" Sandra then noticed she was standing right on his toy soldiers. Sandra then apologized and Benjamin's sister began to laugh at her and said, "Don't worry about it! I'm Jessica. What's your name?" The two began talking. It was the beginning of a new friendship.</p>
<!-- end essay -->
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>
</body>
</html> | {
"content_hash": "7a8afec531f8cee149d767d331c97958",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 460,
"avg_line_length": 47.758620689655174,
"alnum_prop": 0.6534296028880866,
"repo_name": "javanigus/zabuun",
"id": "3e4e9e41f2a0855048027fd9c4321e9af6e3e6cf",
"size": "1385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "essay/2277-a-new-friend.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11368"
},
{
"name": "HTML",
"bytes": "1272"
},
{
"name": "Hack",
"bytes": "352702"
},
{
"name": "JavaScript",
"bytes": "5518"
},
{
"name": "PHP",
"bytes": "6886277"
}
],
"symlink_target": ""
} |
module.exports = function(sails) {
/**
* Module dependencies.
*/
var async = require('async'),
util = require('sails-util'),
Err = require('../../../errors');
/**
* Expose `policies` hook definition
*/
var policyHookDef = {
defaults: {
// Default policy mappings (allow all)
policies: { '*': true }
},
// Don't allow sails to lift until ready
// is explicitly set below
ready: false,
/**
* Initialize is fired first thing when the hook is loaded
*
* @api public
*/
initialize: function(cb) {
// Callback is optional
cb = util.optional(cb);
var self = this;
// Grab policies config & policy modules and trigger callback
this.loadMiddleware( function (err) {
if (err) return cb(err);
// Build / normalize policy config
self.mapping = self.buildPolicyMap();
sails.log.verbose('Finished loading policy middleware logic.');
cb();
});
// Before routing, curry controller functions with appropriate policy chains
sails.on('router:before', this.bindPolicies);
},
/**
* Wipe everything and (re)load middleware from policies
* (policies.js config is already loaded at this point)
*
* @api private
*/
loadMiddleware: function(cb) {
var self = this;
// Load policy modules
sails.log.verbose('Loading policy modules from app...');
sails.modules.loadPolicies(function modulesLoaded (err, modules) {
if (err) return cb(err);
// Register policies in `self.middleware`
util.extend(self.middleware, modules);
return cb();
});
},
/**
* Curry the policy chains into the appropriate controller functions
*
* @api private
*/
bindPolicies: function() {
// sails.log.verbose('Binding policies :: \n', this.mapping,
// '\nto controllers :: \n', sails.middleware.controllers);
// Policies can be bound to:
// -> controllers
_bindPolicies(this.mapping, sails.middleware.controllers);
// NOTE:
// In the past, policies for views were bound here.
//
// Emit event to let other hooks know we're ready to go
sails.log.verbose('Policy-controller bindings complete!');
sails.emit('hook:policies:bound');
},
/**
* Build normalized, hook-internal representation of policy mapping
* by performing a non-destructive parse of `sails.config.policies`
*
* @returns {Object} mapping
* @api private
*/
buildPolicyMap: function () {
var mapping = {};
util.each(sails.config.policies, function (_policy, controllerId) {
// Accept `FooController` or `foo`
// Case-insensitive
controllerId = util.normalizeControllerId(controllerId);
// Controller-level policy ::
// Just map the policy to the controller directly
if ( ! util.isDictionary(_policy) ) {
mapping[controllerId] = this.normalizePolicy(_policy);
return;
}
// Policy mapping contains a sub-object ::
// So we need to dive in and build/normalize the policy mapping from here
// Mapping each policy to each action for this controller
mapping[controllerId] = {};
util.each( _policy, function (__policy, actionId) {
// Case-insensitive
actionId = actionId.toLowerCase();
mapping[controllerId][actionId] = this.normalizePolicy(__policy);
}, this);
}, this);
return mapping;
},
/**
* Convert a single policy into shallow array notation
* (look up string policies using middleware in this hook)
*
* @param {Array|String|Function|Boolean} policy
* @api private
*/
normalizePolicy: function (policy) {
// Recursively normalize lists of policies
if ( util.isArray(policy) ) {
var policyChain = util.clone(policy);
// Normalize each policy in the chain
policyChain = util.map(policyChain, function normalize_each_policy (policy) {
return policyHookDef.normalizePolicy(policy);
}, this);
// Then flatten the policy chain
return util.flatten(policyChain);
}
// Look up the policy in the policy registry
if ( util.isString(policy) ) {
var policyFn = this.lookupFn(policy, 'config.policies');
// Set the "policy" key on the policy function to the policy name, for debugging
policyFn._middlewareType = 'POLICY: '+policy;
return [policyFn];
}
// An explicitly defined, anonymous policy middleware can be directly attached
if ( util.isFunction(policy) ) {
var anonymousPolicy = util.clone(policy);
// Set the "policy" key on the function name (if any) for debugging
anonymousPolicy._middlewareType = 'POLICY: '+(anonymousPolicy.name || 'anonymous');
return [anonymousPolicy];
}
// A false or null policy means NEVER allow any requests
if (policy === false || policy === null) {
var neverAllow = function neverAllow (req, res, next) {
res.send(403);
};
neverAllow._middlewareType = 'POLICY: neverAllow';
return [neverAllow];
}
// A true policy means ALWAYS allow requests
if (policy === true) {
var alwaysAllow = function alwaysAllow (req, res, next) {
next();
};
alwaysAllow._middlewareType = 'POLICY: alwaysAllow';
return [alwaysAllow];
}
// If we made it here, the policy is invalid
sails.log.error('Cannot map invalid policy: ', policy);
return [function(req, res) {
throw new Error('Invalid policy: ' + policy);
}];
},
/**
* Bind a route directly to a policy
*/
bindDirectlyToRoute: function (event) {
// Only pay attention to delegated route events
// if `policy` is declared in event.target
if ( !event.target || !event.target.policy ) {
return;
}
// Bind policy function to route
var fn = this.lookupFn(event.target.policy, 'config.routes');
sails.router.bind(event.path, fn, event.verb);
},
/**
* @param {String} policyId
* @param {String} referencedIn [optional]
* - where the policy identity is being referenced, for providing better error msg
* @returns {Function} the appropriate policy middleware
*/
lookupFn: function (policyId, referencedIn) {
// Case-insensitive
policyId = policyId.toLowerCase();
// Policy doesn't exist
if ( !this.middleware[policyId] ) {
return Err.fatal.__UnknownPolicy__ (policyId, referencedIn, sails.config.paths.policies);
}
// Policy found
return this.middleware[policyId];
}
};
/**
* Bind routes for manually-mapped policies from `config/routes.js`
*/
sails.on('route:typeUnknown', function (ev) {
policyHookDef.bindDirectlyToRoute(ev);
});
return policyHookDef;
/**
* Bind a set of policies to a set of controllers
* (prepend policy chains to original middleware)
*/
function _bindPolicies ( mapping, middlewareSet ) {
util.each(middlewareSet, function (_c, id) {
var topLevelPolicyId = mapping[id];
var actions, actionFn;
var controller = middlewareSet[id];
// If a policy doesn't exist for this controller, use '*'
if ( util.isUndefined(topLevelPolicyId) ) {
topLevelPolicyId = mapping['*'];
}
// sails.log.verbose('Applying policy :: ', topLevelPolicyId, ' to ', id);
// Build list of actions
if ( util.isDictionary(controller) ) {
actions = util.functions(controller);
}
// If this is a controller policy, apply it immediately
if ( !util.isDictionary(topLevelPolicyId) ) {
// :: Controller is a container object
// -> apply the policy to all the actions
if ( util.isDictionary(controller) ) {
// sails.log.verbose('Applying policy (' + topLevelPolicyId + ') to controller\'s (' + id + ') actions...');
util.each(actions, function(actionId) {
actionFn = controller[actionId];
controller[actionId] = topLevelPolicyId.concat([actionFn]);
// sails.log.verbose('Applying policy to ' + id + '.' + actionId + '...', controller[actionId]);
}, this);
return;
}
// :: Controller is a function
// -> apply the policy directly
// sails.log.verbose('Applying policy (' + topLevelPolicyId + ') to top-level controller middleware fn (' + id + ')...');
middlewareSet[id] = topLevelPolicyId.concat(controller);
}
// If this is NOT a top-level policy, and merely a container of other policies,
// iterate through each of this controller's actions and apply policies in a way that makes sense
else {
util.each(actions, function(actionId) {
var actionPolicy = mapping[id][actionId];
// sails.log.verbose('Mapping policies to actions.... ', actions);
// If a policy doesn't exist for this controller/action, use the controller-local '*'
if ( util.isUndefined(actionPolicy) ) {
actionPolicy = mapping[id]['*'];
}
// if THAT doesn't exist, use the global '*' policy
if ( util.isUndefined(actionPolicy) ) {
actionPolicy = mapping['*'];
}
// sails.log.verbose('Applying policy (' + actionPolicy + ') to action (' + id + '.' + actionId + ')...');
actionFn = controller[actionId];
controller[actionId] = actionPolicy.concat([actionFn]);
}, this);
}
});
}
};
| {
"content_hash": "0606e3c51a474079f339066e6dc04ab7",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 125,
"avg_line_length": 26.759530791788855,
"alnum_prop": 0.647013698630137,
"repo_name": "harindaka/node-mvc-starter",
"id": "9eb3f081c732254426c12d186651f90fa6c19f71",
"size": "9125",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "node_modules/sails/lib/hooks/policies/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "874"
},
{
"name": "JavaScript",
"bytes": "96966"
},
{
"name": "Shell",
"bytes": "110"
}
],
"symlink_target": ""
} |
/* Derived from Lucene.Net.Util.PriorityQueue of March 2005 */
using System;
using Lucene.Net.Support;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Scorer = Lucene.Net.Search.Scorer;
namespace Lucene.Net.Util
{
/// <summary>A ScorerDocQueue maintains a partial ordering of its Scorers such that the
/// least Scorer can always be found in constant time. Put()'s and pop()'s
/// require log(size) time. The ordering is by Scorer.doc().
/// </summary>
public class ScorerDocQueue
{
// later: SpansQueue for spans with doc and term positions
private HeapedScorerDoc[] heap;
private int maxSize;
private int size;
private class HeapedScorerDoc
{
private void InitBlock(ScorerDocQueue enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ScorerDocQueue enclosingInstance;
public ScorerDocQueue Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Scorer scorer;
internal int doc;
internal HeapedScorerDoc(ScorerDocQueue enclosingInstance, Scorer s):this(enclosingInstance, s, s.DocID())
{
}
internal HeapedScorerDoc(ScorerDocQueue enclosingInstance, Scorer scorer, int doc)
{
InitBlock(enclosingInstance);
this.scorer = scorer;
this.doc = doc;
}
internal virtual void Adjust()
{
doc = scorer.DocID();
}
}
private HeapedScorerDoc topHSD; // same as heap[1], only for speed
/// <summary>Create a ScorerDocQueue with a maximum size. </summary>
public ScorerDocQueue(int maxSize)
{
// assert maxSize >= 0;
size = 0;
int heapSize = maxSize + 1;
heap = new HeapedScorerDoc[heapSize];
this.maxSize = maxSize;
topHSD = heap[1]; // initially null
}
/// <summary> Adds a Scorer to a ScorerDocQueue in log(size) time.
/// If one tries to add more Scorers than maxSize
/// a RuntimeException (ArrayIndexOutOfBound) is thrown.
/// </summary>
public void Put(Scorer scorer)
{
size++;
heap[size] = new HeapedScorerDoc(this, scorer);
UpHeap();
}
/// <summary> Adds a Scorer to the ScorerDocQueue in log(size) time if either
/// the ScorerDocQueue is not full, or not lessThan(scorer, top()).
/// </summary>
/// <param name="scorer">
/// </param>
/// <returns> true if scorer is added, false otherwise.
/// </returns>
public virtual bool Insert(Scorer scorer)
{
if (size < maxSize)
{
Put(scorer);
return true;
}
else
{
int docNr = scorer.DocID();
if ((size > 0) && (!(docNr < topHSD.doc)))
{
// heap[1] is top()
heap[1] = new HeapedScorerDoc(this, scorer, docNr);
DownHeap();
return true;
}
else
{
return false;
}
}
}
/// <summary>Returns the least Scorer of the ScorerDocQueue in constant time.
/// Should not be used when the queue is empty.
/// </summary>
public Scorer Top()
{
// assert size > 0;
return topHSD.scorer;
}
/// <summary>Returns document number of the least Scorer of the ScorerDocQueue
/// in constant time.
/// Should not be used when the queue is empty.
/// </summary>
public int TopDoc()
{
// assert size > 0;
return topHSD.doc;
}
public float TopScore()
{
// assert size > 0;
return topHSD.scorer.Score();
}
public bool TopNextAndAdjustElsePop()
{
return CheckAdjustElsePop(topHSD.scorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
public bool TopSkipToAndAdjustElsePop(int target)
{
return CheckAdjustElsePop(topHSD.scorer.Advance(target) != DocIdSetIterator.NO_MORE_DOCS);
}
private bool CheckAdjustElsePop(bool cond)
{
if (cond)
{
// see also adjustTop
topHSD.doc = topHSD.scorer.DocID();
}
else
{
// see also popNoResult
heap[1] = heap[size]; // move last to first
heap[size] = null;
size--;
}
DownHeap();
return cond;
}
/// <summary>Removes and returns the least scorer of the ScorerDocQueue in log(size)
/// time.
/// Should not be used when the queue is empty.
/// </summary>
public Scorer Pop()
{
// assert size > 0;
Scorer result = topHSD.scorer;
PopNoResult();
return result;
}
/// <summary>Removes the least scorer of the ScorerDocQueue in log(size) time.
/// Should not be used when the queue is empty.
/// </summary>
private void PopNoResult()
{
heap[1] = heap[size]; // move last to first
heap[size] = null;
size--;
DownHeap(); // adjust heap
}
/// <summary>Should be called when the scorer at top changes doc() value.
/// Still log(n) worst case, but it's at least twice as fast to <c>
/// { pq.top().change(); pq.adjustTop(); }
/// </c> instead of <c>
/// { o = pq.pop(); o.change(); pq.push(o); }
/// </c>
/// </summary>
public void AdjustTop()
{
// assert size > 0;
topHSD.Adjust();
DownHeap();
}
/// <summary>Returns the number of scorers currently stored in the ScorerDocQueue. </summary>
public int Size()
{
return size;
}
/// <summary>Removes all entries from the ScorerDocQueue. </summary>
public void Clear()
{
for (int i = 0; i <= size; i++)
{
heap[i] = null;
}
size = 0;
}
private void UpHeap()
{
int i = size;
HeapedScorerDoc node = heap[i]; // save bottom node
int j = Number.URShift(i, 1);
while ((j > 0) && (node.doc < heap[j].doc))
{
heap[i] = heap[j]; // shift parents down
i = j;
j = Number.URShift(j, 1);
}
heap[i] = node; // install saved node
topHSD = heap[1];
}
private void DownHeap()
{
int i = 1;
HeapedScorerDoc node = heap[i]; // save top node
int j = i << 1; // find smaller child
int k = j + 1;
if ((k <= size) && (heap[k].doc < heap[j].doc))
{
j = k;
}
while ((j <= size) && (heap[j].doc < node.doc))
{
heap[i] = heap[j]; // shift up child
i = j;
j = i << 1;
k = j + 1;
if (k <= size && (heap[k].doc < heap[j].doc))
{
j = k;
}
}
heap[i] = node; // install saved node
topHSD = heap[1];
}
}
} | {
"content_hash": "073c5badcd8e61486c5b5707a6467ee2",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 118,
"avg_line_length": 31.176923076923078,
"alnum_prop": 0.461386627189736,
"repo_name": "antiufo/lucenenet",
"id": "02e83bd1d76d3689321a137d268744e3a7b66a36",
"size": "8906",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/Lucene.Net.Core/Util/ScorerDocQueue.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "722"
},
{
"name": "C#",
"bytes": "23967051"
},
{
"name": "HTML",
"bytes": "24363"
},
{
"name": "Lex",
"bytes": "5530"
}
],
"symlink_target": ""
} |
from mlscripts.ml.som.classes import *
from mlscripts.ml.som.flatten import *
import scipy as scipy
import mlscripts.ml.som.functions as fn
import re
from collections import Counter
def word_plot(matrix):
matrix = scipy.transpose(matrix)
nrows = len(matrix)
for i in range(nrows):
i = nrows - 1 - i
row = matrix[i]
for m in row:
print str(m) + "\t",
print "\n"
def draw_basis_activation(map): # This mapping finds the closest neuron for each basis vector and prints the "name" of the basis vector on the neuron position
words = empty_list(map.size, 1)
basis_vectors = []
d = map.space.dimension
for i in range(d):
b = scipy.zeros(d, int)
b[i] = 1
basis_vectors.append(b)
for i, bv in enumerate(basis_vectors):
bmu = map.find_bmu0(bv)
x = map.positions[bmu]
x = fn.to_int(x)
words[x[0]][x[1]] = map.space.words[i]
word_plot(words)
return words
def draw_item_activation(mymap, named=True, overwrite=False, symbols=False):
words = empty_list(mymap.size, 1)
mymap.renormalize()
if named:
vectors = mymap.vectors
keys = mymap.keys
else:
vectors = []
keys = []
idea_names = mymap.space.idea_names
for item in mymap.space.table:
keys.append(idea_names[item])
vectors.append(mymap.space.table[item])
if symbols:
s = mymap.space.symbol_vectors
keys = []
vectors = []
for item in s:
keys.append(item)
vectors.append(s[item])
for i, vector in enumerate(vectors):
match = fn.find_best_match(vector, mymap.weights)
x = mymap.positions[match]
x = fn.to_int(x)
w = words[x[0]][x[1]]
if w == "" or overwrite:
if overwrite:
winner = fn.find_best_match(mymap.weights[match], mymap.vectors)
w = keys[winner]
else:
w = keys[i]
else:
w = w + "," + keys[i]
words[x[0]][x[1]] = w
word_plot(words)
return words
def draw_neuron_activation(mymap, named=True, symbols=False): # iterates through EACH neuron and finds closest vector
words = distances = empty_list(mymap.size, 1)
if named:
vectors = mymap.vectors
keys = mymap.keys
else:
vectors = []
keys = []
idea_names = mymap.space.idea_names
for item in mymap.space.table:
keys.append(idea_names[item])
vectors.append(mymap.space.table[item])
if symbols:
s = mymap.space.symbol_vectors
keys = []
vectors = []
for item in s:
keys.append(mymap.space.idea_names[item])
vectors.append(s[item])
for neuron in flatten(mymap.neurons):
weight = neuron.weight
match = fn.find_best_match(weight, vectors)
distance = fn.distance(weight, vectors[match])
x = neuron.position
x = fn.to_int(x)
words[x[0]][x[1]] = keys[match]
# distances[x[0]][x[1]] = distance
word_plot(words)
return words
def draw_clusters(mymap, clusters):
cluster_map = empty_list(mymap.size, 1)
vectors = mymap.vectors
keys = mymap.keys
for neuron in flatten(mymap.neurons):
weight = neuron.weight
match = fn.find_best_match(weight, vectors)
key = keys[match]
cluster = clusters[key]
x = neuron.position
x = fn.to_int(x)
# cluster_map[x[0]][x[1]] = key
cluster_map[x[0]][x[1]] = cluster
return cluster_map
def draw_clusters_per_item(mymap, clusters):
cluster_map = empty_list(mymap.size, 1)
vectors = mymap.vectors
keys = mymap.keys
for neuron in flatten(mymap.neurons):
weight = neuron.weight
match = fn.find_best_match(weight, vectors)
key = keys[match]
cluster = clusters[key]
x = neuron.position
x = fn.to_int(x)
cluster_map[x[0]][x[1]] = key
# cluster_map[x[0]][x[1]] = cluster
return cluster_map
def get_distances_to_nearest(mymap):
distances = empty_list(mymap.size, 1)
vectors = mymap.vectors
matches = []
for neuron in flatten(mymap.neurons):
weight = neuron.weight
match = fn.find_best_match(weight, vectors)
matches.append(match)
distance = fn.distance(weight, vectors[match])
x = neuron.position
x = fn.to_int(x)
distances[x[0]][x[1]] = distance
c = Counter(matches)
print c
print 'items mapped : ' + str(len(sorted(c)))
return distances
def get_umatrix(mymap, radius=1):
umatrix = empty_list(mymap.size, 1)
xmax = mymap.size[1]
ymax = mymap.size[0]
rad = range(-radius, radius + 1)
# print rad
for neuron in flatten(mymap.neurons):
weight = neuron.weight
position = neuron.position
x = position[0]
y = position[1]
xrange = []
yrange = []
for i in rad:
xrange.append(int((x + i) % xmax))
yrange.append(int((y + i) % ymax))
average_dist = 0
for x in xrange:
for y in yrange:
neighbour_weight = mymap.neurons[x][y].weight
d = fn.distance(neighbour_weight, weight)
average_dist += d
umatrix[x][y] = average_dist
return umatrix
def create_idea_names(space):
idea_names = {}
for item in space.table:
name = ""
for i, element in enumerate(space.table[item]):
word = space.words[i]
word = re.sub("\"", "", str(word))
if element > 0 :
if len(name) == 0:
name = name + word
else:
name = name + "+" + word
idea_names[item] = name
return idea_names
def empty_list(shape, i):
x = []
for n in range(shape[i]):
if i == 0:
x.append("")
else:
x.append(empty_list(shape, i - 1))
return x
| {
"content_hash": "dd6d1794e32f047d26e924240f7a415f",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 171,
"avg_line_length": 28.957943925233646,
"alnum_prop": 0.5460706793609811,
"repo_name": "IAS-ZHAW/machine_learning_scripts",
"id": "bd2e831585476cf37fde297aa5636db0b86a446c",
"size": "6375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mlscripts/ml/som/visualize.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "78718"
}
],
"symlink_target": ""
} |
///
/// Bro script compiler providing the main entry point to compiling a
/// complete Bro configuration into HILTI.
///
#ifndef BRO_PLUGIN_HILTI_COMPILER_COMPILER_H
#define BRO_PLUGIN_HILTI_COMPILER_COMPILER_H
#include <list>
#include <vector>
#include <set>
#include <memory>
class Func;
class ID;
namespace hilti {
class CompilerContext;
class Module;
class Type;
namespace builder {
class BlockBuilder;
class ModuleBuilder;
}
}
namespace bro {
namespace hilti {
namespace compiler {
class CollectorCallback;
class ModuleBuilder;
class Compiler {
public:
typedef std::list<std::shared_ptr<::hilti::Module>> module_list;
/**
* Constructor.
*
* ctx: The HILTI context to use for compiling script code. */
Compiler(std::shared_ptr<::hilti::CompilerContext> ctx);
/**
* Destructor.
*/
~Compiler();
/**
* Compiles all of Bro's script code.
*
* @return A list of compiled modules.
*/
module_list CompileAll();
/**
* Loads one external *.hlt file.
*
* @param path The full path to load the file from.
*
* @return True if successfull.
*/
bool LoadExternalHiltiCode(const std::string& path);
/**
* Returns all of a Bro namespace's function that need to be
* compiled.
*/
std::list<const Func *> Functions(const string& ns);
/**
* Returns all of a Bro namespace's global IDs that need to be
* compiled.
*/
std::list<const ::ID *> Globals(const string& ns);
/**
* Returns the module builder currently in use.
*/
::hilti::builder::ModuleBuilder* ModuleBuilder();
/**
* Returns the current block builder. This is a short-cut to calling
* the current corresponding method of the current module builder.
*
* @return The block builder.
*/
std::shared_ptr<::hilti::builder::BlockBuilder> Builder() const;
/**
* Pushes another HILTI module builder on top of the current stack.
* This one will now be consulted by Builder().
*/
void pushModuleBuilder(::hilti::builder::ModuleBuilder* mbuilder);
/**
* Removes the top-most HILTI module builder from the stack. This
* must not be called more often than pushModuleBuilder().
*/
void popModuleBuilder();
/**
* Returns the module builder for the glue code module.
*
* TODO: We should move the glue builder over to the manager.
*/
::hilti::builder::ModuleBuilder* GlueModuleBuilder() const;
/**
* XXXX
*/
class ModuleBuilder* moduleBuilderForNamespace(const std::string& ns);
/**
* XXXX
*/
std::shared_ptr<::hilti::Module> FinalizeGlueBuilder();
/**
* Returns the internal HILTI-level symbol for a Bro Function.
*
* @param func The function.
*
* @param module If non-null, a module to which the returned symbol
* should be relative. If the function's ID has the same namespace as
* the module, it will be skipped; otherwise included.
*/
std::string HiltiSymbol(const ::Func* func, shared_ptr<::hilti::Module> module, bool include_module = false);
/**
* Returns the internal HILTI-level symbol for the stub of a Bro Function.
*
* @param func The function.
*
* @param module If non-null, a module to which the returned symbol
* should be relative. If the function's ID has the same namespace as
* the module, it will be skipped; otherwise included.
*
* @param include_module If true, the returned name will include the
* module name and hence reoresent the symbol as visibile at the LLVM
* level after linking.
*/
std::string HiltiStubSymbol(const ::Func* func, shared_ptr<::hilti::Module> module, bool include_module);
/**
* Returns the internal HILTI-level symbol for a Bro ID.
*
* @param id The ID.
*
* @param module: If non-null, a module to which the returned symbol
* should be relative. If the function's ID has the same namespace as
* the module, it will be skipped; otherwise included.
*/
std::string HiltiSymbol(const ::ID* id, shared_ptr<::hilti::Module> module);
/**
* Returns the internal HILTI-level symbol for a Bro type. This will
* always be a globally valid ID.
*
* @param t The type.
*/
std::string HiltiSymbol(const ::BroType* );
/**
* Returns the internal HILTI-level symbol for a Bro ID.
*
* @param id The ID.
*
* @param global True if this is a global ID that need potentially needs
* to be qualified with a namespace.
*
* @param module: If non-empty, a module name to which the returned
* symbol should be relative. If the function's ID has the same
* namespace as the module, it will be skipped; otherwise included.
*
* @param include_module If true, the returned name will include the
* module name and hence reoresent the symbol as visibile at the LLVM
* level after linking.
*/
std::string HiltiSymbol(const std::string& id, bool global, const std::string& module, bool include_module = false);
/**
* Renders a \a BroObj via its \c Describe() method and turns the
* result into a valid HILTI identifier string.
*
* @param obj The object to describe.
*
* @return A string with a valid HILTI identifier.
*/
std::string HiltiODescSymbol(const ::BroObj* obj);
/**
* Registers a function as having been compiled.
*/
void RegisterCompiledFunction(const ::Func* func);
typedef std::map<std::string, const ::Func*> function_symbol_map;
/**
* Returns a map mapping the HILTI symbols of all compiled scripts
* functions to their corresponding Bro functions.
*/
const function_symbol_map& HiltiFunctionSymbolMap() const;
/**
* Checks if a built-in Bro function is available at HILTI-level.
*
* @param The fully-qualified Bro-level name of the function.
*
* @param If given, the HILTI-level name of the function will be
* stored in here.
*
* @param True if the BiF is available at the HILTI-level.
*/
bool HaveHiltiBif(const std::string& name, std::string* hilti_name = 0);
/**
* Attempts to statically determine the Bro function referenced by a
* Bro expression. This may or may not work.
*
* @param func The expression referencing a function
*
* @return A pair \a (success, function). If \a success is true, we
* could infer which Bro function the expression referes to; in that
* case, the function is usually it in the 2nd pair element if
* there's a local implementation (and null instead if not). If \a
* success is false, we couldn't statically determine behind the
* expression; in that case, the 2nd pair element is undefined.
*/
std::pair<bool, ::Func*> BroExprToFunc(const ::Expr* func);
/**
* XXX
*/
void CacheCustomBroType(const BroType* btype, shared_ptr<::hilti::Type> htype, const std::string& bro_id_name);
/**
* XXX
*/
std::pair<shared_ptr<::hilti::Type>, std::string> LookupCachedCustomBroType(const BroType* btype);
/**
* XXX
*/
bool HaveCustomHandler(const ::Func* ev);
private:
std::string normalizeSymbol(const std::string sym, const std::string prefix, const std::string postfix, const std::string& module, bool global, bool include_module = false);
bool CompileScripts();
Compiler::module_list CompileExternalModules();
std::list<std::string> GetNamespaces() const;
std::shared_ptr<::hilti::CompilerContext> hilti_context;
typedef std::list<::hilti::builder::ModuleBuilder*> module_builder_list;
module_builder_list mbuilders;
shared_ptr<::hilti::builder::ModuleBuilder> glue_module_builder;
std::shared_ptr<CollectorCallback> collector_callback;
std::map<const BroType*, std::pair<shared_ptr<::hilti::Type>, std::string>> cached_custom_types;
function_symbol_map hilti_function_symbol_map;
std::list<std::string> external_modules; // Custom modules loaded from external files.
typedef std::map<string, std::shared_ptr<class ModuleBuilder>> mbuilder_map;
mbuilder_map mbuilders_by_ns;
std::vector<bool> custom_event_handlers;
};
}
}
}
#endif
| {
"content_hash": "6dff0e8bab6fab507d3a3cab8ee6a82e",
"timestamp": "",
"source": "github",
"line_count": 279,
"max_line_length": 174,
"avg_line_length": 27.92831541218638,
"alnum_prop": 0.7008470225872689,
"repo_name": "FrozenCaribou/hilti",
"id": "8ad6eb50a90a9017180cc6e024c7b5073289b018",
"size": "7792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bro/src/compiler/Compiler.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "283220"
},
{
"name": "Awk",
"bytes": "126"
},
{
"name": "Bro",
"bytes": "56234"
},
{
"name": "C",
"bytes": "2754319"
},
{
"name": "C++",
"bytes": "3597919"
},
{
"name": "CMake",
"bytes": "92707"
},
{
"name": "Groff",
"bytes": "6657"
},
{
"name": "LLVM",
"bytes": "22597"
},
{
"name": "Lex",
"bytes": "2448"
},
{
"name": "M4",
"bytes": "14535"
},
{
"name": "Makefile",
"bytes": "129789"
},
{
"name": "Objective-C",
"bytes": "11552"
},
{
"name": "Perl",
"bytes": "1104"
},
{
"name": "Python",
"bytes": "30934"
},
{
"name": "Shell",
"bytes": "371796"
},
{
"name": "TeX",
"bytes": "230259"
},
{
"name": "Yacc",
"bytes": "4142"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-safechecker: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.2 / metacoq-safechecker - 1.0~beta2+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-safechecker
<small>
1.0~beta2+8.12
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-04 13:17:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-04 13:17:54 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.11"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <aa755@cs.cornell.edu>"
"Simon Boulier <simon.boulier@inria.fr>"
"Cyril Cohen <cyril.cohen@inria.fr>"
"Yannick Forster <forster@ps.uni-saarland.de>"
"Fabian Kunze <fkunze@fakusb.de>"
"Gregory Malecha <gmalecha@gmail.com>"
"Matthieu Sozeau <matthieu.sozeau@inria.fr>"
"Nicolas Tabareau <nicolas.tabareau@inria.fr>"
"Théo Winterhalter <theo.winterhalter@inria.fr>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j" "%{jobs}%" "-C" "safechecker"]
]
install: [
[make "-C" "safechecker" "install"]
]
depends: [
"ocaml" {>= "4.07.1" & < "4.10~"}
"coq" { >= "8.12~" & < "8.13~" }
"coq-metacoq-template" {= version}
"coq-metacoq-pcuic" {= version}
]
synopsis: "Implementation and verification of safe conversion and typechecking algorithms for Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
The SafeChecker modules provides a correct implementation of
weak-head reduction, conversion and typechecking of Coq definitions and global environments.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/v1.0-beta2-8.12.tar.gz"
checksum: "sha256=108582a6f11ed511a5a94f2b302359f8d648168cba893169009def7c19e08778"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-safechecker.1.0~beta2+8.12 coq.8.7.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.2).
The following dependencies couldn't be met:
- coq-metacoq-safechecker -> ocaml >= 4.07.1
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-safechecker.1.0~beta2+8.12</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "d6191bab36e108f5c522ac122bb7fe39",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 159,
"avg_line_length": 43.11666666666667,
"alnum_prop": 0.5565004509728128,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3f9b573e0d921e7bb0eb9804253c68926b0c5c0e",
"size": "7787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.7.2/metacoq-safechecker/1.0~beta2+8.12.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module ShopqiAPI
class SmartCollection < Base
include Events
include Metafields
def products
Product.find(:all, :params => {:collection_id => self.id})
end
end
end
| {
"content_hash": "00e1c0b05d2966f1d57339acbc3e29ef",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 19.1,
"alnum_prop": 0.6649214659685864,
"repo_name": "nolimit163/shopqi",
"id": "2a0305fb1ffda3d9801f75f16afc0ed96da92aee",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/shopqi_api/resources/smart_collection.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "29429"
}
],
"symlink_target": ""
} |
@implementation NSString (path)
-(NSString *)appendcatch
{
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString *name = [self lastPathComponent];
NSString *namepath = [path stringByAppendingString:name];
return namepath;
}
@end
| {
"content_hash": "94a003da82170090cbd9c3db965cb3b3",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 110,
"avg_line_length": 20.375,
"alnum_prop": 0.7208588957055214,
"repo_name": "tuyongjiang/DSBWebImage",
"id": "1f81dbe3d7c34bcbbe8c4ed9fe9913298fb21f09",
"size": "494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "仿WebImage/仿WebImage/NSString+path.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "12200"
}
],
"symlink_target": ""
} |
package org.hibernate.validator.referenceguide.chapter12.booleancomposition;
//end::include[]
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import jakarta.validation.ReportAsSingleViolation;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.ConstraintComposition;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import static org.hibernate.validator.constraints.CompositionType.OR;
//tag::include[]
@ConstraintComposition(OR)
@Pattern(regexp = "[a-z]")
@Size(min = 2, max = 3)
@ReportAsSingleViolation
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface PatternOrSize {
String message() default "{org.hibernate.validator.referenceguide.chapter11." +
"booleancomposition.PatternOrSize.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
//end::include[]
| {
"content_hash": "27f6e4769977519f5d821d6dfeff3218",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 80,
"avg_line_length": 31.314285714285713,
"alnum_prop": 0.7883211678832117,
"repo_name": "hibernate/hibernate-validator",
"id": "2d37a988ec301c695fe8696eaca9bd4d25a9d2fc",
"size": "1113",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "documentation/src/test/java/org/hibernate/validator/referenceguide/chapter12/booleancomposition/PatternOrSize.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "7782"
},
{
"name": "HTML",
"bytes": "1387"
},
{
"name": "Java",
"bytes": "4884336"
},
{
"name": "Shell",
"bytes": "476"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "611c14e75f1518976c507de7122be836",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "116246411e4195bf6bf382824b9d18b246ef0097",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Pelargonium/Pelargonium lilacinum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.assertj.core.presentation;
import static java.lang.Integer.toHexString;
import static java.lang.reflect.Array.getLength;
import static org.assertj.core.util.Arrays.isArray;
import static org.assertj.core.util.Arrays.isArrayTypePrimitive;
import static org.assertj.core.util.Arrays.isObjectArray;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.Strings.concat;
import static org.assertj.core.util.Strings.quote;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicMarkableReference;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.function.Function;
import org.assertj.core.data.MapEntry;
import org.assertj.core.groups.Tuple;
import org.assertj.core.util.Arrays;
import org.assertj.core.util.Compatibility;
import org.assertj.core.util.DateUtil;
import org.assertj.core.util.diff.ChangeDelta;
import org.assertj.core.util.diff.DeleteDelta;
import org.assertj.core.util.diff.InsertDelta;
/**
* Standard java object representation.
*
* @author Mariusz Smykula
*/
public class StandardRepresentation implements Representation {
// can share this as StandardRepresentation has no state
public static final StandardRepresentation STANDARD_REPRESENTATION = new StandardRepresentation();
private static final String NULL = "null";
private static final String TUPLE_START = "(";
private static final String TUPLE_END = ")";
private static final String DEFAULT_START = "[";
private static final String DEFAULT_END = "]";
private static final String DEFAULT_MAX_ELEMENTS_EXCEEDED = "...";
// 4 spaces indentation : 2 space indentation after new line + '<' + '['
static final String INDENTATION_AFTER_NEWLINE = " ";
// used when formatting iterables to a single line
static final String INDENTATION_FOR_SINGLE_LINE = " ";
public static final String ELEMENT_SEPARATOR = ",";
public static final String ELEMENT_SEPARATOR_WITH_NEWLINE = ELEMENT_SEPARATOR + Compatibility.System.lineSeparator();
private static int maxLengthForSingleLineDescription = 80;
private static final Map<Class<?>, Function<?, String>> customFormatterByType = new HashMap<>();
private static int maxElementsForPrinting = 1000;
/**
* It resets the static defaults for the standard representation.
* <p>
* The following defaults will be reapplied:
* <ul>
* <li>{@code maxLengthForSingleLineDescription = 80}</li>
* <li>{@code maxElementsForPrinting = 1000}</li>
* </ul>
*/
public static void resetDefaults() {
maxLengthForSingleLineDescription = 80;
maxElementsForPrinting = 1000;
}
public static void setMaxLengthForSingleLineDescription(int value) {
checkArgument(value > 0, "maxLengthForSingleLineDescription must be > 0 but was %s", value);
maxLengthForSingleLineDescription = value;
}
public static int getMaxLengthForSingleLineDescription() {
return maxLengthForSingleLineDescription;
}
public static void setMaxElementsForPrinting(int value) {
checkArgument(value >= 1, "maxElementsForPrinting must be >= 1, but was %s", value);
maxElementsForPrinting = value;
}
/**
* Registers new formatter for the given type. All instances of the given type will be formatted with the provided formatter.
*
* @param <T> the type to register a formatter for
* @param type the class of the type to register a formatter for
* @param formatter the formatter
*/
public static <T> void registerFormatterForType(Class<T> type, Function<T, String> formatter) {
customFormatterByType.put(type, formatter);
}
/**
* Clear all formatters registered per type with {@link #registerFormatterForType(Class, Function)}.
*/
public static void removeAllRegisteredFormatters() {
customFormatterByType.clear();
}
/**
* Returns standard the {@code toString} representation of the given object. It may or not the object's own
* implementation of {@code toString}.
*
* @param object the given object.
* @return the {@code toString} representation of the given object.
*/
@Override
public String toStringOf(Object object) {
if (object == null) return null;
if (hasCustomFormatterFor(object)) return customFormat(object);
if (object instanceof Calendar) return toStringOf((Calendar) object);
if (object instanceof Class<?>) return toStringOf((Class<?>) object);
if (object instanceof Date) return toStringOf((Date) object);
if (object instanceof AtomicBoolean) return toStringOf((AtomicBoolean) object);
if (object instanceof AtomicInteger) return toStringOf((AtomicInteger) object);
if (object instanceof AtomicLong) return toStringOf((AtomicLong) object);
if (object instanceof AtomicReference) return toStringOf((AtomicReference<?>) object);
if (object instanceof AtomicMarkableReference) return toStringOf((AtomicMarkableReference<?>) object);
if (object instanceof AtomicStampedReference) return toStringOf((AtomicStampedReference<?>) object);
if (object instanceof AtomicIntegerFieldUpdater) return AtomicIntegerFieldUpdater.class.getSimpleName();
if (object instanceof AtomicLongFieldUpdater) return AtomicLongFieldUpdater.class.getSimpleName();
if (object instanceof AtomicReferenceFieldUpdater) return AtomicReferenceFieldUpdater.class.getSimpleName();
if (object instanceof Number) return toStringOf((Number) object);
if (object instanceof File) return toStringOf((File) object);
if (object instanceof String) return toStringOf((String) object);
if (object instanceof Character) return toStringOf((Character) object);
if (object instanceof Comparator) return toStringOf((Comparator<?>) object);
if (object instanceof SimpleDateFormat) return toStringOf((SimpleDateFormat) object);
if (object instanceof PredicateDescription) return toStringOf((PredicateDescription) object);
if (object instanceof CompletableFuture) return toStringOf((CompletableFuture<?>) object);
if (isArray(object)) return formatArray(object);
if (object instanceof Collection<?>) return smartFormat((Collection<?>) object);
if (object instanceof Map<?, ?>) return toStringOf((Map<?, ?>) object);
if (object instanceof Tuple) return toStringOf((Tuple) object);
if (object instanceof MapEntry) return toStringOf((MapEntry<?, ?>) object);
if (object instanceof Method) return ((Method) object).toGenericString();
if (object instanceof InsertDelta<?>) return toStringOf((InsertDelta<?>) object);
if (object instanceof ChangeDelta<?>) return toStringOf((ChangeDelta<?>) object);
if (object instanceof DeleteDelta<?>) return toStringOf((DeleteDelta<?>) object);
return object == null ? null : fallbackToStringOf(object);
}
@SuppressWarnings("unchecked")
protected <T> String customFormat(T object) {
if (object == null) return null;
return ((Function<T, String>) customFormatterByType.get(object.getClass())).apply(object);
}
protected boolean hasCustomFormatterFor(Object object) {
if (object == null) return false;
return customFormatterByType.containsKey(object.getClass());
}
@Override
public String unambiguousToStringOf(Object obj) {
return obj == null ? null
: String.format("%s (%s@%s)", toStringOf(obj), obj.getClass().getSimpleName(), toHexString(obj.hashCode()));
}
/**
* Returns the {@code String} representation of the given object. This method is used as a last resort if none of
* the {@link StandardRepresentation} predefined string representations were not called.
*
* @param object the object to represent (never {@code null}
* @return to {@code toString} representation for the given object
*/
protected String fallbackToStringOf(Object object) {
return object.toString();
}
protected String toStringOf(Number number) {
if (number instanceof Float) return toStringOf((Float) number);
if (number instanceof Long) return toStringOf((Long) number);
// fallback to default formatting
return number.toString();
}
protected String toStringOf(AtomicBoolean atomicBoolean) {
return String.format("AtomicBoolean(%s)", atomicBoolean.get());
}
protected String toStringOf(AtomicInteger atomicInteger) {
return String.format("AtomicInteger(%s)", atomicInteger.get());
}
protected String toStringOf(AtomicLong atomicLong) {
return String.format("AtomicLong(%s)", atomicLong.get());
}
protected String toStringOf(Comparator<?> comparator) {
if (!comparator.toString().contains("@")) return quote(comparator.toString());
String comparatorSimpleClassName = comparator.getClass().getSimpleName();
if (comparatorSimpleClassName.length() == 0) return quote("anonymous comparator class");
// if toString has not been redefined, let's use comparator simple class name.
if (comparator.toString().contains(comparatorSimpleClassName + "@")) return quote(comparatorSimpleClassName);
return quote(comparator.toString());
}
protected String toStringOf(Calendar c) {
return DateUtil.formatAsDatetime(c);
}
protected String toStringOf(Class<?> c) {
return c.getCanonicalName();
}
protected String toStringOf(String s) {
return concat("\"", s, "\"");
}
protected String toStringOf(Character c) {
return concat("'", c, "'");
}
protected String toStringOf(PredicateDescription p) {
// don't enclose default description with ''
return p.isDefault() ? String.format("%s", p.description) : String.format("'%s'", p.description);
}
protected String toStringOf(Date d) {
return DateUtil.formatAsDatetimeWithMs(d);
}
protected String toStringOf(Float f) {
return String.format("%sf", f);
}
protected String toStringOf(Long l) {
return String.format("%sL", l);
}
protected String toStringOf(File f) {
return f.getAbsolutePath();
}
protected String toStringOf(SimpleDateFormat dateFormat) {
return dateFormat.toPattern();
}
protected String toStringOf(CompletableFuture<?> future) {
String className = future.getClass().getSimpleName();
if (!future.isDone()) return concat(className, "[Incomplete]");
try {
Object joinResult = future.join();
// avoid stack overflow error if future join on itself or another future that cycles back to the first
Object joinResultRepresentation = joinResult instanceof CompletableFuture ? joinResult : toStringOf(joinResult);
return concat(className, "[Completed: ", joinResultRepresentation, "]");
} catch (CompletionException e) {
return concat(className, "[Failed: ", toStringOf(e.getCause()), "]");
} catch (CancellationException e) {
return concat(className, "[Cancelled]");
}
}
protected String toStringOf(Tuple tuple) {
return singleLineFormat(tuple.toList(), TUPLE_START, TUPLE_END);
}
protected String toStringOf(MapEntry<?, ?> mapEntry) {
return String.format("MapEntry[key=%s, value=%s]", toStringOf(mapEntry.key), toStringOf(mapEntry.value));
}
protected String toStringOf(Map<?, ?> map) {
if (map == null) return null;
Map<?, ?> sortedMap = toSortedMapIfPossible(map);
Iterator<?> entriesIterator = sortedMap.entrySet().iterator();
if (!entriesIterator.hasNext()) return "{}";
StringBuilder builder = new StringBuilder("{");
int printedElements = 0;
for (;;) {
Entry<?, ?> entry = (Entry<?, ?>) entriesIterator.next();
if (printedElements == maxElementsForPrinting) {
builder.append(DEFAULT_MAX_ELEMENTS_EXCEEDED);
return builder.append("}").toString();
}
builder.append(format(map, entry.getKey())).append('=').append(format(map, entry.getValue()));
printedElements++;
if (!entriesIterator.hasNext()) return builder.append("}").toString();
builder.append(", ");
}
}
private static Map<?, ?> toSortedMapIfPossible(Map<?, ?> map) {
try {
return new TreeMap<>(map);
} catch (ClassCastException | NullPointerException e) {
return map;
}
}
private String format(Map<?, ?> map, Object o) {
return o == map ? "(this Map)" : toStringOf(o);
}
protected String toStringOf(AtomicReference<?> atomicReference) {
return String.format("AtomicReference[%s]", toStringOf(atomicReference.get()));
}
protected String toStringOf(AtomicMarkableReference<?> atomicMarkableReference) {
return String.format("AtomicMarkableReference[marked=%s, reference=%s]", atomicMarkableReference.isMarked(),
toStringOf(atomicMarkableReference.getReference()));
}
protected String toStringOf(AtomicStampedReference<?> atomicStampedReference) {
return String.format("AtomicStampedReference[stamp=%s, reference=%s]", atomicStampedReference.getStamp(),
toStringOf(atomicStampedReference.getReference()));
}
private String toStringOf(ChangeDelta<?> changeDelta) {
return String.format("Changed content at line %s:%nexpecting:%n %s%nbut was:%n %s%n",
changeDelta.lineNumber(),
formatLines(changeDelta.getOriginal().getLines()),
formatLines(changeDelta.getRevised().getLines()));
}
private String toStringOf(DeleteDelta<?> deleteDelta) {
return String.format("Missing content at line %s:%n %s%n", deleteDelta.lineNumber(),
formatLines(deleteDelta.getOriginal().getLines()));
}
private String toStringOf(InsertDelta<?> insertDelta) {
return String.format("Extra content at line %s:%n %s%n", insertDelta.lineNumber(),
formatLines(insertDelta.getRevised().getLines()));
}
private String formatLines(List<?> lines) {
return format(lines, DEFAULT_START, DEFAULT_END, ELEMENT_SEPARATOR_WITH_NEWLINE, " ");
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
/**
* Returns the {@code String} representation of the given array, or {@code null} if the given object is either
* {@code null} or not an array. This method supports arrays having other arrays as elements.
*
* @param o the object that is expected to be an array.
* @return the {@code String} representation of the given array.
*/
protected String formatArray(Object o) {
if (!isArray(o)) return null;
return isObjectArray(o) ? smartFormat(this, (Object[]) o) : formatPrimitiveArray(o);
}
protected String multiLineFormat(Representation representation, Object[] iterable, Set<Object[]> alreadyFormatted) {
return format(iterable, ELEMENT_SEPARATOR_WITH_NEWLINE, INDENTATION_AFTER_NEWLINE, alreadyFormatted);
}
protected String singleLineFormat(Representation representation, Object[] iterable, String start, String end,
Set<Object[]> alreadyFormatted) {
return format(iterable, ELEMENT_SEPARATOR, INDENTATION_FOR_SINGLE_LINE, alreadyFormatted);
}
protected String smartFormat(Representation representation, Object[] iterable) {
Set<Object[]> alreadyFormatted = new HashSet<>();
String singleLineDescription = singleLineFormat(representation, iterable, DEFAULT_START, DEFAULT_END,
alreadyFormatted);
return doesDescriptionFitOnSingleLine(singleLineDescription) ? singleLineDescription
: multiLineFormat(representation, iterable, alreadyFormatted);
}
protected String format(Object[] array, String elementSeparator,
String indentation, Set<Object[]> alreadyFormatted) {
if (array == null) return null;
if (array.length == 0) return DEFAULT_START + DEFAULT_END;
// iterable has some elements
StringBuilder desc = new StringBuilder();
desc.append(DEFAULT_START);
alreadyFormatted.add(array); // used to avoid infinite recursion when array contains itself
int i = 0;
while (true) {
Object element = array[i];
// do not indent first element
if (i != 0) desc.append(indentation);
if (i == maxElementsForPrinting) {
desc.append(DEFAULT_MAX_ELEMENTS_EXCEEDED);
alreadyFormatted.remove(array);
return desc.append(DEFAULT_END).toString();
}
// add element representation
if (!isArray(element)) desc.append(element == null ? NULL : toStringOf(element));
else if (isArrayTypePrimitive(element)) desc.append(formatPrimitiveArray(element));
else if (alreadyFormatted.contains(element)) desc.append("(this array)");
else desc.append(format((Object[]) element, elementSeparator, indentation, alreadyFormatted));
// manage end description
if (i == array.length - 1) {
alreadyFormatted.remove(array);
return desc.append(DEFAULT_END).toString();
}
// there are still elements to describe
desc.append(elementSeparator);
i++;
}
}
protected String formatPrimitiveArray(Object o) {
if (!isArray(o)) return null;
if (!isArrayTypePrimitive(o)) throw Arrays.notAnArrayOfPrimitives(o);
int size = getLength(o);
if (size == 0) return DEFAULT_START + DEFAULT_END;
StringBuilder buffer = new StringBuilder();
buffer.append(DEFAULT_START);
buffer.append(toStringOf(Array.get(o, 0)));
for (int i = 1; i < size; i++) {
buffer.append(ELEMENT_SEPARATOR)
.append(INDENTATION_FOR_SINGLE_LINE);
if (i == maxElementsForPrinting) {
buffer.append(DEFAULT_MAX_ELEMENTS_EXCEEDED);
break;
}
buffer.append(toStringOf(Array.get(o, i)));
}
buffer.append(DEFAULT_END);
return buffer.toString();
}
public String format(Iterable<?> iterable, String start, String end, String elementSeparator, String indentation) {
if (iterable == null) return null;
Iterator<?> iterator = iterable.iterator();
if (!iterator.hasNext()) return start + end;
// iterable has some elements
StringBuilder desc = new StringBuilder(start);
boolean firstElement = true;
int printedElements = 0;
while (true) {
Object element = iterator.next();
// do not indent first element
if (firstElement) firstElement = false;
else desc.append(indentation);
// add element representation
if (printedElements == maxElementsForPrinting) {
desc.append(DEFAULT_MAX_ELEMENTS_EXCEEDED);
return desc.append(end).toString();
}
desc.append(element == iterable ? "(this Collection)" : toStringOf(element));
printedElements++;
// manage end description
if (!iterator.hasNext()) return desc.append(end).toString();
// there are still elements to be describe
desc.append(elementSeparator);
}
}
protected String multiLineFormat(Iterable<?> iterable) {
return format(iterable, DEFAULT_START, DEFAULT_END, ELEMENT_SEPARATOR_WITH_NEWLINE, INDENTATION_AFTER_NEWLINE);
}
protected String singleLineFormat(Iterable<?> iterable, String start, String end) {
return format(iterable, start, end, ELEMENT_SEPARATOR, INDENTATION_FOR_SINGLE_LINE);
}
/**
* Returns the {@code String} representation of the given {@code Iterable}, or {@code null} if the given
* {@code Iterable} is {@code null}.
* <p>
* The {@code Iterable} will be formatted to a single line if it does not exceed 100 char, otherwise each elements
* will be formatted on a new line with 4 space indentation.
*
* @param iterable the {@code Iterable} to format.
* @return the {@code String} representation of the given {@code Iterable}.
*/
protected String smartFormat(Iterable<?> iterable) {
String singleLineDescription = singleLineFormat(iterable, DEFAULT_START, DEFAULT_END);
return doesDescriptionFitOnSingleLine(singleLineDescription) ? singleLineDescription : multiLineFormat(iterable);
}
private static boolean doesDescriptionFitOnSingleLine(String singleLineDescription) {
return singleLineDescription == null || singleLineDescription.length() < maxLengthForSingleLineDescription;
}
}
| {
"content_hash": "7a80fe28755652f00ee9bceb21700e9d",
"timestamp": "",
"source": "github",
"line_count": 506,
"max_line_length": 127,
"avg_line_length": 41.47430830039526,
"alnum_prop": 0.712332030877728,
"repo_name": "ChrisA89/assertj-core",
"id": "cd25b40363b1c05947e76355b7a2905d7cd56895",
"size": "21593",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/assertj/core/presentation/StandardRepresentation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9353819"
},
{
"name": "Shell",
"bytes": "40820"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Altus.Suffūz.Collections.IO;
using Altus.Suffūz.Serialization;
using Altus.Suffūz.Serialization.Binary;
namespace Altus.Suffūz.Collections
{
public class PersistentList<TValue> : PersistentList, IPersistentList<TValue>
{
public PersistentList() : base()
{
}
public PersistentList(string filePath, int maxSize = 1024 * 1024 * 1024) : base(filePath, maxSize)
{
}
TValue IList<TValue>.this[int index]
{
get
{
return (TValue)base[index];
}
set
{
base[index] = value;
}
}
public void Add(TValue item)
{
base.Add(item);
}
public bool Contains(TValue item)
{
return base.Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
var i = 0;
foreach(var item in this)
{
array[arrayIndex + i] = item;
i++;
}
}
public int IndexOf(TValue item)
{
return base.IndexOf(item);
}
public void Insert(int index, TValue item)
{
base.Insert(index, item);
}
public bool Remove(TValue item)
{
var index = IndexOf(item);
if (index >= 0)
{
var key = Addresses.Skip(index).Take(1).Single();
Free(key.Key);
return true;
}
return false;
}
public new IEnumerator<TValue> GetEnumerator()
{
foreach(var kvp in Addresses)
{
yield return Read<TValue>(kvp.Key);
}
}
}
public class PersistentList : PersistentHeap, IPersistentList
{
public PersistentList() : base()
{
}
public PersistentList(string filePath, int maxSize = 1024 * 1024 * 1024) : base(filePath, maxSize)
{
}
public object this[int index]
{
get
{
var key = Addresses.Skip(index).Take(1).Single();
return Read(key.Key);
}
set
{
var key = Addresses.Skip(index).Take(1).Single();
Write(value, key.Key);
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool Contains(object value)
{
foreach(var item in this)
{
if ((value == null && item == null)
||(value != null && value.Equals(item)))
{
return true;
}
}
return false;
}
public int IndexOf(object value)
{
var i = 0;
foreach (var item in this)
{
if ((value == null && item == null)
|| (value != null && value.Equals(item)))
{
return i;
}
i++;
}
return -1;
}
public void Insert(int index, object value)
{
throw new NotSupportedException("Insert operations are not supported on this collection type");
}
public void Remove(object value)
{
var index = IndexOf(value);
if (index >= 0)
{
var key = Addresses.Skip(index).Take(1).Single();
Free(key.Key);
}
}
public void RemoveAt(int index)
{
var key = Addresses.Skip(index).Take(1).Single();
Free(key.Key);
}
int IList.Add(object value)
{
return (int)base.Add(value);
}
}
}
| {
"content_hash": "3a002d9d323704401aadc5edb49da08d",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 107,
"avg_line_length": 23.48587570621469,
"alnum_prop": 0.44984363723839305,
"repo_name": "odinhaus/Suffuz",
"id": "47d84f1a91124d39a1608126d795f759aeb773f5",
"size": "4163",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Altus.Suffūz/Collections/PersistentList.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1294617"
},
{
"name": "JavaScript",
"bytes": "122396"
}
],
"symlink_target": ""
} |
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TestInterfaceConstructor::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterfaceConstructor::domTemplate, V8TestInterfaceConstructor::trace, V8TestInterfaceConstructor::traceWrappers, 0, 0, V8TestInterfaceConstructor::preparePrototypeAndInterfaceObject, nullptr, "TestInterfaceConstructor", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestInterfaceConstructor.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TestInterfaceConstructor::s_wrapperTypeInfo = V8TestInterfaceConstructor::wrapperTypeInfo;
namespace TestInterfaceConstructorV8Internal {
static void constructor1(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
static void constructor2(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
double doubleArg;
V8StringResource<> stringArg;
TestInterfaceEmpty* testInterfaceEmptyArg;
Dictionary dictionaryArg;
Vector<String> sequenceStringArg;
Vector<Dictionary> sequenceDictionaryArg;
HeapVector<LongOrTestDictionary> sequenceLongOrTestDictionaryArg;
Dictionary optionalDictionaryArg;
TestInterfaceEmpty* optionalTestInterfaceEmptyArg;
{
doubleArg = toRestrictedDouble(info.GetIsolate(), info[0], exceptionState);
if (exceptionState.throwIfNeeded())
return;
stringArg = info[1];
if (!stringArg.prepare())
return;
testInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[2]);
if (!testInterfaceEmptyArg) {
exceptionState.throwTypeError("parameter 3 is not of type 'TestInterfaceEmpty'.");
exceptionState.throwIfNeeded();
return;
}
if (!isUndefinedOrNull(info[3]) && !info[3]->IsObject()) {
exceptionState.throwTypeError("parameter 4 ('dictionaryArg') is not an object.");
exceptionState.throwIfNeeded();
return;
}
dictionaryArg = Dictionary(info[3], info.GetIsolate(), exceptionState);
if (exceptionState.throwIfNeeded())
return;
sequenceStringArg = toImplArray<Vector<String>>(info[4], 5, info.GetIsolate(), exceptionState);
if (exceptionState.throwIfNeeded())
return;
sequenceDictionaryArg = toImplArray<Vector<Dictionary>>(info[5], 6, info.GetIsolate(), exceptionState);
if (exceptionState.throwIfNeeded())
return;
sequenceLongOrTestDictionaryArg = toImplArray<HeapVector<LongOrTestDictionary>>(info[6], 7, info.GetIsolate(), exceptionState);
if (exceptionState.throwIfNeeded())
return;
if (!isUndefinedOrNull(info[7]) && !info[7]->IsObject()) {
exceptionState.throwTypeError("parameter 8 ('optionalDictionaryArg') is not an object.");
exceptionState.throwIfNeeded();
return;
}
optionalDictionaryArg = Dictionary(info[7], info.GetIsolate(), exceptionState);
if (exceptionState.throwIfNeeded())
return;
optionalTestInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[8]);
if (!optionalTestInterfaceEmptyArg) {
exceptionState.throwTypeError("parameter 9 is not of type 'TestInterfaceEmpty'.");
exceptionState.throwIfNeeded();
return;
}
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, doubleArg, stringArg, testInterfaceEmptyArg, dictionaryArg, sequenceStringArg, sequenceDictionaryArg, sequenceLongOrTestDictionaryArg, optionalDictionaryArg, optionalTestInterfaceEmptyArg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
static void constructor3(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
V8StringResource<> arg;
V8StringResource<> optArg;
{
int numArgsPassed = info.Length();
while (numArgsPassed > 0) {
if (!info[numArgsPassed - 1]->IsUndefined())
break;
--numArgsPassed;
}
arg = info[0];
if (!arg.prepare())
return;
if (UNLIKELY(numArgsPassed <= 1)) {
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
return;
}
optArg = info[1];
if (!optArg.prepare())
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, optArg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
static void constructor4(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
V8StringResource<> arg;
V8StringResource<> arg2;
V8StringResource<> arg3;
{
arg = info[0];
if (!arg.prepare())
return;
arg2 = info[1];
if (!arg2.prepare())
return;
arg3 = info[2];
if (!arg3.prepare())
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, arg2, arg3, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
switch (std::min(9, info.Length())) {
case 0:
if (true) {
TestInterfaceConstructorV8Internal::constructor1(info);
return;
}
break;
case 1:
if (true) {
TestInterfaceConstructorV8Internal::constructor3(info);
return;
}
break;
case 2:
if (true) {
TestInterfaceConstructorV8Internal::constructor3(info);
return;
}
break;
case 3:
if (true) {
TestInterfaceConstructorV8Internal::constructor4(info);
return;
}
break;
case 7:
if (true) {
TestInterfaceConstructorV8Internal::constructor2(info);
return;
}
break;
case 8:
if (true) {
TestInterfaceConstructorV8Internal::constructor2(info);
return;
}
break;
case 9:
if (true) {
TestInterfaceConstructorV8Internal::constructor2(info);
return;
}
break;
default:
if (info.Length() >= 0) {
setArityTypeError(exceptionState, "[0, 1, 2, 3, 7, 8, 9]", info.Length());
exceptionState.throwIfNeeded();
return;
}
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(0, info.Length()));
exceptionState.throwIfNeeded();
return;
}
exceptionState.throwTypeError("No matching constructor signature.");
exceptionState.throwIfNeeded();
}
} // namespace TestInterfaceConstructorV8Internal
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TestInterfaceConstructorConstructor::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterfaceConstructorConstructor::domTemplate, V8TestInterfaceConstructor::trace, V8TestInterfaceConstructor::traceWrappers, 0, 0, V8TestInterfaceConstructor::preparePrototypeAndInterfaceObject, nullptr, "TestInterfaceConstructor", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
static void V8TestInterfaceConstructorConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("Audio"));
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
V8StringResource<> arg;
V8StringResource<> optArg;
{
int numArgsPassed = info.Length();
while (numArgsPassed > 0) {
if (!info[numArgsPassed - 1]->IsUndefined())
break;
--numArgsPassed;
}
arg = info[0];
if (!arg.prepare())
return;
if (UNLIKELY(numArgsPassed <= 1)) {
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::createForJSConstructor(scriptState, executionContext, document, arg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructorConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
return;
}
optArg = info[1];
if (!optArg.prepare())
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
TestInterfaceConstructor* impl = TestInterfaceConstructor::createForJSConstructor(scriptState, executionContext, document, arg, optArg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructorConstructor::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructorConstructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world)
{
static int domTemplateKey; // This address is used for a key to look up the dom template.
V8PerIsolateData* data = V8PerIsolateData::from(isolate);
v8::Local<v8::FunctionTemplate> result = data->findInterfaceTemplate(world, &domTemplateKey);
if (!result.IsEmpty())
return result;
result = v8::FunctionTemplate::New(isolate, V8TestInterfaceConstructorConstructorCallback);
v8::Local<v8::ObjectTemplate> instanceTemplate = result->InstanceTemplate();
instanceTemplate->SetInternalFieldCount(V8TestInterfaceConstructor::internalFieldCount);
result->SetClassName(v8AtomicString(isolate, "TestInterfaceConstructor"));
result->Inherit(V8TestInterfaceConstructor::domTemplate(isolate, world));
data->setInterfaceTemplate(world, &domTemplateKey, result);
return result;
}
void V8TestInterfaceConstructor::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::TestFeature);
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("TestInterfaceConstructor"));
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
TestInterfaceConstructorV8Internal::constructor(info);
}
static void installV8TestInterfaceConstructorTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interfaceTemplate)
{
// Initialize the interface object's template.
V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor::internalFieldCount);
interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor::constructorCallback);
interfaceTemplate->SetLength(0);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Register DOM constants, attributes and operations.
}
v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world)
{
return V8DOMConfiguration::domClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TestInterfaceConstructorTemplate);
}
bool V8TestInterfaceConstructor::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TestInterfaceConstructor::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TestInterfaceConstructor* V8TestInterfaceConstructor::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
} // namespace blink
| {
"content_hash": "a0b69643c7d54ab4956bf46a391f1e55",
"timestamp": "",
"source": "github",
"line_count": 384,
"max_line_length": 494,
"avg_line_length": 47.364583333333336,
"alnum_prop": 0.7093688146030349,
"repo_name": "axinging/chromium-crosswalk",
"id": "14443d05878d6c90a998d40896275d89203128f0",
"size": "18961",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "8242"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "23945"
},
{
"name": "C",
"bytes": "4103204"
},
{
"name": "C++",
"bytes": "225022948"
},
{
"name": "CSS",
"bytes": "949808"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Go",
"bytes": "18155"
},
{
"name": "HTML",
"bytes": "28206993"
},
{
"name": "Java",
"bytes": "7651204"
},
{
"name": "JavaScript",
"bytes": "18831169"
},
{
"name": "Makefile",
"bytes": "96270"
},
{
"name": "Objective-C",
"bytes": "1228122"
},
{
"name": "Objective-C++",
"bytes": "7563676"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "418221"
},
{
"name": "Python",
"bytes": "7855597"
},
{
"name": "Shell",
"bytes": "472586"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
} |
import copy
import itertools
import json
import logging
import math
import os
import socket
import traceback
from collections import defaultdict
from datetime import timedelta
import markdown
import nvd3
import pendulum
import sqlalchemy as sqla
from flask import (
redirect, request, Markup, Response, render_template,
make_response, flash, jsonify)
from flask._compat import PY2
from flask_appbuilder import BaseView, ModelView, expose, has_access
from flask_appbuilder.actions import action
from flask_appbuilder.models.sqla.filters import BaseFilter
from flask_babel import lazy_gettext
from past.builtins import unicode
from pygments import highlight, lexers
from pygments.formatters import HtmlFormatter
from sqlalchemy import or_, desc, and_, union_all
from wtforms import SelectField, validators
import airflow
from airflow import configuration as conf
from airflow import models, jobs
from airflow import settings
from airflow.api.common.experimental.mark_tasks import (set_dag_run_state_to_success,
set_dag_run_state_to_failed)
from airflow.models import XCom, DagRun
from airflow.ti_deps.dep_context import DepContext, QUEUE_DEPS, SCHEDULER_DEPS
from airflow.utils import timezone
from airflow.utils.dates import infer_time_unit, scale_time_units
from airflow.utils.db import provide_session
from airflow.utils.helpers import alchemy_to_dict
from airflow.utils.json import json_ser
from airflow.utils.state import State
from airflow.www_rbac import utils as wwwutils
from airflow.www_rbac.app import app, appbuilder
from airflow.www_rbac.decorators import action_logging, gzipped, has_dag_access
from airflow.www_rbac.forms import (DateTimeForm, DateTimeWithNumRunsForm,
DateTimeWithNumRunsWithDagRunsForm,
DagRunForm, ConnectionForm)
from airflow.www_rbac.widgets import AirflowModelListWidget
PAGE_SIZE = conf.getint('webserver', 'page_size')
if os.environ.get('SKIP_DAGS_PARSING') != 'True':
dagbag = models.DagBag(settings.DAGS_FOLDER)
else:
dagbag = models.DagBag
def get_date_time_num_runs_dag_runs_form_data(request, session, dag):
dttm = request.args.get('execution_date')
if dttm:
dttm = pendulum.parse(dttm)
else:
dttm = dag.latest_execution_date or timezone.utcnow()
base_date = request.args.get('base_date')
if base_date:
base_date = timezone.parse(base_date)
else:
# The DateTimeField widget truncates milliseconds and would loose
# the first dag run. Round to next second.
base_date = (dttm + timedelta(seconds=1)).replace(microsecond=0)
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
DR = models.DagRun
drs = (
session.query(DR)
.filter(
DR.dag_id == dag.dag_id,
DR.execution_date <= base_date)
.order_by(desc(DR.execution_date))
.limit(num_runs)
.all()
)
dr_choices = []
dr_state = None
for dr in drs:
dr_choices.append((dr.execution_date.isoformat(), dr.run_id))
if dttm == dr.execution_date:
dr_state = dr.state
# Happens if base_date was changed and the selected dag run is not in result
if not dr_state and drs:
dr = drs[0]
dttm = dr.execution_date
dr_state = dr.state
return {
'dttm': dttm,
'base_date': base_date,
'num_runs': num_runs,
'execution_date': dttm.isoformat(),
'dr_choices': dr_choices,
'dr_state': dr_state,
}
######################################################################################
# BaseViews
######################################################################################
class AirflowBaseView(BaseView):
route_base = ''
def render(self, template, **context):
return render_template(template,
base_template=self.appbuilder.base_template,
appbuilder=self.appbuilder,
**context)
class Airflow(AirflowBaseView):
@expose('/home')
@has_access
@provide_session
def index(self, session=None):
DM = models.DagModel
hide_paused_dags_by_default = conf.getboolean('webserver',
'hide_paused_dags_by_default')
show_paused_arg = request.args.get('showPaused', 'None')
def get_int_arg(value, default=0):
try:
return int(value)
except ValueError:
return default
arg_current_page = request.args.get('page', '0')
arg_search_query = request.args.get('search', None)
dags_per_page = PAGE_SIZE
current_page = get_int_arg(arg_current_page, default=0)
if show_paused_arg.strip().lower() == 'false':
hide_paused = True
elif show_paused_arg.strip().lower() == 'true':
hide_paused = False
else:
hide_paused = hide_paused_dags_by_default
# read orm_dags from the db
sql_query = session.query(DM).filter(
~DM.is_subdag, DM.is_active
)
# optionally filter out "paused" dags
if hide_paused:
sql_query = sql_query.filter(~DM.is_paused)
# Get all the dag id the user could access
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
import_errors = session.query(models.ImportError).all()
for ie in import_errors:
flash(
"Broken DAG: [{ie.filename}] {ie.stacktrace}".format(ie=ie),
"error")
# get a list of all non-subdag dags visible to everyone
# optionally filter out "paused" dags
if hide_paused:
unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if
not dag.parent_dag and not dag.is_paused]
else:
unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if
not dag.parent_dag]
if 'all_dags' in filter_dag_ids:
orm_dags = {dag.dag_id: dag for dag
in sql_query
.all()}
else:
orm_dags = {dag.dag_id: dag for dag in
sql_query.filter(DM.dag_id.in_(filter_dag_ids)).all()}
unfiltered_webserver_dags = [dag for dag in
unfiltered_webserver_dags
if dag.dag_id in filter_dag_ids]
webserver_dags = {
dag.dag_id: dag
for dag in unfiltered_webserver_dags
}
if arg_search_query:
lower_search_query = arg_search_query.lower()
# filter by dag_id
webserver_dags_filtered = {
dag_id: dag
for dag_id, dag in webserver_dags.items()
if (lower_search_query in dag_id.lower() or
lower_search_query in dag.owner.lower())
}
all_dag_ids = (set([dag.dag_id for dag in orm_dags.values()
if lower_search_query in dag.dag_id.lower() or
lower_search_query in dag.owners.lower()]) |
set(webserver_dags_filtered.keys()))
sorted_dag_ids = sorted(all_dag_ids)
else:
webserver_dags_filtered = webserver_dags
sorted_dag_ids = sorted(set(orm_dags.keys()) | set(webserver_dags.keys()))
start = current_page * dags_per_page
end = start + dags_per_page
num_of_all_dags = len(sorted_dag_ids)
page_dag_ids = sorted_dag_ids[start:end]
num_of_pages = int(math.ceil(num_of_all_dags / float(dags_per_page)))
auto_complete_data = set()
for dag in webserver_dags_filtered.values():
auto_complete_data.add(dag.dag_id)
auto_complete_data.add(dag.owner)
for dag in orm_dags.values():
auto_complete_data.add(dag.dag_id)
auto_complete_data.add(dag.owners)
return self.render(
'airflow/dags.html',
webserver_dags=webserver_dags_filtered,
orm_dags=orm_dags,
hide_paused=hide_paused,
current_page=current_page,
search_query=arg_search_query if arg_search_query else '',
page_size=dags_per_page,
num_of_pages=num_of_pages,
num_dag_from=start + 1,
num_dag_to=min(end, num_of_all_dags),
num_of_all_dags=num_of_all_dags,
paging=wwwutils.generate_pages(current_page, num_of_pages,
search=arg_search_query,
showPaused=not hide_paused),
dag_ids_in_page=page_dag_ids,
auto_complete_data=auto_complete_data)
@expose('/dag_stats')
@has_access
@provide_session
def dag_stats(self, session=None):
ds = models.DagStat
ds.update()
qry = (
session.query(ds.dag_id, ds.state, ds.count)
)
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
payload = {}
if filter_dag_ids:
if 'all_dags' not in filter_dag_ids:
qry = qry.filter(ds.dag_id.in_(filter_dag_ids))
data = {}
for dag_id, state, count in qry:
if dag_id not in data:
data[dag_id] = {}
data[dag_id][state] = count
for dag in dagbag.dags.values():
if 'all_dags' in filter_dag_ids or dag.dag_id in filter_dag_ids:
payload[dag.safe_dag_id] = []
for state in State.dag_states:
count = data.get(dag.dag_id, {}).get(state, 0)
payload[dag.safe_dag_id].append({
'state': state,
'count': count,
'dag_id': dag.dag_id,
'color': State.color(state)
})
return wwwutils.json_response(payload)
@expose('/task_stats')
@has_access
@provide_session
def task_stats(self, session=None):
TI = models.TaskInstance
DagRun = models.DagRun
Dag = models.DagModel
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
payload = {}
if not filter_dag_ids:
return
LastDagRun = (
session.query(
DagRun.dag_id,
sqla.func.max(DagRun.execution_date).label('execution_date'))
.join(Dag, Dag.dag_id == DagRun.dag_id)
.filter(DagRun.state != State.RUNNING)
.filter(Dag.is_active == True) # noqa
.group_by(DagRun.dag_id)
.subquery('last_dag_run')
)
RunningDagRun = (
session.query(DagRun.dag_id, DagRun.execution_date)
.join(Dag, Dag.dag_id == DagRun.dag_id)
.filter(DagRun.state == State.RUNNING)
.filter(Dag.is_active == True) # noqa
.subquery('running_dag_run')
)
# Select all task_instances from active dag_runs.
# If no dag_run is active, return task instances from most recent dag_run.
LastTI = (
session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
.join(LastDagRun,
and_(LastDagRun.c.dag_id == TI.dag_id,
LastDagRun.c.execution_date == TI.execution_date))
)
RunningTI = (
session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
.join(RunningDagRun,
and_(RunningDagRun.c.dag_id == TI.dag_id,
RunningDagRun.c.execution_date == TI.execution_date))
)
UnionTI = union_all(LastTI, RunningTI).alias('union_ti')
qry = (
session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count())
.group_by(UnionTI.c.dag_id, UnionTI.c.state)
)
data = {}
for dag_id, state, count in qry:
if 'all_dags' in filter_dag_ids or dag_id in filter_dag_ids:
if dag_id not in data:
data[dag_id] = {}
data[dag_id][state] = count
session.commit()
for dag in dagbag.dags.values():
if 'all_dags' in filter_dag_ids or dag.dag_id in filter_dag_ids:
payload[dag.safe_dag_id] = []
for state in State.task_states:
count = data.get(dag.dag_id, {}).get(state, 0)
payload[dag.safe_dag_id].append({
'state': state,
'count': count,
'dag_id': dag.dag_id,
'color': State.color(state)
})
return wwwutils.json_response(payload)
@expose('/code')
@has_dag_access(can_dag_read=True)
@has_access
def code(self):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
title = dag_id
try:
with wwwutils.open_maybe_zipped(dag.fileloc, 'r') as f:
code = f.read()
html_code = highlight(
code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
except IOError as e:
html_code = str(e)
return self.render(
'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,
root=request.args.get('root'),
demo_mode=conf.getboolean('webserver', 'demo_mode'))
@expose('/dag_details')
@has_dag_access(can_dag_read=True)
@has_access
@provide_session
def dag_details(self, session=None):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
title = "DAG details"
TI = models.TaskInstance
states = (
session.query(TI.state, sqla.func.count(TI.dag_id))
.filter(TI.dag_id == dag_id)
.group_by(TI.state)
.all()
)
return self.render(
'airflow/dag_details.html',
dag=dag, title=title, states=states, State=State)
@app.errorhandler(404)
def circles(self):
return render_template(
'airflow/circles.html', hostname=socket.getfqdn()), 404
@app.errorhandler(500)
def show_traceback(self):
from airflow.utils import asciiart as ascii_
return render_template(
'airflow/traceback.html',
hostname=socket.getfqdn(),
nukular=ascii_.nukular,
info=traceback.format_exc()), 500
@expose('/pickle_info')
@has_access
def pickle_info(self):
d = {}
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
if not filter_dag_ids:
return wwwutils.json_response({})
dag_id = request.args.get('dag_id')
dags = [dagbag.dags.get(dag_id)] if dag_id else dagbag.dags.values()
for dag in dags:
if 'all_dags' in filter_dag_ids or dag.dag_id in filter_dag_ids:
if not dag.is_subdag:
d[dag.dag_id] = dag.pickle_info()
return wwwutils.json_response(d)
@expose('/rendered')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
def rendered(self):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = pendulum.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
dag = dagbag.get_dag(dag_id)
task = copy.copy(dag.get_task(task_id))
ti = models.TaskInstance(task=task, execution_date=dttm)
try:
ti.render_templates()
except Exception as e:
flash("Error rendering template: " + str(e), "error")
title = "Rendered Template"
html_dict = {}
for template_field in task.__class__.template_fields:
content = getattr(task, template_field)
if template_field in wwwutils.get_attr_renderer():
html_dict[template_field] = \
wwwutils.get_attr_renderer()[template_field](content)
else:
html_dict[template_field] = (
"<pre><code>" + str(content) + "</pre></code>")
return self.render(
'airflow/ti_code.html',
html_dict=html_dict,
dag=dag,
task_id=task_id,
execution_date=execution_date,
form=form,
title=title, )
@expose('/get_logs_with_metadata')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def get_logs_with_metadata(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = pendulum.parse(execution_date)
try_number = int(request.args.get('try_number'))
metadata = request.args.get('metadata')
metadata = json.loads(metadata)
# metadata may be null
if not metadata:
metadata = {}
# Convert string datetime into actual datetime
try:
execution_date = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identified '
'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format(
execution_date))
response = jsonify({'error': error_message})
response.status_code = 400
return response
logger = logging.getLogger('airflow.task')
task_log_reader = conf.get('core', 'task_log_reader')
handler = next((handler for handler in logger.handlers
if handler.name == task_log_reader), None)
ti = session.query(models.TaskInstance).filter(
models.TaskInstance.dag_id == dag_id,
models.TaskInstance.task_id == task_id,
models.TaskInstance.execution_date == dttm).first()
try:
if ti is None:
logs = ["*** Task instance did not exist in the DB\n"]
metadata['end_of_log'] = True
else:
dag = dagbag.get_dag(dag_id)
ti.task = dag.get_task(ti.task_id)
logs, metadatas = handler.read(ti, try_number, metadata=metadata)
metadata = metadatas[0]
for i, log in enumerate(logs):
if PY2 and not isinstance(log, unicode):
logs[i] = log.decode('utf-8')
message = logs[0]
return jsonify(message=message, metadata=metadata)
except AttributeError as e:
error_message = ["Task log handler {} does not support read logs.\n{}\n"
.format(task_log_reader, str(e))]
metadata['end_of_log'] = True
return jsonify(message=error_message, error=True, metadata=metadata)
@expose('/log')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def log(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
execution_date = request.args.get('execution_date')
dttm = pendulum.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
dag = dagbag.get_dag(dag_id)
ti = session.query(models.TaskInstance).filter(
models.TaskInstance.dag_id == dag_id,
models.TaskInstance.task_id == task_id,
models.TaskInstance.execution_date == dttm).first()
logs = [''] * (ti.next_try_number - 1 if ti is not None else 0)
return self.render(
'airflow/ti_log.html',
logs=logs, dag=dag, title="Log by attempts",
dag_id=dag.dag_id, task_id=task_id,
execution_date=execution_date, form=form)
@expose('/task')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
def task(self):
TI = models.TaskInstance
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
# Carrying execution_date through, even though it's irrelevant for
# this context
execution_date = request.args.get('execution_date')
dttm = pendulum.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
dag = dagbag.get_dag(dag_id)
if not dag or task_id not in dag.task_ids:
flash(
"Task [{}.{}] doesn't seem to exist"
" at the moment".format(dag_id, task_id),
"error")
return redirect('/')
task = copy.copy(dag.get_task(task_id))
task.resolve_template_files()
ti = TI(task=task, execution_date=dttm)
ti.refresh_from_db()
ti_attrs = []
for attr_name in dir(ti):
if not attr_name.startswith('_'):
attr = getattr(ti, attr_name)
if type(attr) != type(self.task): # noqa
ti_attrs.append((attr_name, str(attr)))
task_attrs = []
for attr_name in dir(task):
if not attr_name.startswith('_'):
attr = getattr(task, attr_name)
if type(attr) != type(self.task) and \
attr_name not in wwwutils.get_attr_renderer(): # noqa
task_attrs.append((attr_name, str(attr)))
# Color coding the special attributes that are code
special_attrs_rendered = {}
for attr_name in wwwutils.get_attr_renderer():
if hasattr(task, attr_name):
source = getattr(task, attr_name)
special_attrs_rendered[attr_name] = \
wwwutils.get_attr_renderer()[attr_name](source)
no_failed_deps_result = [(
"Unknown",
"All dependencies are met but the task instance is not running. In most "
"cases this just means that the task will probably be scheduled soon "
"unless:<br/>\n- The scheduler is down or under heavy load<br/>\n{}\n"
"<br/>\nIf this task instance does not start soon please contact your "
"Airflow administrator for assistance.".format(
"- This task instance already ran and had it's state changed manually "
"(e.g. cleared in the UI)<br/>" if ti.state == State.NONE else ""))]
# Use the scheduler's context to figure out which dependencies are not met
dep_context = DepContext(SCHEDULER_DEPS)
failed_dep_reasons = [(dep.dep_name, dep.reason) for dep in
ti.get_failed_dep_statuses(
dep_context=dep_context)]
title = "Task Instance Details"
return self.render(
'airflow/task.html',
task_attrs=task_attrs,
ti_attrs=ti_attrs,
failed_dep_reasons=failed_dep_reasons or no_failed_deps_result,
task_id=task_id,
execution_date=execution_date,
special_attrs_rendered=special_attrs_rendered,
form=form,
dag=dag, title=title)
@expose('/xcom')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def xcom(self, session=None):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
# Carrying execution_date through, even though it's irrelevant for
# this context
execution_date = request.args.get('execution_date')
dttm = pendulum.parse(execution_date)
form = DateTimeForm(data={'execution_date': dttm})
dag = dagbag.get_dag(dag_id)
if not dag or task_id not in dag.task_ids:
flash(
"Task [{}.{}] doesn't seem to exist"
" at the moment".format(dag_id, task_id),
"error")
return redirect('/')
xcomlist = session.query(XCom).filter(
XCom.dag_id == dag_id, XCom.task_id == task_id,
XCom.execution_date == dttm).all()
attributes = []
for xcom in xcomlist:
if not xcom.key.startswith('_'):
attributes.append((xcom.key, xcom.value))
title = "XCom"
return self.render(
'airflow/xcom.html',
attributes=attributes,
task_id=task_id,
execution_date=execution_date,
form=form,
dag=dag, title=title)
@expose('/run')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def run(self):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
origin = request.args.get('origin')
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
execution_date = request.args.get('execution_date')
execution_date = pendulum.parse(execution_date)
ignore_all_deps = request.args.get('ignore_all_deps') == "true"
ignore_task_deps = request.args.get('ignore_task_deps') == "true"
ignore_ti_state = request.args.get('ignore_ti_state') == "true"
from airflow.executors import GetDefaultExecutor
executor = GetDefaultExecutor()
valid_celery_config = False
valid_kubernetes_config = False
try:
from airflow.executors.celery_executor import CeleryExecutor
valid_celery_config = isinstance(executor, CeleryExecutor)
except ImportError:
pass
try:
from airflow.contrib.executors.kubernetes_executor import KubernetesExecutor
valid_kubernetes_config = isinstance(executor, KubernetesExecutor)
except ImportError:
pass
if not valid_celery_config and not valid_kubernetes_config:
flash("Only works with the Celery or Kubernetes executors, sorry", "error")
return redirect(origin)
ti = models.TaskInstance(task=task, execution_date=execution_date)
ti.refresh_from_db()
# Make sure the task instance can be queued
dep_context = DepContext(
deps=QUEUE_DEPS,
ignore_all_deps=ignore_all_deps,
ignore_task_deps=ignore_task_deps,
ignore_ti_state=ignore_ti_state)
failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context))
if failed_deps:
failed_deps_str = ", ".join(
["{}: {}".format(dep.dep_name, dep.reason) for dep in failed_deps])
flash("Could not queue task instance for execution, dependencies not met: "
"{}".format(failed_deps_str),
"error")
return redirect(origin)
executor.start()
executor.queue_task_instance(
ti,
ignore_all_deps=ignore_all_deps,
ignore_task_deps=ignore_task_deps,
ignore_ti_state=ignore_ti_state)
executor.heartbeat()
flash(
"Sent {} to the message queue, "
"it should start any moment now.".format(ti))
return redirect(origin)
@expose('/delete')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def delete(self):
from airflow.api.common.experimental import delete_dag
from airflow.exceptions import DagNotFound, DagFileExists
dag_id = request.args.get('dag_id')
origin = request.args.get('origin') or "/"
try:
delete_dag.delete_dag(dag_id)
except DagNotFound:
flash("DAG with id {} not found. Cannot delete".format(dag_id), 'error')
return redirect(request.referrer)
except DagFileExists:
flash("Dag id {} is still in DagBag. "
"Remove the DAG file first.".format(dag_id),
'error')
return redirect(request.referrer)
flash("Deleting DAG with id {}. May take a couple minutes to fully"
" disappear.".format(dag_id))
# Upon success return to origin.
return redirect(origin)
@expose('/trigger')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def trigger(self):
dag_id = request.args.get('dag_id')
origin = request.args.get('origin') or "/"
dag = dagbag.get_dag(dag_id)
if not dag:
flash("Cannot find dag {}".format(dag_id))
return redirect(origin)
execution_date = timezone.utcnow()
run_id = "manual__{0}".format(execution_date.isoformat())
dr = DagRun.find(dag_id=dag_id, run_id=run_id)
if dr:
flash("This run_id {} already exists".format(run_id))
return redirect(origin)
run_conf = {}
dag.create_dagrun(
run_id=run_id,
execution_date=execution_date,
state=State.RUNNING,
conf=run_conf,
external_trigger=True
)
flash(
"Triggered {}, "
"it should start any moment now.".format(dag_id))
return redirect(origin)
def _clear_dag_tis(self, dag, start_date, end_date, origin,
recursive=False, confirmed=False):
if confirmed:
count = dag.clear(
start_date=start_date,
end_date=end_date,
include_subdags=recursive,
include_parentdag=recursive,
)
flash("{0} task instances have been cleared".format(count))
return redirect(origin)
tis = dag.clear(
start_date=start_date,
end_date=end_date,
include_subdags=recursive,
include_parentdag=recursive,
dry_run=True,
)
if not tis:
flash("No task instances to clear", 'error')
response = redirect(origin)
else:
details = "\n".join([str(t) for t in tis])
response = self.render(
'airflow/confirm.html',
message=("Here's the list of task instances you are about "
"to clear:"),
details=details)
return response
@expose('/clear')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def clear(self):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
origin = request.args.get('origin')
dag = dagbag.get_dag(dag_id)
execution_date = request.args.get('execution_date')
execution_date = pendulum.parse(execution_date)
confirmed = request.args.get('confirmed') == "true"
upstream = request.args.get('upstream') == "true"
downstream = request.args.get('downstream') == "true"
future = request.args.get('future') == "true"
past = request.args.get('past') == "true"
recursive = request.args.get('recursive') == "true"
dag = dag.sub_dag(
task_regex=r"^{0}$".format(task_id),
include_downstream=downstream,
include_upstream=upstream)
end_date = execution_date if not future else None
start_date = execution_date if not past else None
return self._clear_dag_tis(dag, start_date, end_date, origin,
recursive=recursive, confirmed=confirmed)
@expose('/dagrun_clear')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_clear(self):
dag_id = request.args.get('dag_id')
origin = request.args.get('origin')
execution_date = request.args.get('execution_date')
confirmed = request.args.get('confirmed') == "true"
dag = dagbag.get_dag(dag_id)
execution_date = pendulum.parse(execution_date)
start_date = execution_date
end_date = execution_date
return self._clear_dag_tis(dag, start_date, end_date, origin,
recursive=True, confirmed=confirmed)
@expose('/blocked')
@has_access
@provide_session
def blocked(self, session=None):
DR = models.DagRun
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
payload = []
if filter_dag_ids:
dags = (
session.query(DR.dag_id, sqla.func.count(DR.id))
.filter(DR.state == State.RUNNING)
.group_by(DR.dag_id)
)
if 'all_dags' not in filter_dag_ids:
dags = dags.filter(DR.dag_id.in_(filter_dag_ids))
dags = dags.all()
for dag_id, active_dag_runs in dags:
max_active_runs = 0
if dag_id in dagbag.dags:
max_active_runs = dagbag.dags[dag_id].max_active_runs
payload.append({
'dag_id': dag_id,
'active_dag_run': active_dag_runs,
'max_active_runs': max_active_runs,
})
return wwwutils.json_response(payload)
def _mark_dagrun_state_as_failed(self, dag_id, execution_date, confirmed, origin):
if not execution_date:
flash('Invalid execution date', 'error')
return redirect(origin)
execution_date = pendulum.parse(execution_date)
dag = dagbag.get_dag(dag_id)
if not dag:
flash('Cannot find DAG: {}'.format(dag_id), 'error')
return redirect(origin)
new_dag_state = set_dag_run_state_to_failed(dag, execution_date, commit=confirmed)
if confirmed:
flash('Marked failed on {} task instances'.format(len(new_dag_state)))
return redirect(origin)
else:
details = '\n'.join([str(t) for t in new_dag_state])
response = self.render('airflow/confirm.html',
message=("Here's the list of task instances you are "
"about to mark as failed"),
details=details)
return response
def _mark_dagrun_state_as_success(self, dag_id, execution_date, confirmed, origin):
if not execution_date:
flash('Invalid execution date', 'error')
return redirect(origin)
execution_date = pendulum.parse(execution_date)
dag = dagbag.get_dag(dag_id)
if not dag:
flash('Cannot find DAG: {}'.format(dag_id), 'error')
return redirect(origin)
new_dag_state = set_dag_run_state_to_success(dag, execution_date,
commit=confirmed)
if confirmed:
flash('Marked success on {} task instances'.format(len(new_dag_state)))
return redirect(origin)
else:
details = '\n'.join([str(t) for t in new_dag_state])
response = self.render('airflow/confirm.html',
message=("Here's the list of task instances you are "
"about to mark as success"),
details=details)
return response
@expose('/dagrun_failed')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_failed(self):
dag_id = request.args.get('dag_id')
execution_date = request.args.get('execution_date')
confirmed = request.args.get('confirmed') == 'true'
origin = request.args.get('origin')
return self._mark_dagrun_state_as_failed(dag_id, execution_date,
confirmed, origin)
@expose('/dagrun_success')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def dagrun_success(self):
dag_id = request.args.get('dag_id')
execution_date = request.args.get('execution_date')
confirmed = request.args.get('confirmed') == 'true'
origin = request.args.get('origin')
return self._mark_dagrun_state_as_success(dag_id, execution_date,
confirmed, origin)
def _mark_task_instance_state(self, dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, state):
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
task.dag = dag
execution_date = pendulum.parse(execution_date)
if not dag:
flash("Cannot find DAG: {}".format(dag_id))
return redirect(origin)
if not task:
flash("Cannot find task {} in DAG {}".format(task_id, dag.dag_id))
return redirect(origin)
from airflow.api.common.experimental.mark_tasks import set_state
if confirmed:
altered = set_state(task=task, execution_date=execution_date,
upstream=upstream, downstream=downstream,
future=future, past=past, state=state,
commit=True)
flash("Marked {} on {} task instances".format(state, len(altered)))
return redirect(origin)
to_be_altered = set_state(task=task, execution_date=execution_date,
upstream=upstream, downstream=downstream,
future=future, past=past, state=state,
commit=False)
details = "\n".join([str(t) for t in to_be_altered])
response = self.render("airflow/confirm.html",
message=("Here's the list of task instances you are "
"about to mark as {}:".format(state)),
details=details)
return response
@expose('/failed')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def failed(self):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
origin = request.args.get('origin')
execution_date = request.args.get('execution_date')
confirmed = request.args.get('confirmed') == "true"
upstream = request.args.get('upstream') == "true"
downstream = request.args.get('downstream') == "true"
future = request.args.get('future') == "true"
past = request.args.get('past') == "true"
return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, State.FAILED)
@expose('/success')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
def success(self):
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
origin = request.args.get('origin')
execution_date = request.args.get('execution_date')
confirmed = request.args.get('confirmed') == "true"
upstream = request.args.get('upstream') == "true"
downstream = request.args.get('downstream') == "true"
future = request.args.get('future') == "true"
past = request.args.get('past') == "true"
return self._mark_task_instance_state(dag_id, task_id, origin, execution_date,
confirmed, upstream, downstream,
future, past, State.SUCCESS)
@expose('/tree')
@has_dag_access(can_dag_read=True)
@has_access
@gzipped
@action_logging
@provide_session
def tree(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
blur = conf.getboolean('webserver', 'demo_mode')
dag = dagbag.get_dag(dag_id)
if dag_id not in dagbag.dags:
flash('DAG "{0}" seems to be missing.'.format(dag_id), "error")
return redirect('/')
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_downstream=False,
include_upstream=True)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if base_date:
base_date = timezone.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
DR = models.DagRun
dag_runs = (
session.query(DR)
.filter(
DR.dag_id == dag.dag_id,
DR.execution_date <= base_date)
.order_by(DR.execution_date.desc())
.limit(num_runs)
.all()
)
dag_runs = {
dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs}
dates = sorted(list(dag_runs.keys()))
max_date = max(dates) if dates else None
min_date = min(dates) if dates else None
tis = dag.get_task_instances(
session, start_date=min_date, end_date=base_date)
task_instances = {}
for ti in tis:
tid = alchemy_to_dict(ti)
dr = dag_runs.get(ti.execution_date)
tid['external_trigger'] = dr['external_trigger'] if dr else False
task_instances[(ti.task_id, ti.execution_date)] = tid
expanded = []
# The default recursion traces every path so that tree view has full
# expand/collapse functionality. After 5,000 nodes we stop and fall
# back on a quick DFS search for performance. See PR #320.
node_count = [0]
node_limit = 5000 / max(1, len(dag.roots))
def recurse_nodes(task, visited):
visited.add(task)
node_count[0] += 1
children = [
recurse_nodes(t, visited) for t in task.upstream_list
if node_count[0] < node_limit or t not in visited]
# D3 tree uses children vs _children to define what is
# expanded or not. The following block makes it such that
# repeated nodes are collapsed by default.
children_key = 'children'
if task.task_id not in expanded:
expanded.append(task.task_id)
elif children:
children_key = "_children"
def set_duration(tid):
if (isinstance(tid, dict) and tid.get("state") == State.RUNNING and
tid["start_date"] is not None):
d = timezone.utcnow() - pendulum.parse(tid["start_date"])
tid["duration"] = d.total_seconds()
return tid
return {
'name': task.task_id,
'instances': [
set_duration(task_instances.get((task.task_id, d))) or {
'execution_date': d.isoformat(),
'task_id': task.task_id
}
for d in dates],
children_key: children,
'num_dep': len(task.upstream_list),
'operator': task.task_type,
'retries': task.retries,
'owner': task.owner,
'start_date': task.start_date,
'end_date': task.end_date,
'depends_on_past': task.depends_on_past,
'ui_color': task.ui_color,
}
data = {
'name': '[DAG]',
'children': [recurse_nodes(t, set()) for t in dag.roots],
'instances': [
dag_runs.get(d) or {'execution_date': d.isoformat()}
for d in dates],
}
# minimize whitespace as this can be huge for bigger dags
data = json.dumps(data, default=json_ser, separators=(',', ':'))
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
return self.render(
'airflow/tree.html',
operators=sorted(
list(set([op.__class__ for op in dag.tasks])),
key=lambda x: x.__name__
),
root=root,
form=form,
dag=dag, data=data, blur=blur, num_runs=num_runs)
@expose('/graph')
@has_dag_access(can_dag_read=True)
@has_access
@gzipped
@action_logging
@provide_session
def graph(self, session=None):
dag_id = request.args.get('dag_id')
blur = conf.getboolean('webserver', 'demo_mode')
dag = dagbag.get_dag(dag_id)
if dag_id not in dagbag.dags:
flash('DAG "{0}" seems to be missing.'.format(dag_id), "error")
return redirect('/')
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
arrange = request.args.get('arrange', dag.orientation)
nodes = []
edges = []
for task in dag.tasks:
nodes.append({
'id': task.task_id,
'value': {
'label': task.task_id,
'labelStyle': "fill:{0};".format(task.ui_fgcolor),
'style': "fill:{0};".format(task.ui_color),
'rx': 5,
'ry': 5,
}
})
def get_upstream(task):
for t in task.upstream_list:
edge = {
'u': t.task_id,
'v': task.task_id,
}
if edge not in edges:
edges.append(edge)
get_upstream(t)
for t in dag.roots:
get_upstream(t)
dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)
dt_nr_dr_data['arrange'] = arrange
dttm = dt_nr_dr_data['dttm']
class GraphForm(DateTimeWithNumRunsWithDagRunsForm):
arrange = SelectField("Layout", choices=(
('LR', "Left->Right"),
('RL', "Right->Left"),
('TB', "Top->Bottom"),
('BT', "Bottom->Top"),
))
form = GraphForm(data=dt_nr_dr_data)
form.execution_date.choices = dt_nr_dr_data['dr_choices']
task_instances = {
ti.task_id: alchemy_to_dict(ti)
for ti in dag.get_task_instances(session, dttm, dttm)}
tasks = {
t.task_id: {
'dag_id': t.dag_id,
'task_type': t.task_type,
}
for t in dag.tasks}
if not tasks:
flash("No tasks found", "error")
session.commit()
doc_md = markdown.markdown(dag.doc_md) \
if hasattr(dag, 'doc_md') and dag.doc_md else ''
return self.render(
'airflow/graph.html',
dag=dag,
form=form,
width=request.args.get('width', "100%"),
height=request.args.get('height', "800"),
execution_date=dttm.isoformat(),
state_token=wwwutils.state_token(dt_nr_dr_data['dr_state']),
doc_md=doc_md,
arrange=arrange,
operators=sorted(
list(set([op.__class__ for op in dag.tasks])),
key=lambda x: x.__name__
),
blur=blur,
root=root or '',
task_instances=json.dumps(task_instances, indent=2),
tasks=json.dumps(tasks, indent=2),
nodes=json.dumps(nodes, indent=2),
edges=json.dumps(edges, indent=2), )
@expose('/duration')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def duration(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if dag is None:
flash('DAG "{0}" seems to be missing.'.format(dag_id), "error")
return redirect('/')
if base_date:
base_date = pendulum.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, height=chart_height, width="1200")
cum_chart = nvd3.lineChart(
name="cumLineChart", x_is_date=True, height=chart_height, width="1200")
y = defaultdict(list)
x = defaultdict(list)
cum_y = defaultdict(list)
tis = dag.get_task_instances(
session, start_date=min_date, end_date=base_date)
TF = models.TaskFail
ti_fails = (
session.query(TF)
.filter(TF.dag_id == dag.dag_id, # noqa
TF.execution_date >= min_date,
TF.execution_date <= base_date,
TF.task_id.in_([t.task_id for t in dag.tasks]))
.all() # noqa
)
fails_totals = defaultdict(int)
for tf in ti_fails:
dict_key = (tf.dag_id, tf.task_id, tf.execution_date)
fails_totals[dict_key] += tf.duration
for ti in tis:
if ti.duration:
dttm = wwwutils.epoch(ti.execution_date)
x[ti.task_id].append(dttm)
y[ti.task_id].append(float(ti.duration))
fails_dict_key = (ti.dag_id, ti.task_id, ti.execution_date)
fails_total = fails_totals[fails_dict_key]
cum_y[ti.task_id].append(float(ti.duration + fails_total))
# determine the most relevant time unit for the set of task instance
# durations for the DAG
y_unit = infer_time_unit([d for t in y.values() for d in t])
cum_y_unit = infer_time_unit([d for t in cum_y.values() for d in t])
# update the y Axis on both charts to have the correct time units
chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Duration ({})'.format(y_unit))
chart.axislist['yAxis']['axisLabelDistance'] = '40'
cum_chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Duration ({})'.format(cum_y_unit))
cum_chart.axislist['yAxis']['axisLabelDistance'] = '40'
for task in dag.tasks:
if x[task.task_id]:
chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(y[task.task_id], y_unit))
cum_chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(cum_y[task.task_id],
cum_y_unit))
dates = sorted(list({ti.execution_date for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if dates else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
cum_chart.buildcontent()
s_index = cum_chart.htmlcontent.rfind('});')
cum_chart.htmlcontent = (cum_chart.htmlcontent[:s_index] +
"$( document ).trigger('chartload')" +
cum_chart.htmlcontent[s_index:])
return self.render(
'airflow/duration_chart.html',
dag=dag,
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
chart=chart.htmlcontent,
cum_chart=cum_chart.htmlcontent
)
@expose('/tries')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def tries(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if base_date:
base_date = pendulum.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, y_axis_format='d', height=chart_height,
width="1200")
for task in dag.tasks:
y = []
x = []
for ti in task.get_task_instances(session, start_date=min_date,
end_date=base_date):
dttm = wwwutils.epoch(ti.execution_date)
x.append(dttm)
y.append(ti.try_number)
if x:
chart.add_serie(name=task.task_id, x=x, y=y)
tis = dag.get_task_instances(
session, start_date=min_date, end_date=base_date)
tries = sorted(list({ti.try_number for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if tries else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
return self.render(
'airflow/chart.html',
dag=dag,
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
chart=chart.htmlcontent
)
@expose('/landing_times')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def landing_times(self, session=None):
default_dag_run = conf.getint('webserver', 'default_dag_run_display_number')
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
base_date = request.args.get('base_date')
num_runs = request.args.get('num_runs')
num_runs = int(num_runs) if num_runs else default_dag_run
if base_date:
base_date = pendulum.parse(base_date)
else:
base_date = dag.latest_execution_date or timezone.utcnow()
dates = dag.date_range(base_date, num=-abs(num_runs))
min_date = dates[0] if dates else timezone.utc_epoch()
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
chart_height = wwwutils.get_chart_height(dag)
chart = nvd3.lineChart(
name="lineChart", x_is_date=True, height=chart_height, width="1200")
y = {}
x = {}
for task in dag.tasks:
y[task.task_id] = []
x[task.task_id] = []
for ti in task.get_task_instances(session, start_date=min_date,
end_date=base_date):
ts = ti.execution_date
if dag.schedule_interval and dag.following_schedule(ts):
ts = dag.following_schedule(ts)
if ti.end_date:
dttm = wwwutils.epoch(ti.execution_date)
secs = (ti.end_date - ts).total_seconds()
x[ti.task_id].append(dttm)
y[ti.task_id].append(secs)
# determine the most relevant time unit for the set of landing times
# for the DAG
y_unit = infer_time_unit([d for t in y.values() for d in t])
# update the y Axis to have the correct time units
chart.create_y_axis('yAxis', format='.02f', custom_format=False,
label='Landing Time ({})'.format(y_unit))
chart.axislist['yAxis']['axisLabelDistance'] = '40'
for task in dag.tasks:
if x[task.task_id]:
chart.add_serie(name=task.task_id, x=x[task.task_id],
y=scale_time_units(y[task.task_id], y_unit))
tis = dag.get_task_instances(
session, start_date=min_date, end_date=base_date)
dates = sorted(list({ti.execution_date for ti in tis}))
max_date = max([ti.execution_date for ti in tis]) if dates else None
session.commit()
form = DateTimeWithNumRunsForm(data={'base_date': max_date,
'num_runs': num_runs})
chart.buildcontent()
return self.render(
'airflow/chart.html',
dag=dag,
chart=chart.htmlcontent,
height=str(chart_height + 100) + "px",
demo_mode=conf.getboolean('webserver', 'demo_mode'),
root=root,
form=form,
)
@expose('/paused', methods=['POST'])
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
@provide_session
def paused(self, session=None):
DagModel = models.DagModel
dag_id = request.args.get('dag_id')
orm_dag = (
session.query(DagModel)
.filter(DagModel.dag_id == dag_id).first()
)
if request.args.get('is_paused') == 'false':
orm_dag.is_paused = True
else:
orm_dag.is_paused = False
session.merge(orm_dag)
session.commit()
dagbag.get_dag(dag_id)
return "OK"
@expose('/refresh')
@has_dag_access(can_dag_edit=True)
@has_access
@action_logging
@provide_session
def refresh(self, session=None):
DagModel = models.DagModel
dag_id = request.args.get('dag_id')
orm_dag = session.query(
DagModel).filter(DagModel.dag_id == dag_id).first()
if orm_dag:
orm_dag.last_expired = timezone.utcnow()
session.merge(orm_dag)
session.commit()
# sync dag permission
appbuilder.sm.sync_perm_for_dag(dag_id)
models.DagStat.update([dag_id], session=session, dirty_only=False)
dagbag.get_dag(dag_id)
flash("DAG [{}] is now fresh as a daisy".format(dag_id))
return redirect(request.referrer)
@expose('/refresh_all')
@has_access
@action_logging
def refresh_all(self):
dagbag.collect_dags(only_if_updated=False)
# sync permissions for all dags
appbuilder.sm.sync_perm_for_dag()
flash("All DAGs are now up to date")
return redirect('/')
@expose('/gantt')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def gantt(self, session=None):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
demo_mode = conf.getboolean('webserver', 'demo_mode')
root = request.args.get('root')
if root:
dag = dag.sub_dag(
task_regex=root,
include_upstream=True,
include_downstream=False)
dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)
dttm = dt_nr_dr_data['dttm']
form = DateTimeWithNumRunsWithDagRunsForm(data=dt_nr_dr_data)
form.execution_date.choices = dt_nr_dr_data['dr_choices']
tis = [
ti for ti in dag.get_task_instances(session, dttm, dttm)
if ti.start_date]
tis = sorted(tis, key=lambda ti: ti.start_date)
TF = models.TaskFail
ti_fails = list(itertools.chain(*[(
session
.query(TF)
.filter(TF.dag_id == ti.dag_id,
TF.task_id == ti.task_id,
TF.execution_date == ti.execution_date)
.all()
) for ti in tis]))
TR = models.TaskReschedule
ti_reschedules = list(itertools.chain(*[(
session
.query(TR)
.filter(TR.dag_id == ti.dag_id,
TR.task_id == ti.task_id,
TR.execution_date == ti.execution_date)
.all()
) for ti in tis]))
# determine bars to show in the gantt chart
# all reschedules of one attempt are combinded into one bar
gantt_bar_items = []
for task_id, items in itertools.groupby(
sorted(tis + ti_fails + ti_reschedules, key=lambda ti: ti.task_id),
key=lambda ti: ti.task_id):
start_date = None
for i in sorted(items, key=lambda ti: ti.start_date):
start_date = start_date or i.start_date
end_date = i.end_date or timezone.utcnow()
if type(i) == models.TaskInstance:
gantt_bar_items.append((task_id, start_date, end_date, i.state))
start_date = None
elif type(i) == TF and (len(gantt_bar_items) == 0 or
end_date != gantt_bar_items[-1][2]):
gantt_bar_items.append((task_id, start_date, end_date, State.FAILED))
start_date = None
tasks = []
for gantt_bar_item in gantt_bar_items:
task_id = gantt_bar_item[0]
start_date = gantt_bar_item[1]
end_date = gantt_bar_item[2]
state = gantt_bar_item[3]
tasks.append({
'startDate': wwwutils.epoch(start_date),
'endDate': wwwutils.epoch(end_date),
'isoStart': start_date.isoformat()[:-4],
'isoEnd': end_date.isoformat()[:-4],
'taskName': task_id,
'duration': "{}".format(end_date - start_date)[:-4],
'status': state,
'executionDate': dttm.isoformat(),
})
states = {task['status']: task['status'] for task in tasks}
data = {
'taskNames': [ti.task_id for ti in tis],
'tasks': tasks,
'taskStatus': states,
'height': len(tis) * 25 + 25,
}
session.commit()
return self.render(
'airflow/gantt.html',
dag=dag,
execution_date=dttm.isoformat(),
form=form,
data=json.dumps(data, indent=2),
base_date='',
demo_mode=demo_mode,
root=root,
)
@expose('/object/task_instances')
@has_dag_access(can_dag_read=True)
@has_access
@action_logging
@provide_session
def task_instances(self, session=None):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
dttm = request.args.get('execution_date')
if dttm:
dttm = pendulum.parse(dttm)
else:
return "Error: Invalid execution_date"
task_instances = {
ti.task_id: alchemy_to_dict(ti)
for ti in dag.get_task_instances(session, dttm, dttm)}
return json.dumps(task_instances)
class VersionView(AirflowBaseView):
@expose('/version')
@has_access
def version(self):
try:
airflow_version = airflow.__version__
except Exception as e:
airflow_version = None
logging.error(e)
# Get the Git repo and git hash
git_version = None
try:
with open(os.path.join(*[settings.AIRFLOW_HOME,
'airflow', 'git_version'])) as f:
git_version = f.readline()
except Exception as e:
logging.error(e)
# Render information
title = "Version Info"
return self.render('airflow/version.html',
title=title,
airflow_version=airflow_version,
git_version=git_version)
class ConfigurationView(AirflowBaseView):
@expose('/configuration')
@has_access
def conf(self):
raw = request.args.get('raw') == "true"
title = "Airflow Configuration"
subtitle = conf.AIRFLOW_CONFIG
# Don't show config when expose_config variable is False in airflow config
if conf.getboolean("webserver", "expose_config"):
with open(conf.AIRFLOW_CONFIG, 'r') as f:
config = f.read()
table = [(section, key, value, source)
for section, parameters in conf.as_dict(True, True).items()
for key, (value, source) in parameters.items()]
else:
config = (
"# Your Airflow administrator chose not to expose the "
"configuration, most likely for security reasons.")
table = None
if raw:
return Response(
response=config,
status=200,
mimetype="application/text")
else:
code_html = Markup(highlight(
config,
lexers.IniLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
return self.render(
'airflow/config.html',
pre_subtitle=settings.HEADER + " v" + airflow.__version__,
code_html=code_html, title=title, subtitle=subtitle,
table=table)
######################################################################################
# ModelViews
######################################################################################
class DagFilter(BaseFilter):
def apply(self, query, func): # noqa
if appbuilder.sm.has_all_dags_access():
return query
filter_dag_ids = appbuilder.sm.get_accessible_dag_ids()
return query.filter(self.model.dag_id.in_(filter_dag_ids))
class AirflowModelView(ModelView):
list_widget = AirflowModelListWidget
page_size = PAGE_SIZE
CustomSQLAInterface = wwwutils.CustomSQLAInterface
class SlaMissModelView(AirflowModelView):
route_base = '/slamiss'
datamodel = AirflowModelView.CustomSQLAInterface(models.SlaMiss)
base_permissions = ['can_list']
list_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
add_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
edit_columns = ['dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp']
search_columns = ['dag_id', 'task_id', 'email_sent', 'timestamp', 'execution_date']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'task_id': wwwutils.task_instance_link,
'execution_date': wwwutils.datetime_f('execution_date'),
'timestamp': wwwutils.datetime_f('timestamp'),
'dag_id': wwwutils.dag_link,
}
class XComModelView(AirflowModelView):
route_base = '/xcom'
datamodel = AirflowModelView.CustomSQLAInterface(models.XCom)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
search_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id']
list_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id']
add_columns = ['key', 'value', 'execution_date', 'task_id', 'dag_id']
edit_columns = ['key', 'value', 'execution_date', 'task_id', 'dag_id']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
@action('muldelete', 'Delete', "Are you sure you want to delete selected records?",
single=False)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
class ConnectionModelView(AirflowModelView):
route_base = '/connection'
datamodel = AirflowModelView.CustomSQLAInterface(models.Connection)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
extra_fields = ['extra__jdbc__drv_path', 'extra__jdbc__drv_clsname',
'extra__google_cloud_platform__project',
'extra__google_cloud_platform__key_path',
'extra__google_cloud_platform__keyfile_dict',
'extra__google_cloud_platform__scope']
list_columns = ['conn_id', 'conn_type', 'host', 'port', 'is_encrypted',
'is_extra_encrypted']
add_columns = edit_columns = ['conn_id', 'conn_type', 'host', 'schema',
'login', 'password', 'port', 'extra'] + extra_fields
add_form = edit_form = ConnectionForm
add_template = 'airflow/conn_create.html'
edit_template = 'airflow/conn_edit.html'
base_order = ('conn_id', 'asc')
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
@has_dag_access(can_dag_edit=True)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
def process_form(self, form, is_created):
formdata = form.data
if formdata['conn_type'] in ['jdbc', 'google_cloud_platform']:
extra = {
key: formdata[key]
for key in self.extra_fields if key in formdata}
form.extra.data = json.dumps(extra)
def prefill_form(self, form, pk):
try:
d = json.loads(form.data.get('extra', '{}'))
except Exception:
d = {}
if not hasattr(d, 'get'):
logging.warning('extra field for {} is not iterable'.format(
form.data.get('conn_id', '<unknown>')))
return
for field in self.extra_fields:
value = d.get(field, '')
if value:
field = getattr(form, field)
field.data = value
class PoolModelView(AirflowModelView):
route_base = '/pool'
datamodel = AirflowModelView.CustomSQLAInterface(models.Pool)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete']
list_columns = ['pool', 'slots', 'used_slots', 'queued_slots']
add_columns = ['pool', 'slots', 'description']
edit_columns = ['pool', 'slots', 'description']
base_order = ('pool', 'asc')
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
def pool_link(attr):
pool_id = attr.get('pool')
if pool_id is not None:
url = '/taskinstance/list/?_flt_3_pool=' + str(pool_id)
return Markup("<a href='{url}'>{pool_id}</a>".format(**locals()))
else:
return Markup('<span class="label label-danger">Invalid</span>')
def fused_slots(attr):
pool_id = attr.get('pool')
used_slots = attr.get('used_slots')
if pool_id is not None and used_slots is not None:
url = '/taskinstance/list/?_flt_3_pool=' + str(pool_id) + \
'&_flt_3_state=running'
return Markup("<a href='{url}'>{used_slots}</a>".format(**locals()))
else:
return Markup('<span class="label label-danger">Invalid</span>')
def fqueued_slots(attr):
pool_id = attr.get('pool')
queued_slots = attr.get('queued_slots')
if pool_id is not None and queued_slots is not None:
url = '/taskinstance/list/?_flt_3_pool=' + str(pool_id) + \
'&_flt_3_state=queued'
return Markup("<a href='{url}'>{queued_slots}</a>".format(**locals()))
else:
return Markup('<span class="label label-danger">Invalid</span>')
formatters_columns = {
'pool': pool_link,
'used_slots': fused_slots,
'queued_slots': fqueued_slots
}
validators_columns = {
'pool': [validators.DataRequired()],
'slots': [validators.NumberRange(min=0)]
}
class VariableModelView(AirflowModelView):
route_base = '/variable'
list_template = 'airflow/variable_list.html'
datamodel = AirflowModelView.CustomSQLAInterface(models.Variable)
base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete', 'can_varimport']
list_columns = ['key', 'val', 'is_encrypted']
add_columns = ['key', 'val', 'is_encrypted']
edit_columns = ['key', 'val']
search_columns = ['key', 'val']
base_order = ('key', 'asc')
def hidden_field_formatter(attr):
key = attr.get('key')
val = attr.get('val')
if wwwutils.should_hide_value_for_key(key):
return Markup('*' * 8)
if val:
return val
else:
return Markup('<span class="label label-danger">Invalid</span>')
formatters_columns = {
'val': hidden_field_formatter,
}
validators_columns = {
'key': [validators.DataRequired()]
}
def prefill_form(self, form, id):
if wwwutils.should_hide_value_for_key(form.key.data):
form.val.data = '*' * 8
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
@action('varexport', 'Export', '', single=False)
def action_varexport(self, items):
var_dict = {}
d = json.JSONDecoder()
for var in items:
try:
val = d.decode(var.val)
except Exception:
val = var.val
var_dict[var.key] = val
response = make_response(json.dumps(var_dict, sort_keys=True, indent=4))
response.headers["Content-Disposition"] = "attachment; filename=variables.json"
return response
@expose('/varimport', methods=["POST"])
@has_access
@action_logging
def varimport(self):
try:
out = request.files['file'].read()
if not PY2 and isinstance(out, bytes):
d = json.loads(out.decode('utf-8'))
else:
d = json.loads(out)
except Exception:
flash("Missing file or syntax error.", 'error')
else:
suc_count = fail_count = 0
for k, v in d.items():
try:
models.Variable.set(k, v, serialize_json=isinstance(v, dict))
except Exception as e:
logging.info('Variable import failed: {}'.format(repr(e)))
fail_count += 1
else:
suc_count += 1
flash("{} variable(s) successfully updated.".format(suc_count))
if fail_count:
flash("{} variable(s) failed to be updated.".format(fail_count), 'error')
self.update_redirect()
return redirect(self.get_redirect())
class JobModelView(AirflowModelView):
route_base = '/job'
datamodel = AirflowModelView.CustomSQLAInterface(jobs.BaseJob)
base_permissions = ['can_list']
list_columns = ['id', 'dag_id', 'state', 'job_type', 'start_date',
'end_date', 'latest_heartbeat',
'executor_class', 'hostname', 'unixname']
search_columns = ['id', 'dag_id', 'state', 'job_type', 'start_date',
'end_date', 'latest_heartbeat', 'executor_class',
'hostname', 'unixname']
base_order = ('start_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'start_date': wwwutils.datetime_f('start_date'),
'end_date': wwwutils.datetime_f('end_date'),
'hostname': wwwutils.nobr_f('hostname'),
'state': wwwutils.state_f,
'latest_heartbeat': wwwutils.datetime_f('latest_heartbeat'),
}
class DagRunModelView(AirflowModelView):
route_base = '/dagrun'
datamodel = AirflowModelView.CustomSQLAInterface(models.DagRun)
base_permissions = ['can_list']
list_columns = ['state', 'dag_id', 'execution_date', 'run_id', 'external_trigger']
search_columns = ['state', 'dag_id', 'execution_date', 'run_id', 'external_trigger']
base_order = ('execution_date', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
add_form = edit_form = DagRunForm
formatters_columns = {
'execution_date': wwwutils.datetime_f('execution_date'),
'state': wwwutils.state_f,
'start_date': wwwutils.datetime_f('start_date'),
'dag_id': wwwutils.dag_link,
'run_id': wwwutils.dag_run_link,
}
validators_columns = {
'dag_id': [validators.DataRequired()]
}
@action('muldelete', "Delete", "Are you sure you want to delete selected records?",
single=False)
@has_dag_access(can_dag_edit=True)
@provide_session
def action_muldelete(self, items, session=None):
self.datamodel.delete_all(items)
self.update_redirect()
dirty_ids = []
for item in items:
dirty_ids.append(item.dag_id)
models.DagStat.update(dirty_ids, dirty_only=False, session=session)
return redirect(self.get_redirect())
@action('set_running', "Set state to 'running'", '', single=False)
@provide_session
def action_set_running(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
dr.start_date = timezone.utcnow()
dr.state = State.RUNNING
models.DagStat.update(dirty_ids, session=session)
session.commit()
flash("{count} dag runs were set to running".format(**locals()))
except Exception as ex:
flash(str(ex), 'error')
flash('Failed to set state', 'error')
return redirect(self.route_base + '/list')
@action('set_failed', "Set state to 'failed'",
"All running task instances would also be marked as failed, are you sure?",
single=False)
@provide_session
def action_set_failed(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
altered_tis = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
altered_tis += \
set_dag_run_state_to_failed(dagbag.get_dag(dr.dag_id),
dr.execution_date,
commit=True,
session=session)
models.DagStat.update(dirty_ids, session=session)
altered_ti_count = len(altered_tis)
flash(
"{count} dag runs and {altered_ti_count} task instances "
"were set to failed".format(**locals()))
except Exception as ex:
flash('Failed to set state', 'error')
return redirect(self.route_base + '/list')
@action('set_success', "Set state to 'success'",
"All task instances would also be marked as success, are you sure?",
single=False)
@provide_session
def action_set_success(self, drs, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
altered_tis = []
for dr in session.query(DR).filter(
DR.id.in_([dagrun.id for dagrun in drs])).all():
dirty_ids.append(dr.dag_id)
count += 1
altered_tis += \
set_dag_run_state_to_success(dagbag.get_dag(dr.dag_id),
dr.execution_date,
commit=True,
session=session)
models.DagStat.update(dirty_ids, session=session)
altered_ti_count = len(altered_tis)
flash(
"{count} dag runs and {altered_ti_count} task instances "
"were set to success".format(**locals()))
except Exception as ex:
flash('Failed to set state', 'error')
return redirect(self.route_base + '/list')
class LogModelView(AirflowModelView):
route_base = '/log'
datamodel = AirflowModelView.CustomSQLAInterface(models.Log)
base_permissions = ['can_list']
list_columns = ['id', 'dttm', 'dag_id', 'task_id', 'event', 'execution_date',
'owner', 'extra']
search_columns = ['dag_id', 'task_id', 'execution_date', 'extra']
base_order = ('dttm', 'desc')
base_filters = [['dag_id', DagFilter, lambda: []]]
formatters_columns = {
'dttm': wwwutils.datetime_f('dttm'),
'execution_date': wwwutils.datetime_f('execution_date'),
'dag_id': wwwutils.dag_link,
}
class TaskInstanceModelView(AirflowModelView):
route_base = '/taskinstance'
datamodel = AirflowModelView.CustomSQLAInterface(models.TaskInstance)
base_permissions = ['can_list']
page_size = PAGE_SIZE
list_columns = ['state', 'dag_id', 'task_id', 'execution_date', 'operator',
'start_date', 'end_date', 'duration', 'job_id', 'hostname',
'unixname', 'priority_weight', 'queue', 'queued_dttm', 'try_number',
'pool', 'log_url']
search_columns = ['state', 'dag_id', 'task_id', 'execution_date', 'hostname',
'queue', 'pool', 'operator', 'start_date', 'end_date']
base_order = ('job_id', 'asc')
base_filters = [['dag_id', DagFilter, lambda: []]]
def log_url_formatter(attr):
log_url = attr.get('log_url')
return Markup(
'<a href="{log_url}">'
' <span class="glyphicon glyphicon-book" aria-hidden="true">'
'</span></a>').format(**locals())
def duration_f(attr):
end_date = attr.get('end_date')
duration = attr.get('duration')
if end_date and duration:
return timedelta(seconds=duration)
formatters_columns = {
'log_url': log_url_formatter,
'task_id': wwwutils.task_instance_link,
'hostname': wwwutils.nobr_f('hostname'),
'state': wwwutils.state_f,
'execution_date': wwwutils.datetime_f('execution_date'),
'start_date': wwwutils.datetime_f('start_date'),
'end_date': wwwutils.datetime_f('end_date'),
'queued_dttm': wwwutils.datetime_f('queued_dttm'),
'dag_id': wwwutils.dag_link,
'duration': duration_f,
}
@provide_session
@action('clear', lazy_gettext('Clear'),
lazy_gettext('Are you sure you want to clear the state of the selected task'
' instance(s) and set their dagruns to the running state?'),
single=False)
def action_clear(self, tis, session=None):
try:
dag_to_tis = {}
for ti in tis:
dag = dagbag.get_dag(ti.dag_id)
tis = dag_to_tis.setdefault(dag, [])
tis.append(ti)
for dag, tis in dag_to_tis.items():
models.clear_task_instances(tis, session, dag=dag)
session.commit()
flash("{0} task instances have been cleared".format(len(tis)))
self.update_redirect()
return redirect(self.get_redirect())
except Exception:
flash('Failed to clear task instances', 'error')
@provide_session
def set_task_instance_state(self, tis, target_state, session=None):
try:
count = len(tis)
for ti in tis:
ti.set_state(target_state, session)
session.commit()
flash(
"{count} task instances were set to '{target_state}'".format(**locals()))
except Exception as ex:
flash('Failed to set state', 'error')
@action('set_running', "Set state to 'running'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_running(self, tis):
self.set_task_instance_state(tis, State.RUNNING)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_failed', "Set state to 'failed'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_failed(self, tis):
self.set_task_instance_state(tis, State.FAILED)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_success', "Set state to 'success'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_success(self, tis):
self.set_task_instance_state(tis, State.SUCCESS)
self.update_redirect()
return redirect(self.get_redirect())
@action('set_retry', "Set state to 'up_for_retry'", '', single=False)
@has_dag_access(can_dag_edit=True)
def action_set_retry(self, tis):
self.set_task_instance_state(tis, State.UP_FOR_RETRY)
self.update_redirect()
return redirect(self.get_redirect())
def get_one(self, id):
"""
As a workaround for AIRFLOW-252, this method overrides Flask-Admin's
ModelView.get_one().
TODO: this method should be removed once the below bug is fixed on
Flask-Admin side. https://github.com/flask-admin/flask-admin/issues/1226
"""
task_id, dag_id, execution_date = iterdecode(id) # noqa
execution_date = pendulum.parse(execution_date)
return self.session.query(self.model).get((task_id, dag_id, execution_date))
class DagModelView(AirflowModelView):
route_base = '/dagmodel'
datamodel = AirflowModelView.CustomSQLAInterface(models.DagModel)
base_permissions = ['can_list', 'can_show']
list_columns = ['dag_id', 'is_paused', 'last_scheduler_run',
'last_expired', 'scheduler_lock', 'fileloc', 'owners']
formatters_columns = {
'dag_id': wwwutils.dag_link
}
base_filters = [['dag_id', DagFilter, lambda: []]]
def get_query(self):
"""
Default filters for model
"""
return (
super(DagModelView, self).get_query()
.filter(or_(models.DagModel.is_active,
models.DagModel.is_paused))
.filter(~models.DagModel.is_subdag)
)
def get_count_query(self):
"""
Default filters for model
"""
return (
super(DagModelView, self).get_count_query()
.filter(models.DagModel.is_active)
.filter(~models.DagModel.is_subdag)
)
| {
"content_hash": "ed9d6e11892303e7d3827618d746c8fd",
"timestamp": "",
"source": "github",
"line_count": 2411,
"max_line_length": 90,
"avg_line_length": 36.950642886768975,
"alnum_prop": 0.5419809626436781,
"repo_name": "malmiron/incubator-airflow",
"id": "49a9a734cc483ccb381ec2c3c9c35754262929a4",
"size": "89902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "airflow/www_rbac/views.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "56979"
},
{
"name": "HTML",
"bytes": "145974"
},
{
"name": "JavaScript",
"bytes": "1364212"
},
{
"name": "Mako",
"bytes": "1037"
},
{
"name": "Python",
"bytes": "1847247"
},
{
"name": "Shell",
"bytes": "19680"
}
],
"symlink_target": ""
} |
#ifndef MYTH_WORKER_PROTO_H_
#define MYTH_WORKER_PROTO_H_
#include "myth_desc.h"
static void myth_sched_loop(void);
static inline void myth_env_init(void);
static inline void myth_env_fini(void);
static inline void myth_set_current_env(myth_running_env_t e);
static inline myth_running_env_t myth_get_current_env(void);
static inline myth_running_env_t myth_env_get_first_busy(myth_running_env_t e);
static inline void myth_worker_start_ex_body(int rank);
static inline void myth_startpoint_init_ex_body(int rank);
static inline void myth_startpoint_exit_ex_body(int rank);
static void *myth_worker_thread_fn(void *args);
#endif /* MYTH_WORKER_PROTO_H_ */
| {
"content_hash": "c70446790d3fcb88abc2dceabf6f9c1a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 79,
"avg_line_length": 34.78947368421053,
"alnum_prop": 0.7609682299546142,
"repo_name": "CoryMcCartan/chapel",
"id": "170d79af8b27f048a5b9b77681d62a931e42b652",
"size": "661",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "third-party/massivethreads/massivethreads-0.95/myth_worker_proto.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2072"
},
{
"name": "C",
"bytes": "3689307"
},
{
"name": "C++",
"bytes": "3485120"
},
{
"name": "CSS",
"bytes": "919"
},
{
"name": "Chapel",
"bytes": "9776274"
},
{
"name": "Cuda",
"bytes": "4304"
},
{
"name": "Emacs Lisp",
"bytes": "14304"
},
{
"name": "FORTRAN",
"bytes": "18153"
},
{
"name": "Gnuplot",
"bytes": "5536"
},
{
"name": "HTML",
"bytes": "2419"
},
{
"name": "JavaScript",
"bytes": "50663"
},
{
"name": "LLVM",
"bytes": "16367"
},
{
"name": "Lex",
"bytes": "37600"
},
{
"name": "Makefile",
"bytes": "108034"
},
{
"name": "Mathematica",
"bytes": "4971"
},
{
"name": "Perl",
"bytes": "240159"
},
{
"name": "Python",
"bytes": "482576"
},
{
"name": "Shell",
"bytes": "171928"
},
{
"name": "TeX",
"bytes": "869966"
},
{
"name": "VimL",
"bytes": "14876"
},
{
"name": "Yacc",
"bytes": "2337"
},
{
"name": "Zimpl",
"bytes": "1115"
}
],
"symlink_target": ""
} |
Instructions
Clone the repository locally
```
$ git clone git@github.com:blalab/csv2mr.git
```
Install "requests" module
```
$ pip install requests
```
Access the repository folder
```
$ cd csv2mr
```
Place the CSV you want to import in the same folder
Run the script
```
$ python CSV2MR.py
```
Follow the instructions in the terminal
At then end you'll see the map that links the csv file with the Ring.
To-Do: Implement the part where the items are inserted into the Ring
| {
"content_hash": "45f68e565d69519da286acf7d64f7eff",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 70,
"avg_line_length": 17.814814814814813,
"alnum_prop": 0.7338877338877339,
"repo_name": "blalab/csv2mr",
"id": "2654a2a07da5a77c4e449f12473bc9815319c8e8",
"size": "499",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41156"
}
],
"symlink_target": ""
} |
using LiveSplit.Model.Comparisons;
using LiveSplit.Model.RunFactories;
using LiveSplit.Options;
using LiveSplit.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace LiveSplit.Model.RunImporters
{
public class URLRunImporter : IRunImporter
{
private IRun LoadRunFromURL(string url, Form form = null)
{
try
{
var runFactory = new StandardFormatsRunFactory();
var comparisonGeneratorsFactory = new StandardComparisonGeneratorsFactory();
var uri = new Uri(url);
if (uri.Host.ToLowerInvariant() == "splits.io"
&& uri.LocalPath.Length > 0
&& !uri.LocalPath.Substring(1).Contains('/'))
{
uri = new Uri(string.Format("{0}/download/livesplit", url));
}
if (uri.Host.ToLowerInvariant() == "ge.tt"
&& uri.LocalPath.Length > 0
&& !uri.LocalPath.Substring(1).Contains('/'))
{
uri = new Uri(string.Format("http://ge.tt/api/1/files{0}/0/blob?download", uri.LocalPath));
}
var request = WebRequest.Create(uri);
using (var stream = request.GetResponse().GetResponseStream())
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
runFactory.Stream = memoryStream;
runFactory.FilePath = null;
try
{
return runFactory.Create(comparisonGeneratorsFactory);
}
catch (Exception ex)
{
Log.Error(ex);
MessageBox.Show(form, "The selected file was not recognized as a splits file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception ex)
{
Log.Error(ex);
MessageBox.Show(form, "The splits file couldn't be downloaded.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
public IRun Import(Form form = null)
{
string url = null;
if (DialogResult.OK == InputBox.Show(form, "Open Splits from URL", "URL:", ref url))
{
return LoadRunFromURL(url, form);
}
return null;
}
public string ImportAsComparison(IRun run, Form form = null)
{
string url = null;
string name = null;
if (DialogResult.OK == InputBox.Show(form, "Import Comparison from URL", "Name:", "URL:", ref name, ref url))
{
var imported = LoadRunFromURL(url, form);
return run.AddComparisonWithNameInput(imported, name, form);
}
return null;
}
}
}
| {
"content_hash": "15228f566b4f5b47b2193a08de478a0a",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 161,
"avg_line_length": 35.880434782608695,
"alnum_prop": 0.4968191457134202,
"repo_name": "CryZe/LiveSplit",
"id": "108a3da377f7c359a256b696faf5a202495061fa",
"size": "3303",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "LiveSplit/LiveSplit.View/Model/RunImporters/URLRunImporter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "135"
},
{
"name": "C#",
"bytes": "6691987"
},
{
"name": "Java",
"bytes": "31064"
},
{
"name": "LSL",
"bytes": "6930"
},
{
"name": "PowerShell",
"bytes": "32783"
},
{
"name": "Python",
"bytes": "1990"
},
{
"name": "Scheme",
"bytes": "1202"
},
{
"name": "Visual Basic",
"bytes": "909"
}
],
"symlink_target": ""
} |
#include "tensorflow/lite/core/c/c_api.h"
#include <memory>
#include <mutex> // NOLINT
#include <utility>
#include <vector>
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/c/common_internal.h"
#include "tensorflow/lite/core/interpreter.h"
#include "tensorflow/lite/create_op_resolver.h"
#include "tensorflow/lite/delegates/interpreter_utils.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/version.h"
namespace {
class CallbackErrorReporter : public tflite::ErrorReporter {
public:
explicit CallbackErrorReporter(TfLiteErrorReporterCallback callback)
: callback_(callback) {}
int Report(const char* format, va_list args) override {
callback_.error_reporter(callback_.user_data, format, args);
return 0;
}
private:
TfLiteErrorReporterCallback callback_;
};
} // namespace
extern "C" {
// LINT.IfChange
const char* TfLiteVersion() { return TFLITE_VERSION_STRING; }
int TfLiteSchemaVersion() { return TFLITE_SCHEMA_VERSION; }
TfLiteModel* TfLiteModelCreate(const void* model_data, size_t model_size) {
auto model = tflite::FlatBufferModel::VerifyAndBuildFromBuffer(
static_cast<const char*>(model_data), model_size);
std::shared_ptr<const tflite::FlatBufferModel> shared_model(model.release());
return shared_model ? new TfLiteModel{std::move(shared_model)} : nullptr;
}
TfLiteModel* TfLiteModelCreateWithErrorReporter(
const void* model_data, size_t model_size,
void (*reporter)(void* user_data, const char* format, va_list args),
void* user_data) {
struct TfLiteErrorReporterCallback er_cb = {user_data, reporter};
auto error_reporter = std::make_unique<CallbackErrorReporter>(er_cb);
auto model = tflite::FlatBufferModel::VerifyAndBuildFromBuffer(
static_cast<const char*>(model_data), model_size, nullptr,
error_reporter.get());
std::shared_ptr<const tflite::FlatBufferModel> shared_model(model.release());
return shared_model ? new TfLiteModel{std::move(shared_model)} : nullptr;
}
TfLiteModel* TfLiteModelCreateFromFile(const char* model_path) {
auto model = tflite::FlatBufferModel::VerifyAndBuildFromFile(model_path);
std::shared_ptr<const tflite::FlatBufferModel> shared_model(model.release());
return shared_model ? new TfLiteModel{std::move(shared_model)} : nullptr;
}
TfLiteModel* TfLiteModelCreateFromFileWithErrorReporter(
const char* model_path,
void (*reporter)(void* user_data, const char* format, va_list args),
void* user_data) {
struct TfLiteErrorReporterCallback er_cb = {user_data, reporter};
auto error_reporter = std::make_unique<CallbackErrorReporter>(er_cb);
auto model = tflite::FlatBufferModel::VerifyAndBuildFromFile(
model_path, nullptr, error_reporter.get());
std::shared_ptr<const tflite::FlatBufferModel> shared_model(model.release());
return shared_model ? new TfLiteModel{std::move(shared_model)} : nullptr;
}
void TfLiteModelDelete(TfLiteModel* model) { delete model; }
TfLiteInterpreterOptions* TfLiteInterpreterOptionsCreate() {
return new TfLiteInterpreterOptions{};
}
void TfLiteInterpreterOptionsDelete(TfLiteInterpreterOptions* options) {
delete options;
}
void TfLiteInterpreterOptionsSetNumThreads(TfLiteInterpreterOptions* options,
int32_t num_threads) {
options->num_threads = num_threads;
}
void TfLiteInterpreterOptionsAddDelegate(TfLiteInterpreterOptions* options,
TfLiteDelegate* delegate) {
options->delegates.push_back(delegate);
}
void TfLiteInterpreterOptionsAddOpaqueDelegate(
TfLiteInterpreterOptions* options,
TfLiteOpaqueDelegateStruct* opaque_delegate) {
// The following cast is safe only because this code is part of the TF Lite
// runtime implementation. Apps using TF Lite should not rely on
// TfLiteOpaqueDelegateStruct and TfLiteDelegate being equivalent.
TfLiteDelegate* delegate = reinterpret_cast<TfLiteDelegate*>(opaque_delegate);
TfLiteInterpreterOptionsAddDelegate(options, delegate);
}
void TfLiteInterpreterOptionsSetErrorReporter(
TfLiteInterpreterOptions* options,
void (*reporter)(void* user_data, const char* format, va_list args),
void* user_data) {
options->error_reporter_callback.error_reporter = reporter;
options->error_reporter_callback.user_data = user_data;
}
void TfLiteInterpreterOptionsAddRegistrationExternal(
TfLiteInterpreterOptions* options,
TfLiteRegistrationExternal* registration) {
options->op_registrations.push_back(registration);
}
TfLiteStatus TfLiteInterpreterOptionsEnableCancellation(
TfLiteInterpreterOptions* options, bool enable) {
options->enable_cancellation = enable;
return kTfLiteOk;
}
static void InitTfLiteRegistration(
TfLiteRegistration* registration,
TfLiteRegistrationExternal* registration_external) {
registration->custom_name = registration_external->custom_name;
registration->version = registration_external->version;
registration->registration_external = registration_external;
}
TfLiteInterpreter* TfLiteInterpreterCreate(
const TfLiteModel* model,
const TfLiteInterpreterOptions* optional_options) {
std::unique_ptr<tflite::MutableOpResolver> resolver =
tflite::CreateOpResolver();
return tflite::internal::InterpreterCreateWithOpResolver(
model, optional_options, resolver.get());
}
void TfLiteInterpreterDelete(TfLiteInterpreter* interpreter) {
delete interpreter;
}
int32_t TfLiteInterpreterGetInputTensorCount(
const TfLiteInterpreter* interpreter) {
return static_cast<int32_t>(interpreter->impl->inputs().size());
}
const int* TfLiteInterpreterInputTensorIndices(
const TfLiteInterpreter* interpreter) {
return interpreter->impl->inputs().data();
}
TfLiteTensor* TfLiteInterpreterGetInputTensor(
const TfLiteInterpreter* interpreter, int32_t input_index) {
return interpreter->impl->tensor(interpreter->impl->inputs()[input_index]);
}
TfLiteStatus TfLiteInterpreterResizeInputTensor(TfLiteInterpreter* interpreter,
int32_t input_index,
const int* input_dims,
int32_t input_dims_size) {
std::vector<int> dims{input_dims, input_dims + input_dims_size};
return interpreter->impl->ResizeInputTensor(
interpreter->impl->inputs()[input_index], dims);
}
TfLiteStatus TfLiteInterpreterAllocateTensors(TfLiteInterpreter* interpreter) {
return interpreter->impl->AllocateTensors();
}
TfLiteStatus TfLiteInterpreterInvoke(TfLiteInterpreter* interpreter) {
if (interpreter->enable_delegate_fallback) {
return tflite::delegates::InterpreterUtils::InvokeWithCPUFallback(
interpreter->impl.get());
} else {
return interpreter->impl->Invoke();
}
}
int32_t TfLiteInterpreterGetOutputTensorCount(
const TfLiteInterpreter* interpreter) {
return static_cast<int32_t>(interpreter->impl->outputs().size());
}
TfLiteTensor* TfLiteInterpreterGetTensor(const TfLiteInterpreter* interpreter,
int index) {
return interpreter->impl->tensor(index);
}
const int* TfLiteInterpreterOutputTensorIndices(
const TfLiteInterpreter* interpreter) {
return interpreter->impl->outputs().data();
}
const TfLiteTensor* TfLiteInterpreterGetOutputTensor(
const TfLiteInterpreter* interpreter, int32_t output_index) {
return interpreter->impl->tensor(interpreter->impl->outputs()[output_index]);
}
TfLiteStatus TfLiteInterpreterCancel(const TfLiteInterpreter* interpreter) {
return interpreter->impl->Cancel();
}
TfLiteType TfLiteTensorType(const TfLiteTensor* tensor) { return tensor->type; }
int32_t TfLiteTensorNumDims(const TfLiteTensor* tensor) {
if (!tensor->dims) {
return -1;
}
return tensor->dims->size;
}
int32_t TfLiteTensorDim(const TfLiteTensor* tensor, int32_t dim_index) {
return tensor->dims->data[dim_index];
}
size_t TfLiteTensorByteSize(const TfLiteTensor* tensor) {
return tensor->bytes;
}
void* TfLiteTensorData(const TfLiteTensor* tensor) { return tensor->data.raw; }
const char* TfLiteTensorName(const TfLiteTensor* tensor) {
return tensor->name;
}
TfLiteQuantizationParams TfLiteTensorQuantizationParams(
const TfLiteTensor* tensor) {
return tensor->params;
}
TfLiteStatus TfLiteTensorCopyFromBuffer(TfLiteTensor* tensor,
const void* input_data,
size_t input_data_size) {
if (tensor->bytes != input_data_size) {
return kTfLiteError;
}
memcpy(tensor->data.raw, input_data, input_data_size);
return kTfLiteOk;
}
TfLiteStatus TfLiteTensorCopyToBuffer(const TfLiteTensor* tensor,
void* output_data,
size_t output_data_size) {
if (tensor->bytes != output_data_size) {
return kTfLiteError;
}
memcpy(output_data, tensor->data.raw, output_data_size);
return kTfLiteOk;
}
TfLiteRegistrationExternal* TfLiteRegistrationExternalCreate(
TfLiteBuiltinOperator builtin_code, const char* custom_name, int version) {
return new TfLiteRegistrationExternal{
custom_name, version, nullptr, nullptr, nullptr, nullptr, builtin_code};
}
void TfLiteRegistrationExternalDelete(TfLiteRegistrationExternal* reg) {
delete reg;
}
void TfLiteRegistrationExternalSetInit(
TfLiteRegistrationExternal* registration,
void* (*init)(TfLiteOpaqueContext* context, const char* buffer,
size_t length)) {
// Note, we expect the caller of 'registration->init' to supply as 'data' what
// we store in 'registration->init_data'.
registration->init = [](void* data, TfLiteOpaqueContext* context,
const char* buffer, size_t length) -> void* {
auto local_init = reinterpret_cast<decltype(init)>(data);
return local_init(context, buffer, length);
};
registration->init_data = reinterpret_cast<void*>(init);
}
void TfLiteRegistrationExternalSetFree(
TfLiteRegistrationExternal* registration,
void (*free)(TfLiteOpaqueContext* context, void* data)) {
// Note, we expect the caller of 'registration->free' to supply as 'data' what
// we store in 'registration->free_data'.
registration->free = [](void* free_data, TfLiteOpaqueContext* context,
void* data) {
auto local_free = reinterpret_cast<decltype(free)>(free_data);
return local_free(context, data);
};
registration->free_data = reinterpret_cast<void*>(free);
}
void TfLiteRegistrationExternalSetPrepare(
TfLiteRegistrationExternal* registration,
TfLiteStatus (*prepare)(TfLiteOpaqueContext* context,
TfLiteOpaqueNode* node)) {
// Note, we expect the caller of 'registration->prepare' to supply as
// 'data' what we store in 'registration->prepare_data'.
registration->prepare = [](void* data, TfLiteOpaqueContext* context,
TfLiteOpaqueNode* node) -> TfLiteStatus {
auto local_prepare = reinterpret_cast<decltype(prepare)>(data);
return local_prepare(context, node);
};
registration->prepare_data = reinterpret_cast<void*>(prepare);
}
void TfLiteRegistrationExternalSetInvoke(
TfLiteRegistrationExternal* registration,
TfLiteStatus (*invoke)(TfLiteOpaqueContext* context,
TfLiteOpaqueNode* node)) {
// Note, we expect the caller of 'registration->invoke' to supply as
// 'data' what we store in 'registration->invoke_data'.
registration->invoke = [](void* data, TfLiteOpaqueContext* context,
TfLiteOpaqueNode* node) -> TfLiteStatus {
auto local_invoke = reinterpret_cast<decltype(invoke)>(data);
return local_invoke(context, node);
};
registration->invoke_data = reinterpret_cast<void*>(invoke);
}
TfLiteBuiltinOperator TfLiteRegistrationExternalGetBuiltInCode(
const TfLiteRegistrationExternal* registration) {
return static_cast<TfLiteBuiltinOperator>(registration->builtin_code);
}
const char* TfLiteRegistrationExternalGetCustomName(
const TfLiteRegistrationExternal* registration) {
return registration->custom_name;
}
// LINT.ThenChange(//tensorflow/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs)
} // extern "C"
namespace tflite {
namespace internal {
// Implementation of CallbackOpResolver class which is defined in
// c_api_internal.h. CallbackOpResolver is a (C++) `tflite::OpResolver` that
// forwards the methods to (C ABI) callback functions from a
// `TfLiteOpResolverCallbacks` struct.
// FindOp for builtin op query.
const TfLiteRegistration* CallbackOpResolver::FindOp(tflite::BuiltinOperator op,
int version) const {
// Use Registration V2 API to find op.
if (op_resolver_callbacks_.find_builtin_op) {
return op_resolver_callbacks_.find_builtin_op(
op_resolver_callbacks_.user_data,
static_cast<TfLiteBuiltinOperator>(op), version);
}
if (op_resolver_callbacks_.find_builtin_op_v1) {
// Check if cached Registration is available.
std::lock_guard<std::mutex> lock(mutex_);
for (const auto& created_registration : temporary_builtin_registrations_) {
if (created_registration->builtin_code == op &&
created_registration->version == version) {
return created_registration.get();
}
}
// Get a Registration V1 object and create a Registration V2 object.
const TfLiteRegistration_V1* reg_v1 =
op_resolver_callbacks_.find_builtin_op_v1(
op_resolver_callbacks_.user_data,
static_cast<TfLiteBuiltinOperator>(op), version);
if (reg_v1) {
TfLiteRegistration* new_registration = new TfLiteRegistration();
memcpy(new_registration, reg_v1, sizeof(TfLiteRegistration_V1));
new_registration->registration_external = nullptr;
temporary_builtin_registrations_.push_back(
std::unique_ptr<TfLiteRegistration>(new_registration));
return new_registration;
}
}
return nullptr;
}
// FindOp for custom op query.
const TfLiteRegistration* CallbackOpResolver::FindOp(const char* op,
int version) const {
// Use Registration V2 API to find op.
if (op_resolver_callbacks_.find_custom_op) {
return op_resolver_callbacks_.find_custom_op(
op_resolver_callbacks_.user_data, op, version);
}
if (op_resolver_callbacks_.find_custom_op_v1) {
// Check if cached Registration is available.
std::lock_guard<std::mutex> lock(mutex_);
for (const auto& created_registration : temporary_custom_registrations_) {
if (strcmp(created_registration->custom_name, op) == 0 &&
created_registration->version == version) {
return created_registration.get();
}
}
// Get a Registration V1 object and create a Registration V2 object.
const TfLiteRegistration_V1* reg_v1 =
op_resolver_callbacks_.find_custom_op_v1(
op_resolver_callbacks_.user_data, op, version);
if (reg_v1) {
TfLiteRegistration* new_registration = new TfLiteRegistration();
memcpy(new_registration, reg_v1, sizeof(TfLiteRegistration_V1));
new_registration->registration_external = nullptr;
temporary_custom_registrations_.push_back(
std::unique_ptr<TfLiteRegistration>(new_registration));
return new_registration;
}
}
return nullptr;
}
TfLiteInterpreter* InterpreterCreateWithOpResolver(
const TfLiteModel* model, const TfLiteInterpreterOptions* optional_options,
tflite::MutableOpResolver* mutable_resolver) {
TFLITE_DCHECK_NE(mutable_resolver, nullptr);
if (!model || !model->impl) {
return nullptr;
}
std::unique_ptr<tflite::ErrorReporter> optional_error_reporter;
if (optional_options &&
optional_options->error_reporter_callback.error_reporter != nullptr) {
optional_error_reporter = std::make_unique<CallbackErrorReporter>(
optional_options->error_reporter_callback);
}
// By default, we use the provided mutable_op_resolver, adding any builtin or
// custom ops registered with `TfLiteInterpreterOptionsAddBuiltinOp` and/or
// `TfLiteInterpreterOptionsAddCustomOp`.
tflite::OpResolver* op_resolver = mutable_resolver;
if (optional_options) {
mutable_resolver->AddAll(optional_options->mutable_op_resolver);
for (auto* registration_external : optional_options->op_registrations) {
TfLiteRegistration registration{};
InitTfLiteRegistration(®istration, registration_external);
mutable_resolver->AddCustom(registration_external->custom_name,
®istration,
registration_external->version);
}
}
// However, if `TfLiteInterpreterOptionsSetOpResolver` has been called with
// a non-null callback parameter, then we instead use a
// `CallbackOpResolver` that will forward to the callbacks provided there.
CallbackOpResolver callback_op_resolver;
if (optional_options &&
(optional_options->op_resolver_callbacks.find_builtin_op != nullptr ||
optional_options->op_resolver_callbacks.find_custom_op != nullptr ||
optional_options->op_resolver_callbacks.find_builtin_op_v1 != nullptr ||
optional_options->op_resolver_callbacks.find_custom_op_v1 != nullptr)) {
callback_op_resolver.SetCallbacks(optional_options->op_resolver_callbacks);
op_resolver = &callback_op_resolver;
}
tflite::ErrorReporter* error_reporter = optional_error_reporter
? optional_error_reporter.get()
: tflite::DefaultErrorReporter();
tflite::InterpreterBuilder builder(model->impl->GetModel(), *op_resolver,
error_reporter);
std::unique_ptr<tflite::Interpreter> interpreter;
if (builder(&interpreter) != kTfLiteOk) {
return nullptr;
}
if (optional_options) {
if (optional_options->num_threads !=
TfLiteInterpreterOptions::kDefaultNumThreads) {
interpreter->SetNumThreads(optional_options->num_threads);
}
if (optional_options->use_nnapi) {
if (interpreter->ModifyGraphWithDelegate(tflite::NnApiDelegate()) !=
kTfLiteOk) {
return nullptr;
}
}
for (auto* delegate : optional_options->delegates) {
if (interpreter->ModifyGraphWithDelegate(delegate) != kTfLiteOk) {
return nullptr;
}
}
if (optional_options->enable_cancellation) {
interpreter->EnableCancellation();
}
}
bool enable_delegate_fallback =
optional_options != nullptr && optional_options->enable_delegate_fallback;
return new TfLiteInterpreter{model->impl, std::move(optional_error_reporter),
std::move(interpreter),
enable_delegate_fallback};
}
} // namespace internal
} // namespace tflite
| {
"content_hash": "9203c8a717c9915e7866721a61235ee2",
"timestamp": "",
"source": "github",
"line_count": 504,
"max_line_length": 135,
"avg_line_length": 38.0218253968254,
"alnum_prop": 0.7056306423837604,
"repo_name": "Intel-tensorflow/tensorflow",
"id": "4847034c38e6b3c0f94af0a35580cbde55d8aa4b",
"size": "19831",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tensorflow/lite/core/c/c_api.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "36962"
},
{
"name": "C",
"bytes": "1400913"
},
{
"name": "C#",
"bytes": "13584"
},
{
"name": "C++",
"bytes": "126099634"
},
{
"name": "CMake",
"bytes": "182430"
},
{
"name": "Cython",
"bytes": "5003"
},
{
"name": "Dockerfile",
"bytes": "416133"
},
{
"name": "Go",
"bytes": "2129888"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "1074438"
},
{
"name": "Jupyter Notebook",
"bytes": "792906"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "11447433"
},
{
"name": "Makefile",
"bytes": "2760"
},
{
"name": "Objective-C",
"bytes": "172666"
},
{
"name": "Objective-C++",
"bytes": "300213"
},
{
"name": "Pawn",
"bytes": "5552"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "42782002"
},
{
"name": "Roff",
"bytes": "5034"
},
{
"name": "Ruby",
"bytes": "9199"
},
{
"name": "Shell",
"bytes": "621917"
},
{
"name": "Smarty",
"bytes": "89538"
},
{
"name": "SourcePawn",
"bytes": "14625"
},
{
"name": "Starlark",
"bytes": "7738020"
},
{
"name": "Swift",
"bytes": "78435"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
-fx-background-image: url('/images/toolbar/create.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
#searchBtn {
-fx-background-image: url('/images/toolbar/search.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
#languageBtn {
-fx-background-image: url('/images/toolbar/change_lang.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
// Creator pane tool buttons
#newBtn {
-fx-background-image: url('/images/toolbar/new.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
#saveBtn {
-fx-background-image: url('/images/toolbar/save.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
#uploadBtn {
-fx-background-image: url('/images/toolbar/upload.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
// Search pane tool buttons
#addFolderBtn {
-fx-background-image: url('/images/toolbar/add_recipes_folder.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
#refreshBtn {
-fx-background-image: url('/images/toolbar/refresh.png');
-fx-background-size: 30 30;
-fx-background-repeat: no-repeat;
-fx-background-position: center;
} | {
"content_hash": "8b69e13288359046223ff8f6454110c7",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 72,
"avg_line_length": 26.379310344827587,
"alnum_prop": 0.6725490196078432,
"repo_name": "Kynarth/ryrycipe",
"id": "3affccc55dca481d585b5fb6f3b68d00088dda35",
"size": "1572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/css/toolbar.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1831"
},
{
"name": "Java",
"bytes": "154914"
},
{
"name": "Python",
"bytes": "59204"
}
],
"symlink_target": ""
} |
from django.conf import settings
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path
from core import views as core_views
from api.resources import OrderableResource, PostResource, SearchResource
from core.sitemap import IndexSitemap, BlogSitemap, StaticSitemap
sitemaps = {"index": IndexSitemap, "blog": BlogSitemap, "static": StaticSitemap}
urlpatterns = [
path("", core_views.index, name="index"),
path("email/<email_id>/", core_views.email, name="email"),
path("about/", core_views.static, {"page": "about"}, name="about"),
path("resume/", core_views.static, {"page": "resume"}, name="resume"),
path("copyrights/", core_views.static, {"page": "copyrights"}, name="copyrights"),
# API urls
path("api/posts/", PostResource.as_view()),
path("api/orderable/", OrderableResource.as_view()),
path("api/search/", SearchResource.as_view()),
# Blog urls
path("blog/", include("blog.urls"), name="blog"),
# Gallery urls
path("gallery/", include("gallery.urls")),
# Profile urls
path("profile/", include("profiles.urls")),
# URL shortener
path("sr/", include("shortener.urls")),
# Admin urls
path("dashboard/", admin.site.urls),
# Django RQ
path("dashboard/django-rq/", include("django_rq.urls")),
# Sitemap
path(
"sitemap.xml",
sitemap,
{"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.sitemap",
),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| {
"content_hash": "62b903b50c3bf178f5778567cd813176",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 86,
"avg_line_length": 35.26923076923077,
"alnum_prop": 0.678298800436205,
"repo_name": "manti-by/M2MICRO",
"id": "712ba01a9ca4656d0141cd1ddd49f41e6c08d480",
"size": "1834",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/core/urls.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "13675"
},
{
"name": "Batchfile",
"bytes": "518"
},
{
"name": "CSS",
"bytes": "32089"
},
{
"name": "HTML",
"bytes": "53"
},
{
"name": "JavaScript",
"bytes": "30285"
},
{
"name": "PHP",
"bytes": "573567"
},
{
"name": "PLSQL",
"bytes": "910"
},
{
"name": "SQLPL",
"bytes": "17657"
},
{
"name": "Shell",
"bytes": "13408"
}
],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "request".
*
* @property integer $req_id
* @property integer $user1_id
* @property integer $user2_id
* @property string $req_type
* @property string $date
*
* @property User $user1
* @property User $user2
*/
class Request extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'request';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user1_id', 'user2_id', 'req_type', 'date'], 'required'],
[['user1_id', 'user2_id'], 'integer'],
[['date'], 'safe'],
[['req_type'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'req_id' => 'Req ID',
'user1_id' => 'User1 ID',
'user2_id' => 'User2 ID',
'req_type' => 'Req Type',
'date' => 'Date',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser1()
{
return $this->hasOne(User::className(), ['id' => 'user1_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser2()
{
return $this->hasOne(User::className(), ['id' => 'user2_id']);
}
/**
* @inheritdoc
* @return RequestQuery the active query used by this AR class.
*/
public static function find()
{
return new RequestQuery(get_called_class());
}
}
| {
"content_hash": "a52346f6addd7e5786b8b031876b9c83",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 71,
"avg_line_length": 19.9375,
"alnum_prop": 0.4946708463949843,
"repo_name": "Lupi-Stole-My-Code/NZI-Project",
"id": "8f327974c54069e540722498cdbbdf8fb43c55ea",
"size": "1595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/models/Request.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "1194578"
},
{
"name": "HTML",
"bytes": "3396616"
},
{
"name": "JavaScript",
"bytes": "5732228"
},
{
"name": "PHP",
"bytes": "400441"
}
],
"symlink_target": ""
} |
/**
* Licensed under the CC-GNU Lesser General Public License, Version 2.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* 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.
*/
// Author: Choochart Haruechaiyasak
// Last update: 28 March 2006
package longlexto;
import java.io.*;
import java.util.*;
public class LongParseTree {
//Private variables
private Trie dict; //For storing words from dictionary
private Vector indexList; //List of index positions
private Vector typeList; //List of word types
private Vector frontDepChar; //Front dependent characters: must have front characters
private Vector rearDepChar; //Rear dependent characters: must have rear characters
private Vector tonalChar; //Tonal characters
private Vector endingChar; //Ending characters
/*******************************************************************/
/************************ Constructor ******************************/
/*******************************************************************/
public LongParseTree(Trie dict, Vector indexList, Vector typeList) throws IOException {
this.dict=dict;
this.indexList=indexList;
this.typeList=typeList;
frontDepChar=new Vector();
rearDepChar=new Vector();
tonalChar=new Vector();
endingChar=new Vector();
//Adding front-dependent characters
frontDepChar.addElement("�"); frontDepChar.addElement("�"); frontDepChar.addElement("�");
frontDepChar.addElement("�"); frontDepChar.addElement("�"); frontDepChar.addElement("�");
frontDepChar.addElement("�"); frontDepChar.addElement("�"); frontDepChar.addElement("�");
frontDepChar.addElement("�"); frontDepChar.addElement("�"); frontDepChar.addElement("�");
frontDepChar.addElement("�"); frontDepChar.addElement("�");
//Adding rear-dependent characters
rearDepChar.addElement("�"); rearDepChar.addElement("�"); rearDepChar.addElement("�");
rearDepChar.addElement("�"); rearDepChar.addElement("�"); rearDepChar.addElement("�");
rearDepChar.addElement("�"); rearDepChar.addElement("�");
//Adding tonal characters
tonalChar.addElement("�"); tonalChar.addElement("�"); tonalChar.addElement("�");
tonalChar.addElement("�");
//Adding ending characters
endingChar.addElement("�"); endingChar.addElement("�");
}
/****************************************************************/
/********************** nextWordValid ***************************/
/****************************************************************/
private boolean nextWordValid(int beginPos, String text) {
int pos=beginPos+1;
int status;
if(beginPos==text.length())
return true;
else if(text.charAt(beginPos)<='~') //English alphabets/digits/special characters
return true;
else {
while(pos<=text.length()) {
status=dict.contains(text.substring(beginPos,pos));
if(status==1)
return true;
else if(status==0)
pos++;
else
break;
}
}
return false;
} //nextWordValid
/****************************************************************/
/********************** parseWordInstance ***********************/
/****************************************************************/
public int parseWordInstance(int beginPos, String text) {
char prevChar='\0'; //Previous character
int longestPos=-1; //Longest position
int longestValidPos=-1; //Longest valid position
int numValidPos=0; //Number of longest value pos (for determining ambiguity)
int returnPos=-1; //Returned text position
int pos, status;
status=1;
numValidPos=0;
pos=beginPos+1;
while((pos<=text.length())&&(status!=-1)) {
status=dict.contains(text.substring(beginPos, pos));
//Record longest so far
if(status==1) {
longestPos=pos;
if(nextWordValid(pos, text)) {
longestValidPos=pos;
numValidPos++;
}
}
pos++;
} //while
//--------------------------------------------------
//For checking rear dependent character
if(beginPos>=1)
prevChar=text.charAt(beginPos-1);
//Unknown word
if(longestPos==-1) {
returnPos=beginPos+1;
//Combine unknown segments
if((indexList.size()>0)&&
(frontDepChar.contains("" + text.charAt(beginPos))||
tonalChar.contains("" + text.charAt(beginPos))||
rearDepChar.contains("" + prevChar)||
(((Integer)typeList.elementAt(typeList.size()-1)).intValue()==0))) {
indexList.setElementAt(new Integer(returnPos), indexList.size()-1);
typeList.setElementAt(new Integer(0), typeList.size()-1);
}
else {
indexList.addElement(new Integer(returnPos));
typeList.addElement(new Integer(0));
}
return returnPos;
}
//--------------------------------------------------
//Known or ambiguous word
else {
//If there is no merging point
if(longestValidPos==-1) {
//Check whether front char requires rear segment
if(rearDepChar.contains("" + prevChar)) {
indexList.setElementAt(new Integer(longestPos), indexList.size()-1);
typeList.setElementAt(new Integer(0), typeList.size()-1);
}
else {
typeList.addElement(new Integer(1));
indexList.addElement(new Integer(longestPos));
}
return(longestPos); //known followed by unknown: consider longestPos
}
else {
//Check whether front char requires rear segment
if(rearDepChar.contains("" + prevChar)) {
indexList.setElementAt(new Integer(longestValidPos), indexList.size()-1);
typeList.setElementAt(new Integer(0), typeList.size()-1);
}
else if(numValidPos==1) {
typeList.addElement(new Integer(1)); //known
indexList.addElement(new Integer(longestValidPos));
}
else {
typeList.addElement(new Integer(2)); //ambiguous
indexList.addElement(new Integer(longestValidPos));
}
return(longestValidPos);
}
}
} //parseWordInstance
} | {
"content_hash": "f398cada7693477f210c3c7e82fc96a7",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 94,
"avg_line_length": 37.15,
"alnum_prop": 0.5745476297293256,
"repo_name": "Elbisopmi/Wannatalk",
"id": "86e432b031d61cb216b890a54b403655f994e7fa",
"size": "6743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/longlexto/LongParseTree.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5043"
},
{
"name": "Java",
"bytes": "421455"
},
{
"name": "Shell",
"bytes": "7112"
}
],
"symlink_target": ""
} |
#ifndef JAPA_ONE_SENT_PER_LINE_H
#define JAPA_ONE_SENT_PER_LINE_H
#include "textparser.h"
namespace japa
{
/**
* \french
* Compile un texte donc chaque phrase tient sur une ligne et chaque mot est
* s�par� par un espace.
* \endfrench
*
* \english
* Parse a text in where sentences are delimited by new lines and words by
* spaces.
* \english
*
*
* @version 1.1
*/
class OneSentPerLineParser : public TextParser
{
public :
/**
* \french
* Constructeur.
* \endfrench
*
* \english
* Constructor.
* \endenglish
*/
OneSentPerLineParser();
/**
* \french
* Destructeur.
* \endfrench
*
* \english
* Destructor.
* \endenglish
*/
virtual ~OneSentPerLineParser();
bool operator() ( std::wistream& in, Text& text );
};
}// namespace japa
#endif
| {
"content_hash": "f49184e4099cac80d1ac999f780515e8",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 76,
"avg_line_length": 15.636363636363637,
"alnum_prop": 0.5941860465116279,
"repo_name": "rali-udem/yasa",
"id": "248fadd83c4b72de32129eb2ae987a0dca1cf061",
"size": "1416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/libyasa/onesentperlineparser.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "440761"
},
{
"name": "Shell",
"bytes": "282936"
}
],
"symlink_target": ""
} |
namespace Tests.Unit.Lender.Slos.Financial
{
using System;
using MbUnit.Framework;
[TestFixture]
public class FixtureTests
{
[FixtureSetUp]
public void FixtureSetup()
{
Console.WriteLine("Fixture setup");
}
[FixtureTearDown]
public void FixtureTeardown()
{
Console.WriteLine("Fixture teardown");
}
[SetUp]
public void TestSetup()
{
Console.WriteLine("Before-test");
}
[TearDown]
public void TestTeardown()
{
Console.WriteLine("After-test");
}
[Test]
public void TestMethod_NoParameters()
{
Console.WriteLine("Executing 'TestMethod_NoParameters'");
}
[Test]
[Row(0)]
[Row(1)]
[Row(2)]
public void TestMethod_WithParameters(int index)
{
Console.WriteLine("Executing 'TestMethod_WithParameters' {0}", index);
}
}
}
| {
"content_hash": "139eac807aec58f19f0cfcc2a5b803ec",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 82,
"avg_line_length": 21.06122448979592,
"alnum_prop": 0.5193798449612403,
"repo_name": "ruthlesshelp/prodotnetbestpractices",
"id": "ee47e4c9cac690d1c2ca9c07945fbfdebf0e2dcc",
"size": "1034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SourceCode/Chapter12/2_MbUnit/Tests.Unit.Lender.Slos.Financial/FixtureTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1445854"
}
],
"symlink_target": ""
} |
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Responses {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/CollectDailyBonusResponse.proto</summary>
public static partial class CollectDailyBonusResponseReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Responses/CollectDailyBonusResponse.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CollectDailyBonusResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj9QT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0NvbGxlY3REYWls",
"eUJvbnVzUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5S",
"ZXNwb25zZXMiqwEKGUNvbGxlY3REYWlseUJvbnVzUmVzcG9uc2USUQoGcmVz",
"dWx0GAEgASgOMkEuUE9HT1Byb3Rvcy5OZXR3b3JraW5nLlJlc3BvbnNlcy5D",
"b2xsZWN0RGFpbHlCb251c1Jlc3BvbnNlLlJlc3VsdCI7CgZSZXN1bHQSCQoF",
"VU5TRVQQABILCgdTVUNDRVNTEAESCwoHRkFJTFVSRRACEgwKCFRPT19TT09O",
"EANiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.CollectDailyBonusResponse), global::POGOProtos.Networking.Responses.CollectDailyBonusResponse.Parser, new[]{ "Result" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.CollectDailyBonusResponse.Types.Result) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CollectDailyBonusResponse : pb::IMessage<CollectDailyBonusResponse> {
private static readonly pb::MessageParser<CollectDailyBonusResponse> _parser = new pb::MessageParser<CollectDailyBonusResponse>(() => new CollectDailyBonusResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CollectDailyBonusResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Responses.CollectDailyBonusResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CollectDailyBonusResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CollectDailyBonusResponse(CollectDailyBonusResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CollectDailyBonusResponse Clone() {
return new CollectDailyBonusResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::POGOProtos.Networking.Responses.CollectDailyBonusResponse.Types.Result result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Networking.Responses.CollectDailyBonusResponse.Types.Result Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CollectDailyBonusResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CollectDailyBonusResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CollectDailyBonusResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::POGOProtos.Networking.Responses.CollectDailyBonusResponse.Types.Result) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the CollectDailyBonusResponse message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum Result {
[pbr::OriginalName("UNSET")] Unset = 0,
[pbr::OriginalName("SUCCESS")] Success = 1,
[pbr::OriginalName("FAILURE")] Failure = 2,
[pbr::OriginalName("TOO_SOON")] TooSoon = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| {
"content_hash": "d771b32cabeadb9afb8838acc7dda522",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 318,
"avg_line_length": 36.97674418604651,
"alnum_prop": 0.7004716981132075,
"repo_name": "PoGo-Devs/PoGo",
"id": "a44d0c923d51f22e51065a1e22002c6cc32ccc30",
"size": "6569",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "src/PoGo.ApiClient/Proto/Networking/Responses/CollectDailyBonusResponse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3126013"
}
],
"symlink_target": ""
} |
<?php
namespace Im0rtality\TaskSchedulerBundle\Command;
use Im0rtality\TaskSchedulerBundle\Core\MongoDbBackendInterface;
use Im0rtality\TaskSchedulerBundle\SchedulerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class TasksWorkerRunCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('tasks:worker:run')
->setDescription('Starts task scheduler worker');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var SchedulerInterface $scheduler */
$scheduler = $this->getContainer()->get('im0rtality_task_scheduler.scheduler');
/** @var LoggerInterface $logger */
$logger = $this->getContainer()->get('monolog.logger.runner');
$output->writeln(sprintf('| %25s | %15s | %4s |', 'Timestamp', 'Command', 'Late (s)'));
while (true) {
$task = $scheduler->getTask();
if ($task) {
$output->writeln(
sprintf(
'| %25s | %15s | %4d',
(new \DateTime())->format('Y-m-d H:i:s'),
json_encode($task->getData()) ?: 'null',
time() - $task->getAt()->getTimestamp()
)
);
$logger->info(
'Scheduled task executed',
[
'id' => $task->getTaskId(),
'at' => $task->getAt()->format('Y-m-d H:i:s'),
'data' => $task->getData()
]
);
} else {
sleep(1);
}
}
}
}
| {
"content_hash": "863ebdc9e0315d6c3676ddee53b4ee43",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 95,
"avg_line_length": 35.98076923076923,
"alnum_prop": 0.5221806520577231,
"repo_name": "Im0rtality/task-scheduler",
"id": "14933939a8d54c751c4f3f4689b0229b450a20cc",
"size": "1871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Im0rtality/TaskSchedulerBundle/Command/TasksWorkerRunCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "54930"
},
{
"name": "Puppet",
"bytes": "5393"
},
{
"name": "Ruby",
"bytes": "303"
},
{
"name": "Shell",
"bytes": "1124"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.backup.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/DeleteBackupVaultAccessPolicy"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteBackupVaultAccessPolicyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of a logical container where backups are stored. Backup vaults are identified by names that are unique
* to the account used to create them and the AWS Region where they are created. They consist of lowercase letters,
* numbers, and hyphens.
* </p>
*/
private String backupVaultName;
/**
* <p>
* The name of a logical container where backups are stored. Backup vaults are identified by names that are unique
* to the account used to create them and the AWS Region where they are created. They consist of lowercase letters,
* numbers, and hyphens.
* </p>
*
* @param backupVaultName
* The name of a logical container where backups are stored. Backup vaults are identified by names that are
* unique to the account used to create them and the AWS Region where they are created. They consist of
* lowercase letters, numbers, and hyphens.
*/
public void setBackupVaultName(String backupVaultName) {
this.backupVaultName = backupVaultName;
}
/**
* <p>
* The name of a logical container where backups are stored. Backup vaults are identified by names that are unique
* to the account used to create them and the AWS Region where they are created. They consist of lowercase letters,
* numbers, and hyphens.
* </p>
*
* @return The name of a logical container where backups are stored. Backup vaults are identified by names that are
* unique to the account used to create them and the AWS Region where they are created. They consist of
* lowercase letters, numbers, and hyphens.
*/
public String getBackupVaultName() {
return this.backupVaultName;
}
/**
* <p>
* The name of a logical container where backups are stored. Backup vaults are identified by names that are unique
* to the account used to create them and the AWS Region where they are created. They consist of lowercase letters,
* numbers, and hyphens.
* </p>
*
* @param backupVaultName
* The name of a logical container where backups are stored. Backup vaults are identified by names that are
* unique to the account used to create them and the AWS Region where they are created. They consist of
* lowercase letters, numbers, and hyphens.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteBackupVaultAccessPolicyRequest withBackupVaultName(String backupVaultName) {
setBackupVaultName(backupVaultName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBackupVaultName() != null)
sb.append("BackupVaultName: ").append(getBackupVaultName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteBackupVaultAccessPolicyRequest == false)
return false;
DeleteBackupVaultAccessPolicyRequest other = (DeleteBackupVaultAccessPolicyRequest) obj;
if (other.getBackupVaultName() == null ^ this.getBackupVaultName() == null)
return false;
if (other.getBackupVaultName() != null && other.getBackupVaultName().equals(this.getBackupVaultName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBackupVaultName() == null) ? 0 : getBackupVaultName().hashCode());
return hashCode;
}
@Override
public DeleteBackupVaultAccessPolicyRequest clone() {
return (DeleteBackupVaultAccessPolicyRequest) super.clone();
}
}
| {
"content_hash": "f9df92d8ab359f36e65364f9c5d340b4",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 132,
"avg_line_length": 38.00787401574803,
"alnum_prop": 0.6679096747462192,
"repo_name": "jentfoo/aws-sdk-java",
"id": "156a2829fe91d0f9b1a0d135f0340c4260eaf37b",
"size": "5407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-backup/src/main/java/com/amazonaws/services/backup/model/DeleteBackupVaultAccessPolicyRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>zfc: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.0 / zfc - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
zfc
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-15 07:12:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-15 07:12:26 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/zfc"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ZFC"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: set theory"
"keyword: Zermelo-Fraenkel"
"keyword: Calculus of Inductive Constructions"
"category: Mathematics/Logic/Set theory"
]
authors: [
"Benjamin Werner"
]
bug-reports: "https://github.com/coq-contribs/zfc/issues"
dev-repo: "git+https://github.com/coq-contribs/zfc.git"
synopsis: "An encoding of Zermelo-Fraenkel Set Theory in Coq"
description: """
The encoding of Zermelo-Fraenkel Set Theory is largely inspired by
Peter Aczel's work dating back to the eighties. A type Ens is defined,
which represents sets. Two predicates IN and EQ stand for membership
and extensional equality between sets. The axioms of ZFC are then
proved and thus appear as theorems in the development.
A main motivation for this work is the comparison of the respective
expressive power of Coq and ZFC.
A non-computational type-theoretical axiom of choice is necessary to
prove the replacement schemata and the set-theoretical AC.
The main difference between this work and Peter Aczel's is that
propositions are defined on the impredicative level Prop. Since the
definition of Ens is, however, still unchanged, I also added most of
Peter Aczel's definition. The main advantage of Aczel's approach is a
more constructive vision of the existential quantifier (which gives
the set-theoretical axiom of choice for free)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/zfc/archive/v8.9.0.tar.gz"
checksum: "md5=3723e1731f3dc6eed21c116f1415b27a"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-zfc.8.9.0 coq.8.11.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.0).
The following dependencies couldn't be met:
- coq-zfc -> coq < 8.10~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zfc.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "c571aaa0fca835cb98abd6ae1a75f5e8",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 159,
"avg_line_length": 41.57608695652174,
"alnum_prop": 0.5682352941176471,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3702148e41f1dc645a52789b806123901cf4dc68",
"size": "7675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.11.0/zfc/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
body {
background: #2196f3; /* fallback for old browsers */
background: -webkit-linear-gradient(to left, #2196f3 , #f44336); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #2196f3 , #f44336); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
color: #ffffff;
box-shadow: none;
font-family: 'Rubik', sans-serif !important;
}
select {
color: #000000;
}
.toolbar-left {
display: block;
position: absolute;
top: 5px;
left: 5px;
}
.black-bg {
background: #232526; /* fallback for old browsers */
background: -webkit-linear-gradient(to bottom, #111111 , #000000); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to bottom, #111111 , #000000); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.logo {
width: 75%;
margin-top: 25px;
margin-bottom: 25px;
}
nav {
border: 0 !important;
border-radius: 0px !important;
background: #34495e !important;
}
.navbar-brand {
padding: 0px;
}
.navbar-brand > img {
height: 100%;
padding: 15px;
width: auto;
}
button {
outline: none !important;
}
.page-title, .page-subtitle {
color: white;
}
#cesiumContainer {
margin: 0 auto;
}
.main-panel {
border-color: #34495e !important;
}
.main-panel-heading {
background-color: #34495e !important;
color: white !important;
font-weight: 700;
}
.main-panel-body {
color: #2c3e50 !important;
}
.results-panel {
margin-top: 30px;
}
.btn {
border: 0 none;
font-weight: 500;
letter-spacing: 1px;
font-size: 1em;
text-transform: uppercase;
}
.btn:focus, .btn:active:focus, .btn.active:focus {
outline: 0 none;
}
.btn-blue {
color: #FFFFFF;
background-color: #3498DB;
border-color: #2980B9;
}
.btn-blue:hover,
.btn-blue:focus,
.btn-blue:active,
.btn-blue.active,
.open .dropdown-toggle.btn-blue {
color: #FFFFFF;
background-color: #2980b9;
border-color: #2980B9;
}
.btn-blue:active,
.btn-blue.active,
.open .dropdown-toggle.btn-blue {
background-image: none;
}
.navbar-default .navbar-toggle {
border: none !important;
background: none !important;
}
.navbar-default .navbar-toggle:hover {
background: none !important;
}
.navbar-default .navbar-toggle:hover .icon-bar {
background-color: white !important;
}
.progressbar-text {
transform: translate(-50%, 0) !important;
font-size: 3em !important;
}
.biscore-caption {
letter-spacing: 4px;
text-align: center !important;
margin-left: auto !important;
margin-right: auto !important;
display: block !important;
}
.label-keyword {
background-color: #1abc9c;
font-size: 1em;
margin-bottom: 5px;
}
.score-caption {
letter-spacing: 4px !important;
text-align: center !important;
margin-left: auto !important;
margin-right: auto !important;
}
.score {
font-size: 2.5em;
letter-spacing: 2px !important;
text-align: center !important;
margin-left: auto !important;
margin-right: auto !important;
}
.fa-external-link {
color: white !important;
}
.button-link:hover {
text-decoration: none !important;
}
.white-link {
color: white !important;
}
.white-link:hover {
color: #ecf0f1 !important;
} | {
"content_hash": "4b32b015c77b76902181491339914dad",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 133,
"avg_line_length": 18.572222222222223,
"alnum_prop": 0.6308704756207,
"repo_name": "srujant/MLNews",
"id": "2b5292c3a970631ee4bc31ead771d3e058c19f83",
"size": "3343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/stylesheets/styles.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "676330"
},
{
"name": "GLSL",
"bytes": "172699"
},
{
"name": "HTML",
"bytes": "15064545"
},
{
"name": "JavaScript",
"bytes": "50755294"
},
{
"name": "OpenEdge ABL",
"bytes": "2662139"
},
{
"name": "Python",
"bytes": "216303"
},
{
"name": "Shell",
"bytes": "4042"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (1.8.0_31) on Fri Apr 24 10:58:25 CEST 2015 -->
<title>Uses of Package fr.fablabmars.model.dao</title>
<meta name="date" content="2015-04-24">
<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 Package fr.fablabmars.model.dao";
}
}
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>Class</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-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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?fr/fablabmars/model/dao/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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">
<h1 title="Uses of Package fr.fablabmars.model.dao" class="title">Uses of Package<br>fr.fablabmars.model.dao</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../fr/fablabmars/model/dao/package-summary.html">fr.fablabmars.model.dao</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="#fr.fablabmars.controler.formulaire">fr.fablabmars.controler.formulaire</a></td>
<td class="colLast">
<div class="block">Package réunissant les classes permettant de contrôler des données provenant de formulaires</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#fr.fablabmars.model.dao">fr.fablabmars.model.dao</a></td>
<td class="colLast">
<div class="block">Package réunissant les classes responsables d'accéder à la BDD</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="fr.fablabmars.controler.formulaire">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../fr/fablabmars/model/dao/package-summary.html">fr.fablabmars.model.dao</a> used by <a href="../../../../fr/fablabmars/controler/formulaire/package-summary.html">fr.fablabmars.controler.formulaire</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../fr/fablabmars/model/dao/class-use/DAO.html#fr.fablabmars.controler.formulaire">DAO</a>
<div class="block">Classe abstraite modélisant un objet d'accès aux données.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="fr.fablabmars.model.dao">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../fr/fablabmars/model/dao/package-summary.html">fr.fablabmars.model.dao</a> used by <a href="../../../../fr/fablabmars/model/dao/package-summary.html">fr.fablabmars.model.dao</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../fr/fablabmars/model/dao/class-use/DAO.html#fr.fablabmars.model.dao">DAO</a>
<div class="block">Classe abstraite modélisant un objet d'accès aux données.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../fr/fablabmars/model/dao/class-use/UtilisateurDAO.html#fr.fablabmars.model.dao">UtilisateurDAO</a>
<div class="block">Objet d'accès aux données Utilisateur (MySQL)</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</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>Class</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-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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?fr/fablabmars/model/dao/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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 ======= -->
</body>
</html>
| {
"content_hash": "61f714c52729c4511969d1ca71f1fa0c",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 296,
"avg_line_length": 37.507936507936506,
"alnum_prop": 0.6277331076315418,
"repo_name": "gperouffe/FabLabUsers",
"id": "7bc0e5a06f7d958ef6f085c08ad8bbe4a1913fdb",
"size": "7089",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/fr/fablabmars/model/dao/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "69206"
}
],
"symlink_target": ""
} |
.class public abstract Landroid/media/projection/IMediaProjectionWatcherCallback$Stub;
.super Landroid/os/Binder;
.source "IMediaProjectionWatcherCallback.java"
# interfaces
.implements Landroid/media/projection/IMediaProjectionWatcherCallback;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/media/projection/IMediaProjectionWatcherCallback;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x409
name = "Stub"
.end annotation
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Landroid/media/projection/IMediaProjectionWatcherCallback$Stub$Proxy;
}
.end annotation
# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "android.media.projection.IMediaProjectionWatcherCallback"
.field static final TRANSACTION_onStart_0:I = 0x1
.field static final TRANSACTION_onStop:I = 0x2
# direct methods
.method public constructor <init>()V
.locals 1
.prologue
.line 15
invoke-direct {p0}, Landroid/os/Binder;-><init>()V
.line 16
const-string v0, "android.media.projection.IMediaProjectionWatcherCallback"
invoke-virtual {p0, p0, v0}, Landroid/media/projection/IMediaProjectionWatcherCallback$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V
.line 17
return-void
.end method
.method public static asInterface(Landroid/os/IBinder;)Landroid/media/projection/IMediaProjectionWatcherCallback;
.locals 2
.param p0, "obj" # Landroid/os/IBinder;
.prologue
.line 24
if-nez p0, :cond_0
.line 25
const/4 v0, 0x0
.line 31
:goto_0
return-object v0
.line 27
:cond_0
const-string v1, "android.media.projection.IMediaProjectionWatcherCallback"
invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;
move-result-object v0
.line 28
.local v0, "iin":Landroid/os/IInterface;
if-eqz v0, :cond_1
instance-of v1, v0, Landroid/media/projection/IMediaProjectionWatcherCallback;
if-eqz v1, :cond_1
.line 29
check-cast v0, Landroid/media/projection/IMediaProjectionWatcherCallback;
goto :goto_0
.line 31
:cond_1
new-instance v0, Landroid/media/projection/IMediaProjectionWatcherCallback$Stub$Proxy;
.end local v0 # "iin":Landroid/os/IInterface;
invoke-direct {v0, p0}, Landroid/media/projection/IMediaProjectionWatcherCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
goto :goto_0
.end method
# virtual methods
.method public asBinder()Landroid/os/IBinder;
.locals 0
.prologue
.line 35
return-object p0
.end method
.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
.locals 3
.param p1, "code" # I
.param p2, "data" # Landroid/os/Parcel;
.param p3, "reply" # Landroid/os/Parcel;
.param p4, "flags" # I
.annotation system Ldalvik/annotation/Throws;
value = {
Landroid/os/RemoteException;
}
.end annotation
.prologue
const/4 v1, 0x1
.line 39
sparse-switch p1, :sswitch_data_0
.line 73
invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
move-result v1
:goto_0
return v1
.line 43
:sswitch_0
const-string v2, "android.media.projection.IMediaProjectionWatcherCallback"
invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V
goto :goto_0
.line 48
:sswitch_1
const-string v2, "android.media.projection.IMediaProjectionWatcherCallback"
invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V
.line 50
invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I
move-result v2
if-eqz v2, :cond_0
.line 51
sget-object v2, Landroid/media/projection/MediaProjectionInfo;->CREATOR:Landroid/os/Parcelable$Creator;
invoke-interface {v2, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
move-result-object v0
check-cast v0, Landroid/media/projection/MediaProjectionInfo;
.line 56
.local v0, "_arg0":Landroid/media/projection/MediaProjectionInfo;
:goto_1
invoke-virtual {p0, v0}, Landroid/media/projection/IMediaProjectionWatcherCallback$Stub;->onStart(Landroid/media/projection/MediaProjectionInfo;)V
goto :goto_0
.line 54
.end local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
:cond_0
const/4 v0, 0x0
.restart local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
goto :goto_1
.line 61
.end local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
:sswitch_2
const-string v2, "android.media.projection.IMediaProjectionWatcherCallback"
invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V
.line 63
invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I
move-result v2
if-eqz v2, :cond_1
.line 64
sget-object v2, Landroid/media/projection/MediaProjectionInfo;->CREATOR:Landroid/os/Parcelable$Creator;
invoke-interface {v2, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
move-result-object v0
check-cast v0, Landroid/media/projection/MediaProjectionInfo;
.line 69
.restart local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
:goto_2
invoke-virtual {p0, v0}, Landroid/media/projection/IMediaProjectionWatcherCallback$Stub;->onStop(Landroid/media/projection/MediaProjectionInfo;)V
goto :goto_0
.line 67
.end local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
:cond_1
const/4 v0, 0x0
.restart local v0 # "_arg0":Landroid/media/projection/MediaProjectionInfo;
goto :goto_2
.line 39
nop
:sswitch_data_0
.sparse-switch
0x1 -> :sswitch_1
0x2 -> :sswitch_2
0x5f4e5446 -> :sswitch_0
.end sparse-switch
.end method
| {
"content_hash": "bac7a61370918a61e3e80b1c77e63101",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 157,
"avg_line_length": 27.075555555555557,
"alnum_prop": 0.7094550229809586,
"repo_name": "Liberations/Flyme5_devices_base_cm",
"id": "d99cec0ffc02caf1c32667bb266c8762e72c0c53",
"size": "6092",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/aosp/framework.jar.out/smali/android/media/projection/IMediaProjectionWatcherCallback$Stub.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "11209"
},
{
"name": "Python",
"bytes": "1195"
},
{
"name": "Shell",
"bytes": "55270"
},
{
"name": "Smali",
"bytes": "160321888"
}
],
"symlink_target": ""
} |
package com.dihanov.musiq.ui.detail;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.dihanov.musiq.ui.detail.detailfragments.ArtistSpecificsAlbum;
import com.dihanov.musiq.ui.detail.detailfragments.ArtistSpecificsBiography;
import com.dihanov.musiq.ui.detail.detailfragments.detailfragmentstoptracks.ArtistSpecificsTopTracks;
/**
* Created by dimitar.dihanov on 9/29/2017.
*/
public class ArtistDetailsViewPagerAdapter extends FragmentStatePagerAdapter {
private static int TAB_COUNT = 3;
public ArtistDetailsViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ArtistSpecificsBiography.newInstance();
case 1:
return ArtistSpecificsAlbum.newInstance();
case 2:
return ArtistSpecificsTopTracks.newInstance();
}
return null;
}
@Override
public int getCount() {
return TAB_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return ArtistSpecificsBiography.TITLE;
case 1:
return ArtistSpecificsAlbum.TITLE;
case 2:
return ArtistSpecificsTopTracks.TITLE;
}
return super.getPageTitle(position);
}
}
| {
"content_hash": "443dec9cbe58f453ee53d41a163b03f3",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 101,
"avg_line_length": 28.62264150943396,
"alnum_prop": 0.6671061305207646,
"repo_name": "DDihanov/musiQ",
"id": "2a537bc7fd658026a23d209888f1a98ef87775be",
"size": "1517",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/dihanov/musiq/ui/detail/ArtistDetailsViewPagerAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "453590"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.hive.metastore.alluxio;
import alluxio.client.table.TableMasterClient;
import io.trino.plugin.hive.metastore.HiveMetastore;
import io.trino.plugin.hive.metastore.HiveMetastoreConfig;
import io.trino.plugin.hive.metastore.HiveMetastoreFactory;
import io.trino.spi.security.ConnectorIdentity;
import javax.inject.Inject;
import java.util.Optional;
public class AlluxioHiveMetastoreFactory
implements HiveMetastoreFactory
{
private final AlluxioHiveMetastore metastore;
@Inject
public AlluxioHiveMetastoreFactory(TableMasterClient client, HiveMetastoreConfig hiveMetastoreConfig)
{
// Alluxio metastore does not support impersonation, so just create a single shared instance
metastore = new AlluxioHiveMetastore(client, hiveMetastoreConfig);
}
@Override
public boolean isImpersonationEnabled()
{
return false;
}
@Override
public HiveMetastore createMetastore(Optional<ConnectorIdentity> identity)
{
return metastore;
}
}
| {
"content_hash": "a38d09f457d92ac28ab484f3b4de89fe",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 105,
"avg_line_length": 32.714285714285715,
"alnum_prop": 0.7592014971927635,
"repo_name": "smartnews/presto",
"id": "8737945d4568e674fff2ce71d1e1cb6527507e95",
"size": "1603",
"binary": false,
"copies": "1",
"ref": "refs/heads/smartnews",
"path": "plugin/trino-hive/src/main/java/io/trino/plugin/hive/metastore/alluxio/AlluxioHiveMetastoreFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "50268"
},
{
"name": "CSS",
"bytes": "13515"
},
{
"name": "Dockerfile",
"bytes": "1967"
},
{
"name": "Groovy",
"bytes": "1702"
},
{
"name": "HTML",
"bytes": "30842"
},
{
"name": "Java",
"bytes": "61596519"
},
{
"name": "JavaScript",
"bytes": "232261"
},
{
"name": "PLSQL",
"bytes": "85"
},
{
"name": "Python",
"bytes": "5266"
},
{
"name": "Scala",
"bytes": "10145"
},
{
"name": "Shell",
"bytes": "51516"
},
{
"name": "Smarty",
"bytes": "1938"
}
],
"symlink_target": ""
} |
const rx = require('rx');
const request = require('request');
let wrapMethodInRx = (method) => {
return function (...args) {
return rx.Observable.create((subj) => {
// Push the callback as the last parameter
args.push((err, resp, body) => {
if (err) {
subj.onError(err);
return;
}
if (resp.statusCode >= 400) {
subj.onError(new Error(`Request failed: ${resp.statusCode}\n${body}`));
return;
}
subj.onNext({response: resp, body: body});
subj.onCompleted();
});
try {
method(...args);
} catch (e) {
subj.onError(e);
}
return rx.Disposable.empty;
})
}
};
let requestRx = wrapMethodInRx(request);
requestRx.get = wrapMethodInRx(request.get);
requestRx.post = wrapMethodInRx(request.post);
requestRx.patch = wrapMethodInRx(request.patch);
requestRx.put = wrapMethodInRx(request.put);
requestRx.del = wrapMethodInRx(request.del);
requestRx.pipe = (url, stream) => {
return rx.Observable.create((subj) => {
try {
request.get(url).pipe(stream)
.on('error', (err) => subj.onError(err))
.on('end', () => { subj.onNext(true); subj.onCompleted(); });
} catch (e) {
subj.onError(e);
}
});
};
module.exports = requestRx; | {
"content_hash": "cc2b62c6dd1197908e1bce92a92b0b23",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 91,
"avg_line_length": 28.566037735849058,
"alnum_prop": 0.49933949801849403,
"repo_name": "lockerfish/mini-hacks",
"id": "ed459ba1623fe5ec8b918ae37f58c304b0c338a6",
"size": "1514",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ios-sync-progress-indicator/requestRx.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "798"
},
{
"name": "C",
"bytes": "278"
},
{
"name": "C#",
"bytes": "45137"
},
{
"name": "Go",
"bytes": "1256"
},
{
"name": "HTML",
"bytes": "205"
},
{
"name": "Java",
"bytes": "24467"
},
{
"name": "JavaScript",
"bytes": "6017"
},
{
"name": "Objective-C",
"bytes": "6278"
},
{
"name": "Python",
"bytes": "452"
},
{
"name": "Ruby",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "4137"
},
{
"name": "Swift",
"bytes": "21387"
}
],
"symlink_target": ""
} |
package org.jivesoftware.openfire.plugin.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.entity.UserGroupsEntity;
import org.jivesoftware.openfire.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.UserServicePluginNG;
@Path("userService/users/{username}/groups")
public class UserGroupService {
private UserServicePluginNG plugin;
@PostConstruct
public void init() {
plugin = UserServicePluginNG.getInstance();
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public UserGroupsEntity getUserGroups(@PathParam("username") String username) throws ServiceException {
return new UserGroupsEntity(plugin.getUserGroups(username));
}
@POST
public Response addUserToGroups(@PathParam("username") String username, UserGroupsEntity userGroupsEntity)
throws ServiceException {
plugin.addUserToGroups(username, userGroupsEntity);
return Response.status(Response.Status.CREATED).build();
}
@DELETE
public Response deleteUserFromGroups(@PathParam("username") String username, UserGroupsEntity userGroupsEntity)
throws ServiceException {
plugin.deleteUserFromGroups(username, userGroupsEntity);
return Response.status(Response.Status.OK).build();
}
}
| {
"content_hash": "1f1f188e7e40ddb63e23beb276988bbe",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 115,
"avg_line_length": 34.30434782608695,
"alnum_prop": 0.7572877059569075,
"repo_name": "Gugli/Openfire",
"id": "e09372f08f5e85bbe285d8ab1d2c956b3903e42a",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/plugins/userservice/src/java/org/jivesoftware/openfire/plugin/service/UserGroupService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3721"
},
{
"name": "C",
"bytes": "3814"
},
{
"name": "CSS",
"bytes": "500100"
},
{
"name": "Dockerfile",
"bytes": "1238"
},
{
"name": "HTML",
"bytes": "701889"
},
{
"name": "Java",
"bytes": "14273677"
},
{
"name": "JavaScript",
"bytes": "3765620"
},
{
"name": "Makefile",
"bytes": "1274"
},
{
"name": "Objective-C",
"bytes": "6879"
},
{
"name": "PLSQL",
"bytes": "763"
},
{
"name": "Shell",
"bytes": "31993"
}
],
"symlink_target": ""
} |
require "rails_helper"
RSpec.describe TimeslotMailer, type: :mailer do
describe "tutor_scheduled" do
let!(:timeslot) { FactoryGirl.create(:booked_timeslot)}
let!(:mail) { TimeslotMailer.tutor_scheduled(timeslot) }
it "renders the headers" do
expect(mail.subject).to eq("there's a board Scheduling Notification")
expect(mail.to).to eq(["notify@theresaboard.com"])
expect(mail.from).to eq(["notify@theresaboard.com"])
end
end
describe "student_scheduled" do
let!(:timeslot) { FactoryGirl.create(:booked_timeslot)}
let!(:mail) { TimeslotMailer.tutor_scheduled(timeslot) }
it "renders the headers" do
expect(mail.subject).to eq("there's a board Scheduling Notification")
expect(mail.to).to eq(["notify@theresaboard.com"])
expect(mail.from).to eq(["notify@theresaboard.com"])
end
end
describe "tutor_cancel" do
let!(:timeslot) { FactoryGirl.create(:booked_timeslot)}
let!(:mail) { TimeslotMailer.tutor_cancel(timeslot, timeslot.student) }
it "renders the headers" do
expect(mail.subject).to eq("there's a board Cancellation Notification")
expect(mail.to).to eq(["notify@theresaboard.com"])
expect(mail.from).to eq(["notify@theresaboard.com"])
end
end
describe "student_cancel" do
let!(:timeslot) { FactoryGirl.create(:booked_timeslot)}
let!(:mail) { TimeslotMailer.tutor_cancel(timeslot, timeslot.student) }
it "renders the headers" do
expect(mail.subject).to eq("there's a board Cancellation Notification")
expect(mail.to).to eq(["notify@theresaboard.com"])
expect(mail.from).to eq(["notify@theresaboard.com"])
end
end
end
| {
"content_hash": "e2e2880e298cecc26957c8c7a3104a5f",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 77,
"avg_line_length": 32.38461538461539,
"alnum_prop": 0.6852731591448931,
"repo_name": "theresaboard/theres-a-board",
"id": "00730bc45601fbbe1d6444ad0f0079348dbf8f39",
"size": "1684",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "spec/mailers/timeslot_mailer_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "1477"
},
{
"name": "CSS",
"bytes": "565022"
},
{
"name": "HTML",
"bytes": "40234"
},
{
"name": "JavaScript",
"bytes": "2217707"
},
{
"name": "Ruby",
"bytes": "79572"
}
],
"symlink_target": ""
} |
package org.apache.ignite.ml.nn.updaters;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableVectorToDoubleFunction;
import org.apache.ignite.ml.math.functions.IgniteFunction;
/**
* Interface for classes encapsulating parameters update logic.
*
* @param <M> Type of model to be updated.
* @param <P> Type of parameters needed for this updater.
*/
public interface ParameterUpdater<M, P extends UpdaterParams> {
/**
* Initializes the updater.
*
* @param mdl Model to be trained.
* @param loss Loss function.
*/
P init(M mdl, IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss);
/**
* Update updater parameters.
*
* @param mdl Model to be updated.
* @param updaterParameters Updater parameters to update.
* @param iteration Current trainer iteration.
* @param inputs Inputs.
* @param groundTruth True values.
* @return Updated parameters.
*/
P updateParams(M mdl, P updaterParameters, int iteration, Matrix inputs, Matrix groundTruth);
}
| {
"content_hash": "6f1e379bcd33cd8651c0835bd04557e4",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 97,
"avg_line_length": 31.86111111111111,
"alnum_prop": 0.7131647776809067,
"repo_name": "wmz7year/ignite",
"id": "e8e28fdec1b7687318885120754b61223af9dc4a",
"size": "1949",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/ml/src/main/java/org/apache/ignite/ml/nn/updaters/ParameterUpdater.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "40997"
},
{
"name": "C",
"bytes": "7463"
},
{
"name": "C#",
"bytes": "4383874"
},
{
"name": "C++",
"bytes": "2223075"
},
{
"name": "CSS",
"bytes": "110872"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "491764"
},
{
"name": "Java",
"bytes": "25694372"
},
{
"name": "JavaScript",
"bytes": "1073567"
},
{
"name": "M4",
"bytes": "5568"
},
{
"name": "Makefile",
"bytes": "102117"
},
{
"name": "Nginx",
"bytes": "3468"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "13480"
},
{
"name": "Scala",
"bytes": "681495"
},
{
"name": "Shell",
"bytes": "586288"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "24ca457f01e21f7109f4e5ba575373d5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "a432868ef35d9a93172ae508410f6598ee95966a",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Protozoa/Ciliophora/Heterotrichea/Heterotrichida/Metopidae/Metopus/Metopus caudatus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Proto.Cluster.Identity.Tests
{
public sealed class FailureInjectionStorage : IIdentityStorage
{
private const double SuccessRate = 0.8;
private static readonly Random Mayhem = new();
private readonly IIdentityStorage _identityStorageImplementation;
public FailureInjectionStorage(IIdentityStorage identityStorageImplementation)
=> _identityStorageImplementation = identityStorageImplementation;
public void Dispose() => _identityStorageImplementation.Dispose();
public Task<StoredActivation?> TryGetExistingActivation(ClusterIdentity clusterIdentity, CancellationToken ct)
{
MaybeFail();
return _identityStorageImplementation.TryGetExistingActivation(clusterIdentity, ct);
}
public Task<SpawnLock?> TryAcquireLock(ClusterIdentity clusterIdentity, CancellationToken ct)
{
MaybeFail();
return _identityStorageImplementation.TryAcquireLock(clusterIdentity, ct);
}
public Task<StoredActivation?> WaitForActivation(ClusterIdentity clusterIdentity, CancellationToken ct)
{
MaybeFail();
return _identityStorageImplementation.WaitForActivation(clusterIdentity, ct);
}
public Task RemoveLock(SpawnLock spawnLock, CancellationToken ct)
{
MaybeFail();
return _identityStorageImplementation.RemoveLock(spawnLock, ct);
}
public Task StoreActivation(string memberId, SpawnLock spawnLock, PID pid, CancellationToken ct)
{
if (Mayhem.NextDouble() > SuccessRate)
{
RemoveLock(spawnLock, ct);
throw Mayhem.Next() % 2 == 0
? new Exception("Activation fail")
: new LockNotFoundException("fake lock");
}
return _identityStorageImplementation.StoreActivation(memberId, spawnLock, pid, ct);
}
public Task RemoveActivation(ClusterIdentity clusterIdentity, PID pid, CancellationToken ct) =>
// MaybeFail();
_identityStorageImplementation.RemoveActivation(clusterIdentity, pid, ct);
public Task RemoveMember(string memberId, CancellationToken ct) => _identityStorageImplementation.RemoveMember(memberId, ct);
public Task Init() => _identityStorageImplementation.Init();
private static void MaybeFail()
{
if (Mayhem.NextDouble() > SuccessRate) throw new Exception("Chaos monkey at work");
}
}
} | {
"content_hash": "e8af0c906169c860c7025a16129d6280",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 133,
"avg_line_length": 38.55072463768116,
"alnum_prop": 0.6695488721804511,
"repo_name": "AsynkronIT/protoactor-dotnet",
"id": "57b2984365e2dc88d8e46cc2ee90b91e81377b8f",
"size": "2662",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "tests/Proto.Cluster.Identity.Tests/FailureInjectionStorage.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "282"
},
{
"name": "C#",
"bytes": "626451"
},
{
"name": "Dockerfile",
"bytes": "916"
}
],
"symlink_target": ""
} |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard;
import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider;
import com.intellij.ide.util.newProjectWizard.AddSupportForFrameworksPanel;
import com.intellij.ide.util.newProjectWizard.FrameworkSupportNodeBase;
import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase;
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.StatisticsAwareModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider;
import org.jetbrains.plugins.gradle.frameworkSupport.KotlinDslGradleFrameworkSupportProvider;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author Vladislav.Soroka
*/
public class GradleFrameworksWizardStep extends ModuleWizardStep implements Disposable, StatisticsAwareModuleWizardStep {
private JPanel myPanel;
private final AddSupportForFrameworksPanel myFrameworksPanel;
private JPanel myFrameworksPanelPlaceholder;
private JPanel myOptionsPanel;
@SuppressWarnings("unused") private JBLabel myFrameworksLabel;
private JCheckBox kdslCheckBox;
private final AbstractGradleModuleBuilder builder;
public GradleFrameworksWizardStep(WizardContext context, final AbstractGradleModuleBuilder builder) {
this.builder = builder;
Project project = context.getProject();
final LibrariesContainer container = LibrariesContainerFactory.createContainer(context.getProject());
FrameworkSupportModelBase model = new FrameworkSupportModelBase(project, builder, container) {
@NotNull
@Override
public String getBaseDirectoryForLibrariesPath() {
return StringUtil.notNullize(builder.getContentEntryPath());
}
};
myFrameworksPanel =
new AddSupportForFrameworksPanel(Collections.emptyList(), model, true, null);
setGradleFrameworkSupportProviders(Collections.singleton(
"java"/*KotlinDslGradleJavaFrameworkSupportProvider.ID*/));
Disposer.register(this, myFrameworksPanel);
myFrameworksPanelPlaceholder.add(myFrameworksPanel.getMainPanel());
ModuleBuilder.ModuleConfigurationUpdater configurationUpdater = new ModuleBuilder.ModuleConfigurationUpdater() {
@Override
public void update(@NotNull Module module, @NotNull ModifiableRootModel rootModel) {
myFrameworksPanel.addSupport(module, rootModel);
}
};
builder.addModuleConfigurationUpdater(configurationUpdater);
((CardLayout)myOptionsPanel.getLayout()).show(myOptionsPanel, "frameworks card");
kdslCheckBox.addActionListener((actionEvent) -> {
updateGradleFrameworkSupportProviders(kdslCheckBox.isSelected());
});
}
private void setKotlinDslGradleFrameworkSupportProviders(Set<String> selectedNodeIds) {
List<FrameworkSupportInModuleProvider> providers = new ArrayList<>();
Collections.addAll(providers, KotlinDslGradleFrameworkSupportProvider.EP_NAME.getExtensions());
myFrameworksPanel.setProviders(providers, Collections.emptySet(), selectedNodeIds);
}
private void setGradleFrameworkSupportProviders(Set<String> selectedNodeIds) {
List<FrameworkSupportInModuleProvider> providers = new ArrayList<>();
Collections.addAll(providers, GradleFrameworkSupportProvider.EP_NAME.getExtensions());
myFrameworksPanel.setProviders(providers, Collections.emptySet(), selectedNodeIds);
}
@Override
public JComponent getComponent() {
return myPanel;
}
@Override
public void updateDataModel() {
}
@Override
public void dispose() {
}
@Override
public void disposeUIResources() {
Disposer.dispose(this);
}
@Override
public void addCustomFeatureUsageData(@NotNull String eventId, @NotNull FeatureUsageData data) {
myFrameworksPanel.reportSelectedFrameworks(eventId, data);
data.addData("gradle-kotlin-dsl", kdslCheckBox.isSelected());
}
private void updateGradleFrameworkSupportProviders(boolean useKotlinDsl) {
builder.setUseKotlinDsl(kdslCheckBox.isSelected());
Set<String> selectedNodeIds = ContainerUtil.map2Set(myFrameworksPanel.getSelectedNodes(), FrameworkSupportNodeBase::getId);
if (useKotlinDsl) {
setKotlinDslGradleFrameworkSupportProviders(selectedNodeIds);
}
else {
setGradleFrameworkSupportProviders(selectedNodeIds);
}
}
@TestOnly
public void setUseKotlinDsl(boolean useKotlinDsl) {
kdslCheckBox.setSelected(useKotlinDsl);
updateGradleFrameworkSupportProviders(useKotlinDsl);
}
}
| {
"content_hash": "1037f5f3d675f66dae8031e0a48ddfc9",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 140,
"avg_line_length": 40.0431654676259,
"alnum_prop": 0.8020122170319799,
"repo_name": "allotria/intellij-community",
"id": "6467877b5ec4c2e82bec3a60cdc677325fb63bd8",
"size": "5566",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "plugins/gradle/java/src/service/project/wizard/GradleFrameworksWizardStep.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60580"
},
{
"name": "C",
"bytes": "195249"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "195810"
},
{
"name": "CMake",
"bytes": "1675"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groovy",
"bytes": "3197810"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1891055"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "164463076"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "4240307"
},
{
"name": "Lex",
"bytes": "147047"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "51270"
},
{
"name": "Objective-C",
"bytes": "27941"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6680"
},
{
"name": "Python",
"bytes": "25385564"
},
{
"name": "Roff",
"bytes": "37534"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "65705"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
class Gear
attr_reader :chainring, :cog
def initialize(chainring, cog)
@chainring = chainring
@cog = cog
end
def ratio
chainring / cog.to_f
end
end
puts Gear.new(52, 11).ratio
puts Gear.new(30, 27).ratio
| {
"content_hash": "abc69198a161a877b751dda35e8850e6",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 32,
"avg_line_length": 16.285714285714285,
"alnum_prop": 0.6666666666666666,
"repo_name": "etdev/ruby_notes",
"id": "b33da610d908c36cf83aa1ffe840c7572f71c736",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ruby_random/poodr/ch_2/19_gear.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9362"
}
],
"symlink_target": ""
} |
{% extends "photoshare/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% block content %}
<div style="max-width:250px;margin-left:auto;margin-right:auto;">
Your account is now activated
</div>
{% endblock %} | {
"content_hash": "ba95dfa4af42c7b6c8734224c18fc126",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 65,
"avg_line_length": 16.6,
"alnum_prop": 0.6746987951807228,
"repo_name": "sbabineau/django-intro",
"id": "e63af7104134cd767d5e668f4cb92df1696cacca",
"size": "249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "photoshare/templates/registration/activation_complete.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "29712"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="deploy" name="jse_adig">
<import file="${user.home}/conf/adligo/builds/jse-build.xml"/>
</project> | {
"content_hash": "37ae0b7cbc849bf5b9a289fc024509c5",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 63,
"avg_line_length": 42,
"alnum_prop": 0.6785714285714286,
"repo_name": "adligo/jse_adig.adligo.org",
"id": "5434ba3363ecdd1b9aeac2beea3181aa8fe870db",
"size": "168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "17616"
}
],
"symlink_target": ""
} |
//
// SFInjectionsNotificationsCenter.m
// dyci-framework
//
// Created by Paul Taykalo on 6/1/13.
// Copyright (c) 2013 Stanfy. All rights reserved.
//
#import "SFInjectionsNotificationsCenter.h"
#if TARGET_IPHONE_SIMULATOR
/*
notification.object will be the class that was injected
This notification is private due to discussion here https://github.com/DyCI/dyci-main/pull/51
*/
NSString * const SFInjectionsClassInjectedNotification = @"SFInjectionsClassInjectedNotification";
/*
notification.object will be the resource that was injected
This notification is private due to discussion here https://github.com/DyCI/dyci-main/pull/51
*/
NSString * const SFInjectionsResourceInjectedNotification = @"SFInjectionsResourceInjectedNotification";
@implementation SFInjectionsNotificationsCenter {
NSMutableDictionary * _observers;
}
+ (instancetype)sharedInstance {
static SFInjectionsNotificationsCenter * _instance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
if (!_instance) {
_instance = [[self alloc] init];
_instance->_observers = [NSMutableDictionary dictionary];
}
});
return _instance;
}
- (void)addObserver:(id<SFInjectionObserver>)observer {
[self addObserver:observer forClass:[observer class]];
}
- (void)removeObserver:(id<SFInjectionObserver>)observer {
[self removeObserver:observer ofClass:[observer class]];
}
- (void)removeObserver:(id<SFInjectionObserver>)observer ofClass:(Class)aClass {
@synchronized (_observers) {
NSMutableSet * observersPerClass = [_observers objectForKey:aClass];
if (observersPerClass) {
@synchronized (observersPerClass) {
[observersPerClass removeObject:observer];
}
}
}
}
- (void)addObserver:(id<SFInjectionObserver>)observer forClass:(Class)aClass {
if (!aClass) {
return;
}
@synchronized (_observers) {
NSMutableSet * observersPerClass = [_observers objectForKey:aClass];
if (!observersPerClass) {
observersPerClass = (__bridge_transfer NSMutableSet *) CFSetCreateMutable(nil, 0, nil);
[_observers setObject:observersPerClass forKey:aClass];
}
@synchronized (observersPerClass) {
[observersPerClass addObject:observer];
}
}
}
/*
This will notify about class injection
*/
- (void)notifyOnClassInjection:(Class)injectedClass {
[[NSNotificationCenter defaultCenter] postNotificationName:SFInjectionsClassInjectedNotification object:injectedClass];
int idx = 0;
@synchronized (_observers) {
for (NSMutableSet * observersPerClass in [_observers allValues]) {
@synchronized (observersPerClass) {
id anyObject = [observersPerClass anyObject];
if (self.notificationStategy == SFInjectionNotificationStrategyInjectedClassOnly
&& ![anyObject isKindOfClass:injectedClass]) {
continue;
}
for (id<SFInjectionObserver> observer in observersPerClass) {
[observer updateOnClassInjection];
idx++;
}
}
}
}
NSLog(@"%d instanses were notified on Class Injection by injecting class: (%@)", idx, NSStringFromClass(injectedClass));
}
/*
This will notiy all registered classes about that some resource was injected
*/
- (void)notifyOnResourceInjection:(NSString *)resourceInjection {
[[NSNotificationCenter defaultCenter] postNotificationName:SFInjectionsResourceInjectedNotification object:resourceInjection];
int idx = 0;
@synchronized (_observers) {
for (NSMutableSet * observersPerClass in [_observers allValues]) {
@synchronized (observersPerClass) {
for (id<SFInjectionObserver> observer in observersPerClass) {
[observer updateOnResourceInjection:resourceInjection];
idx++;
}
}
}
}
NSLog(@"%d classes instanses were notified on REsource Injection", idx);
}
@end
#endif | {
"content_hash": "63de7452314b18c3bd33a1305f818d62",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 130,
"avg_line_length": 30.544117647058822,
"alnum_prop": 0.6668271545498314,
"repo_name": "DyCI/dyci-main",
"id": "bdba8fc86a7b38b94dad9981e7d0c3313d9eb9c4",
"size": "4154",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dynamic Code Injection/dyci/Classes/Notifications/SFInjectionsNotificationsCenter.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "7127"
},
{
"name": "Objective-C",
"bytes": "50563"
},
{
"name": "Python",
"bytes": "11456"
},
{
"name": "Ruby",
"bytes": "11736"
},
{
"name": "Shell",
"bytes": "7664"
}
],
"symlink_target": ""
} |
using Bagombo.Models.ViewModels.Home;
using System;
using System.Collections.Generic;
using System.Text;
namespace Bagombo.Data.Query.Queries
{
public class GetAllPostsByDateViewModelQuery : IQuery<AllPostsViewModel>
{
}
}
| {
"content_hash": "56d16cea01ac08aab39e8954268bf7ce",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 74,
"avg_line_length": 21,
"alnum_prop": 0.7965367965367965,
"repo_name": "tylerlrhodes/bagombo",
"id": "fa83445d07e188c35c9139e43ef600786a3eaf5b",
"size": "233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Bagombo.Data/Query/Queries/GetAllPostsByDateViewModelQuery.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "235300"
},
{
"name": "CSS",
"bytes": "580"
},
{
"name": "HTML",
"bytes": "67052"
},
{
"name": "JavaScript",
"bytes": "4088"
},
{
"name": "PLpgSQL",
"bytes": "49812"
}
],
"symlink_target": ""
} |
<?php
/*
Safe sample
input : get the field userData from the variable $_GET via an object
Uses a special_chars_filter via filter_var function
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
class Input{
private $input;
public function getInput(){
return $this->input;
}
public function __construct(){
$this->input = $_GET['UserData'] ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS);
$tainted = $sanitized ;
$query = "(&(objectCategory=person)(objectClass=user)(cn='". $tainted . "'))";
$ds=ldap_connect("localhost");
$r=ldap_bind($ds);
$sr=ldap_search($ds,"o=My Company, c=US", $query);
ldap_close($ds);
?> | {
"content_hash": "66080c1731f8ee272723c6f9366acdb3",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 78,
"avg_line_length": 23.3,
"alnum_prop": 0.73635806253832,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "aab8209eb5ba176307590f5c87f0e7a1c015940f",
"size": "1631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Injection/CWE_90/safe/CWE_90__object-classicGet__func_FILTER-CLEANING-special_chars_filter__userByCN-concatenation_simple_quote.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>dictionaries: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.2 / dictionaries - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
dictionaries
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-20 20:17:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-20 20:17:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.5.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/dictionaries"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Dictionaries"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: modules"
"keyword: functors"
"keyword: search trees"
"category: Computer Science/Data Types and Data Structures"
"category: Miscellaneous/Extracted Programs/Data structures"
"date: 2003-02-6"
]
authors: [
"Pierre Castéran <casteran@labri.fr>"
]
bug-reports: "https://github.com/coq-contribs/dictionaries/issues"
dev-repo: "git+https://github.com/coq-contribs/dictionaries.git"
synopsis: "Dictionaries (with modules)"
description: """
This file contains a specification for dictionaries, and
an implementation using binary search trees. Coq's module system,
with module types and functors, is heavily used. It can be considered
as a certified version of an example proposed by Paulson in Standard ML.
A detailed description (in French) can be found in the chapter 11 of
The Coq'Art, the book written by Yves Bertot and Pierre Castéran
(please follow the link http://coq.inria.fr/doc-eng.html)"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/dictionaries/archive/v8.9.0.tar.gz"
checksum: "md5=d1a48827a1b710987adbf0366a63f64b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-dictionaries.8.9.0 coq.8.5.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2).
The following dependencies couldn't be met:
- coq-dictionaries -> coq >= 8.9 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dictionaries.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "c94ba788d3ab7a6f136bfb3030f41fba",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 159,
"avg_line_length": 41.57222222222222,
"alnum_prop": 0.5594013096351731,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "6c92de82ed4751a8c9b04881688e4beba2bc06fd",
"size": "7510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.2/dictionaries/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
eslint: {
target: ['SizeConstraint.js'],
options: {
config: '.eslintrc'
}
},
jscs: {
src: ['SizeConstraint.js'],
options: {
config: '.jscsrc'
}
},
jsdoc2md: {
separateOutputFilePerInput: {
options: {
index: true
},
files: [
{ src: 'SizeConstraint.js', dest: 'docs/SizeConstraint.md' }
]
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-jsdoc-to-markdown');
// Default task.
grunt.registerTask('default', ['eslint', 'jscs', 'jsdoc2md']);
};
| {
"content_hash": "393c52116d859e9d9bd4a63fbb8d9933",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 72,
"avg_line_length": 22,
"alnum_prop": 0.5454545454545454,
"repo_name": "IjzerenHein/famous-sizeconstraint",
"id": "b566c2c751b2c7f2519fe735235c9d05513f3006",
"size": "814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gruntfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1914"
},
{
"name": "HTML",
"bytes": "6420"
},
{
"name": "JavaScript",
"bytes": "13229"
}
],
"symlink_target": ""
} |
package main
import (
"context"
cx "cloud.google.com/go/dialogflow/cx/apiv3beta1"
cxpb "cloud.google.com/go/dialogflow/cx/apiv3beta1/cxpb"
)
func main() {
ctx := context.Background()
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in:
// https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
c, err := cx.NewVersionsClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &cxpb.CreateVersionRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3beta1/cxpb#CreateVersionRequest.
}
op, err := c.CreateVersion(ctx, req)
if err != nil {
// TODO: Handle error.
}
resp, err := op.Wait(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
// [END dialogflow_v3beta1_generated_Versions_CreateVersion_sync]
| {
"content_hash": "cb4c18b42badd347d32cf8b5a064aefb",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 99,
"avg_line_length": 27.45,
"alnum_prop": 0.7040072859744991,
"repo_name": "googleapis/google-cloud-go",
"id": "fcaf861bf110a5b2787612a7304894df957c0b5d",
"size": "1842",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/CreateVersion/main.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "10349"
},
{
"name": "C",
"bytes": "74"
},
{
"name": "Dockerfile",
"bytes": "1841"
},
{
"name": "Go",
"bytes": "7626642"
},
{
"name": "M4",
"bytes": "43723"
},
{
"name": "Makefile",
"bytes": "1455"
},
{
"name": "Python",
"bytes": "718"
},
{
"name": "Shell",
"bytes": "27309"
}
],
"symlink_target": ""
} |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.
using System;
using System.Reflection;
using Xunit;
using static Google.Cloud.Speech.V1Beta1.RecognitionConfig.Types;
namespace Google.Cloud.Speech.V1Beta1.Snippets
{
public class SpeechClientSnippets
{
[Fact]
public void SyncRecognize()
{
var audio = LoadResourceAudio("speech.raw");
// Snippet: SyncRecognize
SpeechClient client = SpeechClient.Create();
RecognitionConfig config = new RecognitionConfig { Encoding = AudioEncoding.Linear16, SampleRate = 16000 };
SyncRecognizeResponse response = client.SyncRecognize(config, audio);
Console.WriteLine(response);
// End snippet
Assert.Equal(
"this is a test file for the google cloud speech api",
response.Results[0].Alternatives[0].Transcript,
true);
}
private static RecognitionAudio LoadResourceAudio(string name)
{
var type = typeof(SpeechClientSnippets);
using (var stream = type.GetTypeInfo().Assembly.GetManifestResourceStream($"{type.Namespace}.{name}"))
{
return RecognitionAudio.FromStream(stream);
}
}
}
}
| {
"content_hash": "32babc22497d9809991c7a81b415b7e3",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 119,
"avg_line_length": 37.14,
"alnum_prop": 0.6591276252019386,
"repo_name": "ctaggart/google-cloud-dotnet",
"id": "babb00694f41714e7b0a20c61e695d80a8a814e2",
"size": "1859",
"binary": false,
"copies": "1",
"ref": "refs/heads/preview3",
"path": "apis/Google.Cloud.Speech.V1Beta1/Google.Cloud.Speech.V1Beta1.Snippets/SpeechClientSnippets.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "14"
},
{
"name": "C#",
"bytes": "4503442"
},
{
"name": "Python",
"bytes": "69477"
},
{
"name": "Shell",
"bytes": "14078"
}
],
"symlink_target": ""
} |
using Aqla.DtoHelpers;
namespace DtoHelpers.Example
{
class Container
{
// structs read-only controlled via get-set
public DtoExamplePlayerStruct StructWritable { get; set; } = new DtoExamplePlayerStruct();
public DtoExamplePlayerStruct StructReadOnly { get; } = new DtoExamplePlayerStruct();
// these are controlled by type so get-only
public DtoExamplePlayerClass ClassWritable { get; } = new DtoExamplePlayerClass();
// should be different type with copy-pasted members but get only
public DtoExamplePlayerClass ClassReadOnly { get; } = new DtoExamplePlayerClass();
public Ref<DtoExamplePlayerNew> NewWritable { get; } = new Ref<DtoExamplePlayerNew>();
public Getter<DtoExamplePlayerNew> NewReadOnly { get; } = new Getter<DtoExamplePlayerNew>();
}
} | {
"content_hash": "f8fe47a9a468bc80848258a2e5a33f3d",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 100,
"avg_line_length": 42.05,
"alnum_prop": 0.7074910820451843,
"repo_name": "AqlaSolutions/Aqla.DtoHelpers",
"id": "1aa56e7e7fae53fc47bc1fe7ccd2ae0cf4fe9bb3",
"size": "843",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Aqla.DtoHelpers/Example/Container.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10924"
}
],
"symlink_target": ""
} |
<configurations>
<configuration name="Test test_foo" class="CargoCommandConfiguration" show_console_on_std_err="false" show_console_on_std_out="false">
<parameters>
<option name="additionalArguments">
<list>
<option value="--package" />
<option value="test-package" />
<option value="--lib" />
<option value="test_foo" />
</list>
</option>
<option name="backtraceMode" value="2" />
<option name="channel" value="0" />
<option name="command" value="test" />
<option name="environmentVariables">
<map>
<entry key="FOO" value="BAR" />
</map>
</option>
<option name="nocapture" value="true" />
</parameters>
<module name="light_idea_test_case" />
</configuration>
</configurations>
| {
"content_hash": "9b68bfd9b73ece7245342fb704c10796",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 136,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.5776699029126213,
"repo_name": "himikof/intellij-rust",
"id": "ce48ace0cd79904a17bdd6a51a5a37eb9197c9f8",
"size": "824",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/resources/org/rust/cargo/runconfig/producers/fixtures/2017.1/ test configuration uses default environment.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "8593"
},
{
"name": "Java",
"bytes": "1121"
},
{
"name": "Kotlin",
"bytes": "1732761"
},
{
"name": "Lex",
"bytes": "19046"
},
{
"name": "RenderScript",
"bytes": "15"
},
{
"name": "Rust",
"bytes": "76504"
},
{
"name": "Shell",
"bytes": "760"
}
],
"symlink_target": ""
} |
{
expect(response.data.foo).toEqual("bar");
expect(response.status).toEqual(200);
expect(response.statusText).toEqual("OK");
expect(response.headers["content-type"]).toEqual("application/json");
done();
}
| {
"content_hash": "f34e7cf32102bd040af5dee83db82781",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 71,
"avg_line_length": 30.714285714285715,
"alnum_prop": 0.7069767441860465,
"repo_name": "stas-vilchik/bdd-ml",
"id": "12581d9f333db6a4640217faa0ae75920496ee44",
"size": "215",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "data/737.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6666795"
},
{
"name": "Python",
"bytes": "3199"
}
],
"symlink_target": ""
} |
.class Lcom/android/internal/widget/multiwaveview/GlowPadView$5;
.super Landroid/animation/AnimatorListenerAdapter;
.source "GlowPadView.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/android/internal/widget/multiwaveview/GlowPadView;->startWaveAnimation()V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/internal/widget/multiwaveview/GlowPadView;
# direct methods
.method constructor <init>(Lcom/android/internal/widget/multiwaveview/GlowPadView;)V
.locals 0
.parameter
.prologue
.line 791
iput-object p1, p0, Lcom/android/internal/widget/multiwaveview/GlowPadView$5;->this$0:Lcom/android/internal/widget/multiwaveview/GlowPadView;
invoke-direct {p0}, Landroid/animation/AnimatorListenerAdapter;-><init>()V
return-void
.end method
# virtual methods
.method public onAnimationEnd(Landroid/animation/Animator;)V
.locals 2
.parameter "animator"
.prologue
const/4 v1, 0x0
.line 793
iget-object v0, p0, Lcom/android/internal/widget/multiwaveview/GlowPadView$5;->this$0:Lcom/android/internal/widget/multiwaveview/GlowPadView;
#getter for: Lcom/android/internal/widget/multiwaveview/GlowPadView;->mPointCloud:Lcom/android/internal/widget/multiwaveview/PointCloud;
invoke-static {v0}, Lcom/android/internal/widget/multiwaveview/GlowPadView;->access$1100(Lcom/android/internal/widget/multiwaveview/GlowPadView;)Lcom/android/internal/widget/multiwaveview/PointCloud;
move-result-object v0
iget-object v0, v0, Lcom/android/internal/widget/multiwaveview/PointCloud;->waveManager:Lcom/android/internal/widget/multiwaveview/PointCloud$WaveManager;
invoke-virtual {v0, v1}, Lcom/android/internal/widget/multiwaveview/PointCloud$WaveManager;->setRadius(F)V
.line 794
iget-object v0, p0, Lcom/android/internal/widget/multiwaveview/GlowPadView$5;->this$0:Lcom/android/internal/widget/multiwaveview/GlowPadView;
#getter for: Lcom/android/internal/widget/multiwaveview/GlowPadView;->mPointCloud:Lcom/android/internal/widget/multiwaveview/PointCloud;
invoke-static {v0}, Lcom/android/internal/widget/multiwaveview/GlowPadView;->access$1100(Lcom/android/internal/widget/multiwaveview/GlowPadView;)Lcom/android/internal/widget/multiwaveview/PointCloud;
move-result-object v0
iget-object v0, v0, Lcom/android/internal/widget/multiwaveview/PointCloud;->waveManager:Lcom/android/internal/widget/multiwaveview/PointCloud$WaveManager;
invoke-virtual {v0, v1}, Lcom/android/internal/widget/multiwaveview/PointCloud$WaveManager;->setAlpha(F)V
.line 795
return-void
.end method
| {
"content_hash": "42dce5277dc1db3c3b1469fb046bc68c",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 203,
"avg_line_length": 39.41428571428571,
"alnum_prop": 0.7879666545849946,
"repo_name": "baidurom/devices-base_cm",
"id": "bd0ecb5f0737c7dcfd52ca10852486b556ab6fd5",
"size": "2759",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.2",
"path": "vendor/aosp/framework.jar.out/smali/com/android/internal/widget/multiwaveview/GlowPadView$5.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12555"
}
],
"symlink_target": ""
} |
package com.desno365.mods.Tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.desno365.mods.DesnoUtils;
import com.desno365.mods.R;
public class FragmentTab1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
String version = DesnoUtils.getMinecraftVersion(getActivity());
if(version != null) {
version = getResources().getString(R.string.minecraft_version_content, version);
} else {
version = getResources().getString(R.string.minecraft_not_installed);
}
TextView textVersion = (TextView) rootView.findViewById(R.id.installed_minecraft_version);
textVersion.setText(version);
return rootView;
}
}
| {
"content_hash": "c565f307e8aba51c9b17fbd30b646bd7",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 100,
"avg_line_length": 26.25,
"alnum_prop": 0.7777777777777778,
"repo_name": "Desno365/Desno365sMods",
"id": "e88f057890bbb6886211b6eb567fc081710726bc",
"size": "1543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/desno365/mods/Tabs/FragmentTab1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "206914"
}
],
"symlink_target": ""
} |
function EEG = re_ref(EEG, ref_type)
if ischar(ref_type) && strcmpi(ref_type, 'average')
EEG = pop_reref(EEG, []);
EEG = eeg_checkset(EEG);
else
if iscellstr(ref_type)
ref_ind = lix_elecfind(EEG.chanlocs, ref_type);
EEG = pop_reref(EEG, ref_ind);
EEG = eeg_checkset(EEG);
else
disp('ref_type must be string or cell string array')
return
end
end | {
"content_hash": "2afa0dae3ea1be9d04525559f813eece",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 54,
"avg_line_length": 24,
"alnum_prop": 0.675,
"repo_name": "lix90/eeglab_pipeline",
"id": "95c03a228fe5ad54ac7cb314bd556b38c877d2e9",
"size": "360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "miscellaneous/utilities/re_ref.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "8536"
},
{
"name": "Limbo",
"bytes": "380"
},
{
"name": "M",
"bytes": "802"
},
{
"name": "Matlab",
"bytes": "1842233"
}
],
"symlink_target": ""
} |
/*eslint-env mocha*/
/*global BOOMR_test,assert*/
describe("e2e/11-restiming/06-type-filter", function() {
var t = BOOMR_test;
var tf = BOOMR.plugins.TestFramework;
it("Should pass basic beacon validation", function(done) {
t.validateBeaconWasSent(done);
});
it("Should only have the one IMG in the filter (if ResourceTiming is supported)", function() {
if (t.isResourceTimingSupported()) {
var b = tf.lastBeacon();
var resources = ResourceTimingDecompression.decompressResources(JSON.parse(b.restiming));
// find our img
assert.equal(resources.length, 1);
assert.equal(resources[0].initiatorType, "img");
assert.include(resources[0].name, "img.jpg");
}
else {
this.skip();
}
});
});
| {
"content_hash": "e060fbd74410c335d4df3eb2f37c0aea",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 95,
"avg_line_length": 26.88888888888889,
"alnum_prop": 0.6914600550964187,
"repo_name": "lognormal/boomerang",
"id": "12a42aab876ebcbd5bb7549bb7b5a9e477ede2fd",
"size": "726",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/page-templates/11-restiming/06-type-filter.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "59333"
},
{
"name": "JavaScript",
"bytes": "305865"
},
{
"name": "Makefile",
"bytes": "1985"
},
{
"name": "Smarty",
"bytes": "3545"
}
],
"symlink_target": ""
} |
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>ru.job4j</groupId>
<artifactId>junior</artifactId>
<packaging>pom</packaging>
<version>2.0</version>
<name>junior</name>
<url>http://job4j.ru/</url>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modules>
<module>chapter_001</module>
<module>chapter_002</module>
<module>chapter_003</module>
<module>chapter_005</module>
<module>chapter_006</module>
<module>chapter_007</module>
<module>eLama</module>
<module>chapter_008</module>
</modules>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.20.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-sqlmap -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.17</version>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<compilerVersion>1.8</compilerVersion>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "1e9fafa64836a5a6df8546207731a8d4",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 89,
"avg_line_length": 33.63157894736842,
"alnum_prop": 0.5271629778672032,
"repo_name": "GitKashis/mkubar",
"id": "9ad86275c6a71ec9fc2239e5cb2e3cde33e0d44b",
"size": "4473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "129"
},
{
"name": "Java",
"bytes": "405644"
},
{
"name": "XSLT",
"bytes": "441"
}
],
"symlink_target": ""
} |
var child_process = require('child_process');
module.exports = function () {
return function (request, response, next) {
// Does the client even support gzip awesomeness?
if (!request.headers['accept-encoding'] ||
(request.headers['accept-encoding'] &&
request.headers['accept-encoding'].indexOf('gzip') <= -1)) {
return next();
}
var old_writeHead = response.writeHead,
old_write, old_end;
response.writeHead = function writeHead(code, headers) {
if (code === 304) {
response.writeHead = old_writeHead;
return response.writeHead(code, headers);
}
old_write = response.write;
old_end = response.end;
headers['Content-Encoding'] = 'gzip';
delete headers['Content-Length'];
response.writeHead = old_writeHead;
response.writeHead(code, headers);
var gzip = child_process.spawn('gzip', ['-9']),
paused;
response.write = function write(data, encoding) {
if (paused) return false;
return gzip.stdin.write(data, encoding);
};
response.end = function end(data, encoding) {
if (data) {
response.write(data, encoding);
}
return gzip.stdin.end();
};
response.addListener('drain', function () {
gzip.stdout.resume();
paused = false;
});
gzip.stdout.addListener('data', function (buffer) {
if (!old_write.call(response, buffer)) {
gzip.stdout.pause();
paused = true;
}
});
gzip.stdin.addListener('drain', function () {
paused = false;
response.emit('drain');
});
gzip.addListener('exit', function () {
response.write = old_write;
response.end = old_end;
response.end();
});
};
next();
};
};
| {
"content_hash": "9df1e654c90dfd89247e7009d64d7e40",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 69,
"avg_line_length": 26.4,
"alnum_prop": 0.564935064935065,
"repo_name": "roselleebarle04/eac",
"id": "369a56f3469d9fd988ea2b04bb86333c0cd03ec4",
"size": "1985",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "node_modules/middleware/gzip.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "454246"
},
{
"name": "HTML",
"bytes": "6820"
},
{
"name": "Handlebars",
"bytes": "58384"
},
{
"name": "JavaScript",
"bytes": "383346"
},
{
"name": "PHP",
"bytes": "690"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.