text
stringlengths
2
1.04M
meta
dict
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (global = global || self, factory(global.jQuery)); }(this, (function ($) { 'use strict'; $ = $ && Object.prototype.hasOwnProperty.call($, 'default') ? $['default'] : $; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global_1 = // eslint-disable-next-line no-undef check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof commonjsGlobal == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func Function('return this')(); var fails = function (exec) { try { return !!exec(); } catch (error) { return true; } }; // Thank's IE8 for his funny defineProperty var descriptors = !fails(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable var f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; var objectPropertyIsEnumerable = { f: f }; var createPropertyDescriptor = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var toString = {}.toString; var classofRaw = function (it) { return toString.call(it).slice(8, -1); }; var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings var indexedObject = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible var requireObjectCoercible = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // toObject with fallback for non-array-like ES3 strings var toIndexedObject = function (it) { return indexedObject(requireObjectCoercible(it)); }; var isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; // `ToPrimitive` abstract operation // https://tc39.github.io/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var toPrimitive = function (input, PREFERRED_STRING) { if (!isObject(input)) return input; var fn, val; if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; var hasOwnProperty = {}.hasOwnProperty; var has = function (it, key) { return hasOwnProperty.call(it, key); }; var document = global_1.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); var documentCreateElement = function (it) { return EXISTS ? document.createElement(it) : {}; }; // Thank's IE8 for his funny defineProperty var ie8DomDefine = !descriptors && !fails(function () { return Object.defineProperty(documentCreateElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (ie8DomDefine) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }; var objectGetOwnPropertyDescriptor = { f: f$1 }; var anObject = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (ie8DomDefine) try { return nativeDefineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var objectDefineProperty = { f: f$2 }; var createNonEnumerableProperty = descriptors ? function (object, key, value) { return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var setGlobal = function (key, value) { try { createNonEnumerableProperty(global_1, key, value); } catch (error) { global_1[key] = value; } return value; }; var SHARED = '__core-js_shared__'; var store = global_1[SHARED] || setGlobal(SHARED, {}); var sharedStore = store; var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof sharedStore.inspectSource != 'function') { sharedStore.inspectSource = function (it) { return functionToString.call(it); }; } var inspectSource = sharedStore.inspectSource; var WeakMap = global_1.WeakMap; var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); var shared = createCommonjsModule(function (module) { (module.exports = function (key, value) { return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.0', mode: 'global', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var postfix = Math.random(); var uid = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); }; var keys = shared('keys'); var sharedKey = function (key) { return keys[key] || (keys[key] = uid(key)); }; var hiddenKeys = {}; var WeakMap$1 = global_1.WeakMap; var set, get, has$1; var enforce = function (it) { return has$1(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (nativeWeakMap) { var store$1 = new WeakMap$1(); var wmget = store$1.get; var wmhas = store$1.has; var wmset = store$1.set; set = function (it, metadata) { wmset.call(store$1, it, metadata); return metadata; }; get = function (it) { return wmget.call(store$1, it) || {}; }; has$1 = function (it) { return wmhas.call(store$1, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return has(it, STATE) ? it[STATE] : {}; }; has$1 = function (it) { return has(it, STATE); }; } var internalState = { set: set, get: get, has: has$1, enforce: enforce, getterFor: getterFor }; var redefine = createCommonjsModule(function (module) { var getInternalState = internalState.get; var enforceInternalState = internalState.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global_1) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); }); var path = global_1; var aFunction = function (variable) { return typeof variable == 'function' ? variable : undefined; }; var getBuiltIn = function (namespace, method) { return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace]) : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method]; }; var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger var toInteger = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength var toLength = function (argument) { return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; var max = Math.max; var min$1 = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). var toAbsoluteIndex = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min$1(integer, length); }; // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIncludes = { // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; var indexOf = arrayIncludes.indexOf; var objectKeysInternal = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } return result; }; // IE8- don't enum bug keys var enumBugKeys = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return objectKeysInternal(O, hiddenKeys$1); }; var objectGetOwnPropertyNames = { f: f$3 }; var f$4 = Object.getOwnPropertySymbols; var objectGetOwnPropertySymbols = { f: f$4 }; // all object keys, includes non-enumerable and symbols var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = objectGetOwnPropertyNames.f(anObject(it)); var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var copyConstructorProperties = function (target, source) { var keys = ownKeys(source); var defineProperty = objectDefineProperty.f; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; var isForced_1 = isForced; var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global_1; } else if (STATIC) { target = global_1[TARGET] || setGlobal(TARGET, {}); } else { target = (global_1[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor$1(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; // `IsArray` abstract operation // https://tc39.github.io/ecma262/#sec-isarray var isArray = Array.isArray || function isArray(arg) { return classofRaw(arg) == 'Array'; }; // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject var toObject = function (argument) { return Object(requireObjectCoercible(argument)); }; var createProperty = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () { // Chrome 38 Symbol has incorrect toString conversion // eslint-disable-next-line no-undef return !String(Symbol()); }); var useSymbolAsUid = nativeSymbol // eslint-disable-next-line no-undef && !Symbol.sham // eslint-disable-next-line no-undef && typeof Symbol() == 'symbol'; var WellKnownSymbolsStore = shared('wks'); var Symbol$1 = global_1.Symbol; var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : uid; var wellKnownSymbol = function (name) { if (!has(WellKnownSymbolsStore, name)) { if (nativeSymbol && has(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name]; else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate = function (originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; var userAgent = getBuiltIn('navigator', 'userAgent') || ''; var process = global_1.process; var versions = process && process.versions; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); version = match[0] + match[1]; } else if (userAgent) { match = userAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = userAgent.match(/Chrome\/(\d+)/); if (match) version = match[1]; } } var v8Version = version && +version; var SPECIES$1 = wellKnownSymbol('species'); var arrayMethodHasSpeciesSupport = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return v8Version >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES$1] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = v8Version >= 51 || !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function (O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.github.io/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species _export({ target: 'Array', proto: true, forced: FORCED }, { concat: function concat(arg) { // eslint-disable-line no-unused-vars var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); /** * Bootstrap Table Ukrainian translation * Author: Vitaliy Timchenko <vitaliy.timchenko@gmail.com> */ $.fn.bootstrapTable.locales['uk-UA'] = { formatCopyRows: function formatCopyRows() { return 'Copy Rows'; }, formatPrint: function formatPrint() { return 'Print'; }, formatLoadingMessage: function formatLoadingMessage() { return 'Завантаження, будь ласка, зачекайте'; }, formatRecordsPerPage: function formatRecordsPerPage(pageNumber) { return "".concat(pageNumber, " \u0437\u0430\u043F\u0438\u0441\u0456\u0432 \u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443"); }, formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) { if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) { return "\u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E \u0437 ".concat(pageFrom, " \u043F\u043E ").concat(pageTo, ". \u0412\u0441\u044C\u043E\u0433\u043E: ").concat(totalRows, " (filtered from ").concat(totalNotFiltered, " total rows)"); } return "\u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E \u0437 ".concat(pageFrom, " \u043F\u043E ").concat(pageTo, ". \u0412\u0441\u044C\u043E\u0433\u043E: ").concat(totalRows); }, formatSRPaginationPreText: function formatSRPaginationPreText() { return 'previous page'; }, formatSRPaginationPageText: function formatSRPaginationPageText(page) { return "to page ".concat(page); }, formatSRPaginationNextText: function formatSRPaginationNextText() { return 'next page'; }, formatDetailPagination: function formatDetailPagination(totalRows) { return "Showing ".concat(totalRows, " rows"); }, formatClearSearch: function formatClearSearch() { return 'Очистити фільтри'; }, formatSearch: function formatSearch() { return 'Пошук'; }, formatNoMatches: function formatNoMatches() { return 'Не знайдено жодного запису'; }, formatPaginationSwitch: function formatPaginationSwitch() { return 'Hide/Show pagination'; }, formatPaginationSwitchDown: function formatPaginationSwitchDown() { return 'Show pagination'; }, formatPaginationSwitchUp: function formatPaginationSwitchUp() { return 'Hide pagination'; }, formatRefresh: function formatRefresh() { return 'Оновити'; }, formatToggle: function formatToggle() { return 'Змінити'; }, formatToggleOn: function formatToggleOn() { return 'Show card view'; }, formatToggleOff: function formatToggleOff() { return 'Hide card view'; }, formatColumns: function formatColumns() { return 'Стовпці'; }, formatColumnsToggleAll: function formatColumnsToggleAll() { return 'Toggle all'; }, formatFullscreen: function formatFullscreen() { return 'Fullscreen'; }, formatAllRows: function formatAllRows() { return 'All'; }, formatAutoRefresh: function formatAutoRefresh() { return 'Auto Refresh'; }, formatExport: function formatExport() { return 'Export data'; }, formatJumpTo: function formatJumpTo() { return 'GO'; }, formatAdvancedSearch: function formatAdvancedSearch() { return 'Advanced search'; }, formatAdvancedCloseButton: function formatAdvancedCloseButton() { return 'Close'; }, formatFilterControlSwitch: function formatFilterControlSwitch() { return 'Hide/Show controls'; }, formatFilterControlSwitchHide: function formatFilterControlSwitchHide() { return 'Hide controls'; }, formatFilterControlSwitchShow: function formatFilterControlSwitchShow() { return 'Show controls'; } }; $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['uk-UA']); })));
{ "content_hash": "2b46c8ff84c02fcd18bd62362fe8f4ec", "timestamp": "", "source": "github", "line_count": 777, "max_line_length": 246, "avg_line_length": 33.12741312741313, "alnum_prop": 0.6656177156177157, "repo_name": "cdnjs/cdnjs", "id": "f4712e5a295170dae4697928facf70440483d744", "size": "25835", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ajax/libs/bootstrap-table/1.18.0/locale/bootstrap-table-uk-UA.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require 'mkmf' raise unless have_library('rsync') have_header('librsync.h') create_makefile('lib_ruby_diff/lib_ruby_diff')
{ "content_hash": "ddf0f801a4b455bfe297ddf83b6a5f89", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 46, "avg_line_length": 20.833333333333332, "alnum_prop": 0.744, "repo_name": "daveallie/lib_ruby_diff", "id": "b1dba05afcbb075df4fe8d319378d29da2f0721e", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ext/lib_ruby_diff/extconf.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3297" }, { "name": "Ruby", "bytes": "4090" }, { "name": "Shell", "bytes": "87" } ], "symlink_target": "" }
/** * LineItemCreativeAssociationOperationErrorReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201302; public class LineItemCreativeAssociationOperationErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected LineItemCreativeAssociationOperationErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _NOT_ALLOWED = "NOT_ALLOWED"; public static final java.lang.String _NOT_APPLICABLE = "NOT_APPLICABLE"; public static final java.lang.String _CANNOT_ACTIVATE_INVALID_CREATIVE = "CANNOT_ACTIVATE_INVALID_CREATIVE"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final LineItemCreativeAssociationOperationErrorReason NOT_ALLOWED = new LineItemCreativeAssociationOperationErrorReason(_NOT_ALLOWED); public static final LineItemCreativeAssociationOperationErrorReason NOT_APPLICABLE = new LineItemCreativeAssociationOperationErrorReason(_NOT_APPLICABLE); public static final LineItemCreativeAssociationOperationErrorReason CANNOT_ACTIVATE_INVALID_CREATIVE = new LineItemCreativeAssociationOperationErrorReason(_CANNOT_ACTIVATE_INVALID_CREATIVE); public static final LineItemCreativeAssociationOperationErrorReason UNKNOWN = new LineItemCreativeAssociationOperationErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static LineItemCreativeAssociationOperationErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { LineItemCreativeAssociationOperationErrorReason enumeration = (LineItemCreativeAssociationOperationErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static LineItemCreativeAssociationOperationErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(LineItemCreativeAssociationOperationErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "LineItemCreativeAssociationOperationError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
{ "content_hash": "10a5a0a3a4470ecaeeacfeb400b02984", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 194, "avg_line_length": 50.17567567567568, "alnum_prop": 0.7374091031510908, "repo_name": "google-code-export/google-api-dfp-java", "id": "9e7effffb67737b14f089159b22def7d9f9486fe", "size": "3713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/google/api/ads/dfp/v201302/LineItemCreativeAssociationOperationErrorReason.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "39950935" } ], "symlink_target": "" }
 using System; using MindTouch.Tasking; namespace MindTouch.Threading { /// <summary> /// Provides extension methods to <see cref="IDispatchQueue"/> to simplify enqueuing of work to be invoked in a specific <see cref="TaskEnv"/>. /// </summary> public static class DispatchQueueEx { /// <summary> /// Enqueue a callback as a work item to be invoked with the current <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> public static void QueueWorkItemWithCurrentEnv(this IDispatchQueue dispatchQueue, Action callback) { dispatchQueue.QueueWorkItemWithCurrentEnv(callback, null); } /// <summary> /// Enqueue a callback as a work item to be invoked with a clone of the current <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> public static void QueueWorkItemWithClonedEnv(this IDispatchQueue dispatchQueue, Action callback) { dispatchQueue.QueueWorkItemWithEnv(callback, TaskEnv.Clone(), null); } /// <summary> /// Enqueue a callback as a work item to be invoked with a provided <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="env">Environment for work item invocation.</param> public static void QueueWorkItemWithEnv(this IDispatchQueue dispatchQueue, Action callback, TaskEnv env) { dispatchQueue.QueueWorkItemWithEnv(callback, env, null); } /// <summary> /// Enqueue a callback as a work item to be invoked with the current <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result QueueWorkItemWithCurrentEnv(this IDispatchQueue dispatchQueue, Action callback, Result result) { var current = TaskEnv.CurrentOrNull; if(current != null) { return dispatchQueue.QueueWorkItemWithEnv(callback, current, result); } if(result != null) { dispatchQueue.QueueWorkItem(delegate() { try { callback(); result.Return(); } catch(Exception e) { result.Throw(e); } }); return result; } dispatchQueue.QueueWorkItem(callback); return null; } /// <summary> /// Enqueue a callback as a work item to be invoked with a clone of the current <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result QueueWorkItemWithClonedEnv(this IDispatchQueue dispatchQueue, Action callback, Result result) { return dispatchQueue.QueueWorkItemWithEnv(callback, TaskEnv.Clone(), result); } /// <summary> /// Enqueue a callback as a work item to be invoked with a provided <see cref="TaskEnv"/>. /// </summary> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="env">Environment for work item invocation.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result QueueWorkItemWithEnv(this IDispatchQueue dispatchQueue, Action callback, TaskEnv env, Result result) { if(env == null) { throw new ArgumentException("env"); } dispatchQueue.QueueWorkItem(env.MakeAction(callback, result)); return result; } /// <summary> /// Enqueue a callback as a work item to be invoked with the current <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> public static void QueueWorkItemWithCurrentEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback) { dispatchQueue.QueueWorkItemWithCurrentEnv(callback, null); } /// <summary> /// Enqueue a callback as a work item to be invoked with a clone of the current <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> public static void QueueWorkItemWithClonedEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback) { dispatchQueue.QueueWorkItemWithEnv(callback, TaskEnv.Clone(), null); } /// <summary> /// Enqueue a callback as a work item to be invoked with a provided <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="env">Environment for work item invocation.</param> public static void QueueWorkItemWithEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback, TaskEnv env) { dispatchQueue.QueueWorkItemWithEnv(callback, env, null); } /// <summary> /// Enqueue a callback as a work item to be invoked with the current <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result<T> QueueWorkItemWithCurrentEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback, Result<T> result) { var current = TaskEnv.CurrentOrNull; if(current != null) { return dispatchQueue.QueueWorkItemWithEnv(callback, current, result); } if(result != null) { dispatchQueue.QueueWorkItem(delegate() { try { result.Return(callback()); } catch(Exception e) { result.Throw(e); } }); return result; } dispatchQueue.QueueWorkItem(() => callback()); return null; } /// <summary> /// Enqueue a callback as a work item to be invoked with a clone of the current <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result<T> QueueWorkItemWithClonedEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback, Result<T> result) { return dispatchQueue.QueueWorkItemWithEnv(callback, TaskEnv.Clone(), result); } /// <summary> /// Enqueue a callback as a work item to be invoked with a provided <see cref="TaskEnv"/>. /// </summary> /// <typeparam name="T">Result value type of callback.</typeparam> /// <param name="dispatchQueue">DispatchQueue to enqueue work into.</param> /// <param name="callback">Work item callback.</param> /// <param name="env">Environment for work item invocation.</param> /// <param name="result">Synchronization handle for work item.</param> /// <returns>The synchronization handle provided to the method.</returns> public static Result<T> QueueWorkItemWithEnv<T>(this IDispatchQueue dispatchQueue, Func<T> callback, TaskEnv env, Result<T> result) { if(env == null) { throw new ArgumentException("env"); } dispatchQueue.QueueWorkItem(env.MakeAction(callback, result)); return result; } } }
{ "content_hash": "7c1f96daf282370511620ceafea4e7ad", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 147, "avg_line_length": 52.785714285714285, "alnum_prop": 0.602789632559592, "repo_name": "yurigorokhov/DReAM", "id": "4386c34f428924fc94b1c800c0a35b713782c599", "size": "10452", "binary": false, "copies": "2", "ref": "refs/heads/2.2", "path": "src/mindtouch.dream/Threading/DispatchQueueEx.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "3755927" }, { "name": "XSLT", "bytes": "5764" } ], "symlink_target": "" }
/**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <sys/socket.h> #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <poll.h> #include <errno.h> #include <nuttx/fs/fs.h> #include <debug.h> #include <nuttx/net/net.h> #include <apps/netutils/telnetd.h> #include <apps/netutils/uiplib.h> #include "telnetd.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Telnet protocol stuff ****************************************************/ #define ISO_nl 0x0a #define ISO_cr 0x0d #define TELNET_IAC 255 #define TELNET_WILL 251 #define TELNET_WONT 252 #define TELNET_DO 253 #define TELNET_DONT 254 /* Device stuff *************************************************************/ #define TELNETD_DEVFMT "/dev/telnetd%d" /**************************************************************************** * Private Types ****************************************************************************/ /* The state of the telnet parser */ enum telnetd_state_e { STATE_NORMAL = 0, STATE_IAC, STATE_WILL, STATE_WONT, STATE_DO, STATE_DONT }; /* This structure describes the internal state of the driver */ struct telnetd_dev_s { sem_t td_exclsem; /* Enforces mutually exclusive access */ uint8_t td_state; /* (See telnetd_state_e) */ uint8_t td_pending; /* Number of valid, pending bytes in the rxbuffer */ uint8_t td_offset; /* Offset to the valid, pending bytes in the rxbuffer */ uint8_t td_crefs; /* The number of open references to the session */ int td_minor; /* Minor device number */ FAR struct socket td_psock; /* A clone of the internal socket structure */ char td_rxbuffer[CONFIG_TELNETD_RXBUFFER_SIZE]; char td_txbuffer[CONFIG_TELNETD_TXBUFFER_SIZE]; }; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Support functions */ #ifdef CONFIG_TELNETD_DUMPBUFFER static inline void telnetd_dumpbuffer(FAR const char *msg, FAR const char *buffer, unsigned int nbytes) #else # define telnetd_dumpbuffer(msg,buffer,nbytes) #endif static void telnetd_getchar(FAR struct telnetd_dev_s *priv, uint8_t ch, FAR char *dest, int *nread); static ssize_t telnetd_receive(FAR struct telnetd_dev_s *priv, FAR const char *src, size_t srclen, FAR char *dest, size_t destlen); static bool telnetd_putchar(FAR struct telnetd_dev_s *priv, uint8_t ch, int *nwritten); static void telnetd_sendopt(FAR struct telnetd_dev_s *priv, uint8_t option, uint8_t value); /* Character driver methods */ static int telnetd_open(FAR struct file *filep); static int telnetd_close(FAR struct file *filep); static ssize_t telnetd_read(FAR struct file *, FAR char *, size_t); static ssize_t telnetd_write(FAR struct file *, FAR const char *, size_t); static int telnetd_ioctl(FAR struct file *filep, int cmd, unsigned long arg); /**************************************************************************** * Private Data ****************************************************************************/ static const struct file_operations g_telnetdfops = { telnetd_open, /* open */ telnetd_close, /* close */ telnetd_read, /* read */ telnetd_write, /* write */ 0, /* seek */ telnetd_ioctl /* ioctl */ #ifndef CONFIG_DISABLE_POLL , 0 /* poll */ #endif }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: telnetd_dumpbuffer * * Description: * Dump a buffer of data (debug only) * ****************************************************************************/ #ifdef CONFIG_TELNETD_DUMPBUFFER static inline void telnetd_dumpbuffer(FAR const char *msg, FAR const char *buffer, unsigned int nbytes) { /* CONFIG_DEBUG, CONFIG_DEBUG_VERBOSE, and CONFIG_DEBUG_NET have to be * defined or the following does nothing. */ nvdbgdumpbuffer(msg, (FAR const uint8_t*)buffer, nbytes); } #endif /**************************************************************************** * Name: telnetd_getchar * * Description: * Get another character for the user received buffer from the RX buffer * ****************************************************************************/ static void telnetd_getchar(FAR struct telnetd_dev_s *priv, uint8_t ch, FAR char *dest, int *nread) { register int index; /* Ignore carriage returns */ if (ch != ISO_cr) { /* Add all other characters to the destination buffer */ index = *nread; dest[index++] = ch; *nread = index; } } /**************************************************************************** * Name: telnetd_receive * * Description: * Process a received telenet buffer * ****************************************************************************/ static ssize_t telnetd_receive(FAR struct telnetd_dev_s *priv, FAR const char *src, size_t srclen, FAR char *dest, size_t destlen) { int nread; uint8_t ch; nllvdbg("srclen: %d destlen: %d\n", srclen, destlen); for (nread = 0; srclen > 0 && nread < destlen; srclen--) { ch = *src++; nllvdbg("ch=%02x state=%d\n", ch, priv->td_state); switch (priv->td_state) { case STATE_IAC: if (ch == TELNET_IAC) { telnetd_getchar(priv, ch, dest, &nread); priv->td_state = STATE_NORMAL; } else { switch (ch) { case TELNET_WILL: priv->td_state = STATE_WILL; break; case TELNET_WONT: priv->td_state = STATE_WONT; break; case TELNET_DO: priv->td_state = STATE_DO; break; case TELNET_DONT: priv->td_state = STATE_DONT; break; default: priv->td_state = STATE_NORMAL; break; } } break; case STATE_WILL: /* Reply with a DONT */ telnetd_sendopt(priv, TELNET_DONT, ch); priv->td_state = STATE_NORMAL; break; case STATE_WONT: /* Reply with a DONT */ telnetd_sendopt(priv, TELNET_DONT, ch); priv->td_state = STATE_NORMAL; break; case STATE_DO: /* Reply with a WONT */ telnetd_sendopt(priv, TELNET_WONT, ch); priv->td_state = STATE_NORMAL; break; case STATE_DONT: /* Reply with a WONT */ telnetd_sendopt(priv, TELNET_WONT, ch); priv->td_state = STATE_NORMAL; break; case STATE_NORMAL: if (ch == TELNET_IAC) { priv->td_state = STATE_IAC; } else { telnetd_getchar(priv, ch, dest, &nread); } break; } } /* We get here if (1) all of the received bytes have been processed, or * (2) if the user's buffer has become full. */ if (srclen > 0) { /* Remember where we left off. These bytes will be returned the next * time that telnetd_read() is called. */ priv->td_pending = srclen; priv->td_offset = (src - priv->td_rxbuffer); } else { /* All of the received bytes were consumed */ priv->td_pending = 0; priv->td_offset = 0; } return nread; } /**************************************************************************** * Name: telnetd_putchar * * Description: * Put another character from the user buffer to the TX buffer. * ****************************************************************************/ static bool telnetd_putchar(FAR struct telnetd_dev_s *priv, uint8_t ch, int *nread) { register int index; bool ret = false; /* Ignore carriage returns (we will put these in automatically as necesary) */ if (ch != ISO_cr) { /* Add all other characters to the destination buffer */ index = *nread; priv->td_txbuffer[index++] = ch; /* Check for line feeds */ if (ch == ISO_nl) { /* Now add the carriage return */ priv->td_txbuffer[index++] = ISO_cr; priv->td_txbuffer[index++] = '\0'; /* End of line */ ret = true; } *nread = index; } return ret; } /**************************************************************************** * Name: telnetd_sendopt * * Description: * Send the telnet option bytes * ****************************************************************************/ static void telnetd_sendopt(FAR struct telnetd_dev_s *priv, uint8_t option, uint8_t value) { uint8_t optbuf[4]; optbuf[0] = TELNET_IAC; optbuf[1] = option; optbuf[2] = value; optbuf[3] = 0; telnetd_dumpbuffer("Send optbuf", optbuf, 4); if (psock_send(&priv->td_psock, optbuf, 4, 0) < 0) { nlldbg("Failed to send TELNET_IAC\n"); } } /**************************************************************************** * Name: telnetd_open ****************************************************************************/ static int telnetd_open(FAR struct file *filep) { FAR struct inode *inode = filep->f_inode; FAR struct telnetd_dev_s *priv = inode->i_private; int tmp; int ret; nllvdbg("td_crefs: %d\n", priv->td_crefs); /* O_NONBLOCK is not supported */ if (filep->f_oflags & O_NONBLOCK) { ret = -ENOSYS; goto errout; } /* Get exclusive access to the device structures */ ret = sem_wait(&priv->td_exclsem); if (ret < 0) { ret = -errno; goto errout; } /* Increment the count of references to the device. If this the first * time that the driver has been opened for this device, then initialize * the device. */ tmp = priv->td_crefs + 1; if (tmp > 255) { /* More than 255 opens; uint8_t would overflow to zero */ ret = -EMFILE; goto errout_with_sem; } /* Save the new open count on success */ priv->td_crefs = tmp; ret = OK; errout_with_sem: sem_post(&priv->td_exclsem); errout: return ret; } /**************************************************************************** * Name: telnetd_close ****************************************************************************/ static int telnetd_close(FAR struct file *filep) { FAR struct inode *inode = filep->f_inode; FAR struct telnetd_dev_s *priv = inode->i_private; FAR char *devpath; int ret; nllvdbg("td_crefs: %d\n", priv->td_crefs); /* Get exclusive access to the device structures */ ret = sem_wait(&priv->td_exclsem); if (ret < 0) { ret = -errno; goto errout; } /* Decrement the references to the driver. If the reference count will * decrement to 0, then uninitialize the driver. */ if (priv->td_crefs > 1) { /* Just decrement the reference count and release the semaphore */ priv->td_crefs--; sem_post(&priv->td_exclsem); } else { /* Re-create the path to the driver. */ sched_lock(); ret = asprintf(&devpath, TELNETD_DEVFMT, priv->td_minor); if (ret < 0) { nlldbg("Failed to allocate the driver path\n"); } else { /* Unregister the character driver */ ret = unregister_driver(devpath); if (ret < 0) { nlldbg("Failed to unregister the driver %s: %d\n", ret); } free(devpath); } /* Close the socket */ psock_close(&priv->td_psock); /* Release the driver memory. What if there are threads waiting on * td_exclsem? They will never be awakened! How could this happen? * crefs == 1 so there are no other open references to the driver. * But this could have if someone were trying to re-open the driver * after every other thread has closed it. That really should not * happen in the intended usage model. */ DEBUGASSERT(priv->td_exclsem.semcount == 0); sem_destroy(&priv->td_exclsem); free(priv); sched_unlock(); } ret = OK; errout: return ret; } /**************************************************************************** * Name: telnetd_read ****************************************************************************/ static ssize_t telnetd_read(FAR struct file *filep, FAR char *buffer, size_t len) { FAR struct inode *inode = filep->f_inode; FAR struct telnetd_dev_s *priv = inode->i_private; ssize_t ret; nllvdbg("len: %d\n", len); /* First, handle the case where there are still valid bytes left in the * I/O buffer from the last time that read was called. NOTE: Much of * what we read may be protocol stuff and may not correspond to user * data. Hence we need the loop and we need may need to call psock_recv() * multiple times in order to get data that the client is interested in. */ do { if (priv->td_pending > 0) { /* Process the buffered telnet data */ FAR const char *src = &priv->td_rxbuffer[priv->td_offset]; ret = telnetd_receive(priv, src, priv->td_pending, buffer, len); } /* Read a buffer of data from the telnet client */ else { ret = psock_recv(&priv->td_psock, priv->td_rxbuffer, CONFIG_TELNETD_RXBUFFER_SIZE, 0); /* Did we receive anything? */ if (ret > 0) { /* Yes.. Process the newly received telnet data */ telnetd_dumpbuffer("Received buffer", priv->td_rxbuffer, ret); ret = telnetd_receive(priv, priv->td_rxbuffer, ret, buffer, len); } /* Otherwise the peer closed the connection (ret == 0) or an error * occurred (ret < 0). */ else { break; } } } while (ret == 0); /* Return: * * ret > 0: The number of characters copied into the user buffer by * telnetd_receive(). * ret <= 0: Loss of connection or error events reported by recv(). */ return ret; } /**************************************************************************** * Name: telnetd_write ****************************************************************************/ static ssize_t telnetd_write(FAR struct file *filep, FAR const char *buffer, size_t len) { FAR struct inode *inode = filep->f_inode; FAR struct telnetd_dev_s *priv = inode->i_private; FAR const char *src = buffer; ssize_t nsent; ssize_t ret; int ncopied; char ch; bool eol; nllvdbg("len: %d\n", len); /* Process each character from the user buffer */ for (nsent = 0, ncopied = 0; nsent < len; nsent++) { /* Get the next character from the user buffer */ ch = *src++; /* Add the character to the TX buffer */ eol = telnetd_putchar(priv, ch, &ncopied); /* Was that the end of a line? Or is the buffer too full to hold the * next largest character sequence ("\r\n\0")? */ if (eol || ncopied > CONFIG_TELNETD_TXBUFFER_SIZE-3) { /* Yes... send the data now */ ret = psock_send(&priv->td_psock, priv->td_txbuffer, ncopied, 0); if (ret < 0) { nlldbg("psock_send failed '%s': %d\n", priv->td_txbuffer, ret); return ret; } /* Reset the index to the beginning of the TX buffer. */ ncopied = 0; } } /* Send anything remaining in the TX buffer */ if (ncopied > 0) { ret = psock_send(&priv->td_psock, priv->td_txbuffer, ncopied, 0); if (ret < 0) { nlldbg("psock_send failed '%s': %d\n", priv->td_txbuffer, ret); return ret; } } /* Notice that we don't actually return the number of bytes sent, but * rather, the number of bytes that the caller asked us to send. We may * have sent more bytes (because of CR-LF expansion and because of NULL * termination). But it confuses some logic if you report that you sent * more than you were requested to. */ return len; } /**************************************************************************** * Name: telnetd_poll ****************************************************************************/ static int telnetd_ioctl(FAR struct file *filep, int cmd, unsigned long arg) { #if 0 /* No ioctl commands are yet supported */ struct inode *inode = filep->f_inode; struct cdcacm_dev_s *priv = inode->i_private; int ret = OK; switch (cmd) { /* Add ioctl commands here */ default: ret = -ENOTTY; break; } return ret; #else return -ENOTTY; #endif } /**************************************************************************** * Name: telnetd_poll ****************************************************************************/ #if 0 /* Not used by this driver */ static int telnetd_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup) { FAR struct inode *inode = filep->f_inode; FAR struct telnetd_dev_s *priv = inode->i_private; } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: telnetd_driver * * Description: * Create a character driver to "wrap" the telnet session. This function * will select and return a unique path for the new telnet device. * * Parameters: * sd - The socket descriptor that represents the new telnet connection. * daemon - A pointer to the structure representing the overall state of * this instance of the telnet daemon. * * Return: * An allocated string represent the full path to the created driver. The * receiver of the string must de-allocate this memory when it is no longer * needed. NULL is returned on a failure. * ****************************************************************************/ FAR char *telnetd_driver(int sd, FAR struct telnetd_s *daemon) { FAR struct telnetd_dev_s *priv; FAR struct socket *psock; FAR char *devpath = NULL; int ret; /* Allocate instance data for this driver */ priv = (FAR struct telnetd_dev_s*)malloc(sizeof(struct telnetd_dev_s)); if (!priv) { nlldbg("Failed to allocate the driver data structure\n"); return NULL; } /* Initialize the allocated driver instance */ sem_init(&priv->td_exclsem, 0, 1); priv->td_state = STATE_NORMAL; priv->td_crefs = 0; priv->td_pending = 0; priv->td_offset = 0; /* Clone the internal socket structure. We do this so that it will be * independent of threads and of socket descriptors (the original socket * instance resided in the daemon's socket array). */ psock = sockfd_socket(sd); if (!psock) { nlldbg("Failed to convert sd=%d to a socket structure\n", sd); goto errout_with_dev; } ret = net_clone(psock, &priv->td_psock); if (ret < 0) { nlldbg("net_clone failed: %d\n", ret); goto errout_with_dev; } /* And close the original */ psock_close(psock); /* Allocation a unique minor device number of the telnet drvier */ do { ret = sem_wait(&g_telnetdcommon.exclsem); if (ret < 0 && errno != -EINTR) { goto errout_with_dev; } } while (ret < 0); priv->td_minor = g_telnetdcommon.minor; g_telnetdcommon.minor++; sem_post(&g_telnetdcommon.exclsem); /* Create a path and name for the driver. */ ret = asprintf(&devpath, TELNETD_DEVFMT, priv->td_minor); if (ret < 0) { nlldbg("Failed to allocate the driver path\n"); goto errout_with_dev; } /* Register the driver */ ret = register_driver(devpath, &g_telnetdfops, 0666, priv); if (ret < 0) { nlldbg("Failed to register the driver %s: %d\n", devpath, ret); goto errout_with_devpath; } /* Return the path to the new telnet driver */ return devpath; errout_with_devpath: free(devpath); errout_with_dev: free(priv); return NULL; }
{ "content_hash": "7e45cb5b8b136fd6630ae6f36ceb0fc0", "timestamp": "", "source": "github", "line_count": 796, "max_line_length": 89, "avg_line_length": 27.054020100502512, "alnum_prop": 0.49380078941258415, "repo_name": "Yndal/ArduPilot-SensorPlatform", "id": "1b04bfbe596408821f67b8fe349d42ddf16fa86c", "size": "23552", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "PX4NuttX/apps/netutils/telnetd/telnetd_driver.c", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "12462" }, { "name": "Assembly", "bytes": "799628" }, { "name": "Batchfile", "bytes": "68199" }, { "name": "C", "bytes": "55034159" }, { "name": "C#", "bytes": "9917" }, { "name": "C++", "bytes": "13663242" }, { "name": "CMake", "bytes": "13681" }, { "name": "CSS", "bytes": "6280" }, { "name": "EmberScript", "bytes": "19928" }, { "name": "GDB", "bytes": "744" }, { "name": "Groff", "bytes": "43610" }, { "name": "HTML", "bytes": "9849" }, { "name": "Io", "bytes": "286" }, { "name": "Java", "bytes": "4394945" }, { "name": "Lex", "bytes": "13878" }, { "name": "Lua", "bytes": "87871" }, { "name": "M4", "bytes": "15467" }, { "name": "Makefile", "bytes": "8807880" }, { "name": "Matlab", "bytes": "185473" }, { "name": "Objective-C", "bytes": "24203" }, { "name": "OpenEdge ABL", "bytes": "12712" }, { "name": "PHP", "bytes": "484" }, { "name": "Pascal", "bytes": "253102" }, { "name": "Perl", "bytes": "17902" }, { "name": "Processing", "bytes": "168008" }, { "name": "Python", "bytes": "1785059" }, { "name": "Ruby", "bytes": "7108" }, { "name": "Scilab", "bytes": "1502" }, { "name": "Shell", "bytes": "1276765" }, { "name": "Yacc", "bytes": "30289" } ], "symlink_target": "" }
package com.linkedin.thirdeye.datalayer.bao; import com.linkedin.thirdeye.datalayer.DaoTestUtils; import com.linkedin.thirdeye.datasource.DAORegistry; import java.util.List; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.linkedin.thirdeye.datalayer.dto.DataCompletenessConfigDTO; public class TestDataCompletenessConfigManager { private Long dataCompletenessConfigId1; private Long dataCompletenessConfigId2; private static String collection1 = "my dataset1"; private DateTime now = new DateTime(); private DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmm"); private DAOTestBase testDAOProvider; private DataCompletenessConfigManager dataCompletenessConfigDAO; @BeforeClass void beforeClass() { testDAOProvider = DAOTestBase.getInstance(); DAORegistry daoRegistry = DAORegistry.getInstance(); dataCompletenessConfigDAO = daoRegistry.getDataCompletenessConfigDAO(); } @AfterClass(alwaysRun = true) void afterClass() { testDAOProvider.cleanup(); } @Test public void testCreate() { dataCompletenessConfigId1 = dataCompletenessConfigDAO. save(DaoTestUtils.getTestDataCompletenessConfig(collection1, now.getMillis(), dateTimeFormatter.print(now.getMillis()), true)); dataCompletenessConfigId2 = dataCompletenessConfigDAO. save(DaoTestUtils.getTestDataCompletenessConfig(collection1, now.minusHours(1).getMillis(), dateTimeFormatter.print(now.minusHours(1).getMillis()), false)); Assert.assertNotNull(dataCompletenessConfigId1); Assert.assertNotNull(dataCompletenessConfigId2); List<DataCompletenessConfigDTO> dataCompletenessConfigDTOs = dataCompletenessConfigDAO.findAll(); Assert.assertEquals(dataCompletenessConfigDTOs.size(), 2); } @Test(dependsOnMethods = {"testCreate"}) public void testFind() { List<DataCompletenessConfigDTO> dataCompletenessConfigDTOs = dataCompletenessConfigDAO.findAllByDataset(collection1); Assert.assertEquals(dataCompletenessConfigDTOs.get(0).getDataset(), collection1); dataCompletenessConfigDTOs = dataCompletenessConfigDAO.findAllInTimeRange(now.minusMinutes(30).getMillis(), new DateTime().getMillis()); Assert.assertEquals(dataCompletenessConfigDTOs.size(), 1); dataCompletenessConfigDTOs = dataCompletenessConfigDAO.findAllByTimeOlderThan(new DateTime().getMillis()); Assert.assertEquals(dataCompletenessConfigDTOs.size(), 2); dataCompletenessConfigDTOs = dataCompletenessConfigDAO.findAllByTimeOlderThanAndStatus(new DateTime().getMillis(), true); Assert.assertEquals(dataCompletenessConfigDTOs.size(), 1); DataCompletenessConfigDTO config = dataCompletenessConfigDAO.findByDatasetAndDateSDF(collection1, dateTimeFormatter.print(now.getMillis())); Assert.assertNotNull(config); Assert.assertEquals(config.getId(), dataCompletenessConfigId1); config = dataCompletenessConfigDAO.findByDatasetAndDateMS(collection1, now.minusHours(1).getMillis()); Assert.assertNotNull(config); Assert.assertEquals(config.getId(), dataCompletenessConfigId2); } @Test(dependsOnMethods = { "testFind" }) public void testUpdate() { DataCompletenessConfigDTO dataCompletenessConfigDTO = dataCompletenessConfigDAO.findById(dataCompletenessConfigId2); Assert.assertNotNull(dataCompletenessConfigDTO); Assert.assertFalse(dataCompletenessConfigDTO.isTimedOut()); dataCompletenessConfigDTO.setTimedOut(true); dataCompletenessConfigDAO.update(dataCompletenessConfigDTO); dataCompletenessConfigDTO = dataCompletenessConfigDAO.findById(dataCompletenessConfigId2); Assert.assertNotNull(dataCompletenessConfigDTO); Assert.assertTrue(dataCompletenessConfigDTO.isTimedOut()); } @Test(dependsOnMethods = { "testUpdate" }) public void testDelete() { dataCompletenessConfigDAO.deleteById(dataCompletenessConfigId2); DataCompletenessConfigDTO dataCompletenessConfigDTO = dataCompletenessConfigDAO.findById(dataCompletenessConfigId2); Assert.assertNull(dataCompletenessConfigDTO); } }
{ "content_hash": "a4c435a0e6f0d9058b171625334776e6", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 164, "avg_line_length": 41.35576923076923, "alnum_prop": 0.8007440130202279, "repo_name": "fx19880617/pinot-1", "id": "4af0b2fd58f096bf57d317448bd88a99f167fd5e", "size": "4938", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thirdeye/thirdeye-pinot/src/test/java/com/linkedin/thirdeye/datalayer/bao/TestDataCompletenessConfigManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "4620" }, { "name": "Batchfile", "bytes": "7738" }, { "name": "CSS", "bytes": "925082" }, { "name": "FreeMarker", "bytes": "243834" }, { "name": "HTML", "bytes": "275258" }, { "name": "Java", "bytes": "14422749" }, { "name": "JavaScript", "bytes": "5194066" }, { "name": "Makefile", "bytes": "8076" }, { "name": "Python", "bytes": "36574" }, { "name": "Shell", "bytes": "51677" }, { "name": "Thrift", "bytes": "5028" } ], "symlink_target": "" }
![backup banner](backup_hrz.png) An application data backup creates an archive file that contains the database, all repositories and all attachments. You can only restore a backup to **exactly the same version and type (CE/EE)** of GitLab on which it was created. The best way to migrate your repositories from one server to another is through backup restore. ## Backup GitLab provides a simple command line interface to backup your whole installation, and is flexible enough to fit your needs. ### Backup timestamp >**Note:** In GitLab 9.2 the timestamp format was changed from `EPOCH_YYYY_MM_DD` to `EPOCH_YYYY_MM_DD_GitLab version`, for example `1493107454_2017_04_25` would become `1493107454_2017_04_25_9.1.0`. The backup archive will be saved in `backup_path`, which is specified in the `config/gitlab.yml` file. The filename will be `[TIMESTAMP]_gitlab_backup.tar`, where `TIMESTAMP` identifies the time at which each backup was created, plus the GitLab version. The timestamp is needed if you need to restore GitLab and multiple backups are available. For example, if the backup name is `1493107454_2017_04_25_9.1.0_gitlab_backup.tar`, then the timestamp is `1493107454_2017_04_25_9.1.0`. ### Creating a backup of the GitLab system Use this command if you've installed GitLab with the Omnibus package: ``` sudo gitlab-rake gitlab:backup:create ``` Use this if you've installed GitLab from source: ``` sudo -u git -H bundle exec rake gitlab:backup:create RAILS_ENV=production ``` If you are running GitLab within a Docker container, you can run the backup from the host: ``` docker exec -t <container name> gitlab-rake gitlab:backup:create ``` Example output: ``` Dumping database tables: - Dumping table events... [DONE] - Dumping table issues... [DONE] - Dumping table keys... [DONE] - Dumping table merge_requests... [DONE] - Dumping table milestones... [DONE] - Dumping table namespaces... [DONE] - Dumping table notes... [DONE] - Dumping table projects... [DONE] - Dumping table protected_branches... [DONE] - Dumping table schema_migrations... [DONE] - Dumping table services... [DONE] - Dumping table snippets... [DONE] - Dumping table taggings... [DONE] - Dumping table tags... [DONE] - Dumping table users... [DONE] - Dumping table users_projects... [DONE] - Dumping table web_hooks... [DONE] - Dumping table wikis... [DONE] Dumping repositories: - Dumping repository abcd... [DONE] Creating backup archive: $TIMESTAMP_gitlab_backup.tar [DONE] Deleting tmp directories...[DONE] Deleting old backups... [SKIPPING] ``` ### Backup strategy option > **Note:** Introduced as an option in GitLab 8.17. The default backup strategy is to essentially stream data from the respective data locations to the backup using the Linux command `tar` and `gzip`. This works fine in most cases, but can cause problems when data is rapidly changing. When data changes while `tar` is reading it, the error `file changed as we read it` may occur, and will cause the backup process to fail. To combat this, 8.17 introduces a new backup strategy called `copy`. The strategy copies data files to a temporary location before calling `tar` and `gzip`, avoiding the error. A side-effect is that the backup process with take up to an additional 1X disk space. The process does its best to clean up the temporary files at each stage so the problem doesn't compound, but it could be a considerable change for large installations. This is why the `copy` strategy is not the default in 8.17. To use the `copy` strategy instead of the default streaming strategy, specify `STRATEGY=copy` in the Rake task command. For example, `sudo gitlab-rake gitlab:backup:create STRATEGY=copy`. ### Excluding specific directories from the backup You can choose what should be backed up by adding the environment variable `SKIP`. The available options are: - `db` (database) - `uploads` (attachments) - `repositories` (Git repositories data) - `builds` (CI job output logs) - `artifacts` (CI job artifacts) - `lfs` (LFS objects) - `registry` (Container Registry images) - `pages` (Pages content) Use a comma to specify several options at the same time: ``` # use this command if you've installed GitLab with the Omnibus package sudo gitlab-rake gitlab:backup:create SKIP=db,uploads # if you've installed GitLab from source sudo -u git -H bundle exec rake gitlab:backup:create SKIP=db,uploads RAILS_ENV=production ``` ### Uploading backups to a remote (cloud) storage Starting with GitLab 7.4 you can let the backup script upload the '.tar' file it creates. It uses the [Fog library](http://fog.io/) to perform the upload. In the example below we use Amazon S3 for storage, but Fog also lets you use [other storage providers](http://fog.io/storage/). GitLab [imports cloud drivers](https://gitlab.com/gitlab-org/gitlab-ce/blob/30f5b9a5b711b46f1065baf755e413ceced5646b/Gemfile#L88) for AWS, Google, OpenStack Swift, Rackspace and Aliyun as well. A local driver is [also available](#uploading-to-locally-mounted-shares). For omnibus packages, add the following to `/etc/gitlab/gitlab.rb`: ```ruby gitlab_rails['backup_upload_connection'] = { 'provider' => 'AWS', 'region' => 'eu-west-1', 'aws_access_key_id' => 'AKIAKIAKI', 'aws_secret_access_key' => 'secret123' # If using an IAM Profile, leave aws_access_key_id & aws_secret_access_key empty # ie. 'aws_access_key_id' => '', # 'use_iam_profile' => 'true' } gitlab_rails['backup_upload_remote_directory'] = 'my.s3.bucket' ``` Make sure to run `sudo gitlab-ctl reconfigure` after editing `/etc/gitlab/gitlab.rb` to reflect the changes. For installations from source: ```yaml backup: # snip upload: # Fog storage connection settings, see http://fog.io/storage/ . connection: provider: AWS region: eu-west-1 aws_access_key_id: AKIAKIAKI aws_secret_access_key: 'secret123' # If using an IAM Profile, leave aws_access_key_id & aws_secret_access_key empty # ie. aws_access_key_id: '' # use_iam_profile: 'true' # The remote 'directory' to store your backups. For S3, this would be the bucket name. remote_directory: 'my.s3.bucket' # Turns on AWS Server-Side Encryption with Amazon S3-Managed Keys for backups, this is optional # encryption: 'AES256' # Specifies Amazon S3 storage class to use for backups, this is optional # storage_class: 'STANDARD' ``` If you are uploading your backups to S3 you will probably want to create a new IAM user with restricted access rights. To give the upload user access only for uploading backups create the following IAM profile, replacing `my.s3.bucket` with the name of your bucket: ```json { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1412062044000", "Effect": "Allow", "Action": [ "s3:AbortMultipartUpload", "s3:GetBucketAcl", "s3:GetBucketLocation", "s3:GetObject", "s3:GetObjectAcl", "s3:ListBucketMultipartUploads", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::my.s3.bucket/*" ] }, { "Sid": "Stmt1412062097000", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:ListAllMyBuckets" ], "Resource": [ "*" ] }, { "Sid": "Stmt1412062128000", "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::my.s3.bucket" ] } ] } ``` ### Uploading to locally mounted shares You may also send backups to a mounted share (`NFS` / `CIFS` / `SMB` / etc.) by using the Fog [`Local`](https://github.com/fog/fog-local#usage) storage provider. The directory pointed to by the `local_root` key **must** be owned by the `git` user **when mounted** (mounting with the `uid=` of the `git` user for `CIFS` and `SMB`) or the user that you are executing the backup tasks under (for omnibus packages, this is the `git` user). The `backup_upload_remote_directory` **must** be set in addition to the `local_root` key. This is the sub directory inside the mounted directory that backups will be copied to, and will be created if it does not exist. If the directory that you want to copy the tarballs to is the root of your mounted directory, just use `.` instead. For omnibus packages: ```ruby gitlab_rails['backup_upload_connection'] = { :provider => 'Local', :local_root => '/mnt/backups' } # The directory inside the mounted folder to copy backups to # Use '.' to store them in the root directory gitlab_rails['backup_upload_remote_directory'] = 'gitlab_backups' ``` For installations from source: ```yaml backup: # snip upload: # Fog storage connection settings, see http://fog.io/storage/ . connection: provider: Local local_root: '/mnt/backups' # The directory inside the mounted folder to copy backups to # Use '.' to store them in the root directory remote_directory: 'gitlab_backups' ``` ### Specifying a custom directory for backups If you want to group your backups you can pass a `DIRECTORY` environment variable: ``` sudo gitlab-rake gitlab:backup:create DIRECTORY=daily sudo gitlab-rake gitlab:backup:create DIRECTORY=weekly ``` ### Backup archive permissions The backup archives created by GitLab (`1393513186_2014_02_27_gitlab_backup.tar`) will have owner/group git:git and 0600 permissions by default. This is meant to avoid other system users reading GitLab's data. If you need the backup archives to have different permissions you can use the 'archive_permissions' setting. ``` # In /etc/gitlab/gitlab.rb, for omnibus packages gitlab_rails['backup_archive_permissions'] = 0644 # Makes the backup archives world-readable ``` ``` # In gitlab.yml, for installations from source: backup: archive_permissions: 0644 # Makes the backup archives world-readable ``` ### Storing configuration files Please be informed that a backup does not store your configuration files. One reason for this is that your database contains encrypted information for two-factor authentication. Storing encrypted information along with its key in the same place defeats the purpose of using encryption in the first place! If you use an Omnibus package please see the [instructions in the readme to backup your configuration](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md#backup-and-restore-omnibus-gitlab-configuration). If you have a cookbook installation there should be a copy of your configuration in Chef. If you installed from source, please consider backing up your `config/secrets.yml` file, `gitlab.yml` file, any SSL keys and certificates, and your [SSH host keys](https://superuser.com/questions/532040/copy-ssh-keys-from-one-server-to-another-server/532079#532079). At the very **minimum** you should backup `/etc/gitlab/gitlab.rb` and `/etc/gitlab/gitlab-secrets.json` (Omnibus), or `/home/git/gitlab/config/secrets.yml` (source) to preserve your database encryption key. ### Configuring cron to make daily backups >**Note:** The following cron jobs do not [backup your GitLab configuration files](#storing-configuration-files) or [SSH host keys](https://superuser.com/questions/532040/copy-ssh-keys-from-one-server-to-another-server/532079#532079). **For Omnibus installations** To schedule a cron job that backs up your repositories and GitLab metadata, use the root user: ``` sudo su - crontab -e ``` There, add the following line to schedule the backup for everyday at 2 AM: ``` 0 2 * * * /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1 ``` You may also want to set a limited lifetime for backups to prevent regular backups using all your disk space. To do this add the following lines to `/etc/gitlab/gitlab.rb` and reconfigure: ``` # limit backup lifetime to 7 days - 604800 seconds gitlab_rails['backup_keep_time'] = 604800 ``` Note that the `backup_keep_time` configuration option only manages local files. GitLab does not automatically prune old files stored in a third-party object storage (e.g., AWS S3) because the user may not have permission to list and delete files. We recommend that you configure the appropriate retention policy for your object storage. For example, you can configure [the S3 backup policy as described here](http://stackoverflow.com/questions/37553070/gitlab-omnibus-delete-backup-from-amazon-s3). **For installation from source** ``` cd /home/git/gitlab sudo -u git -H editor config/gitlab.yml # Enable keep_time in the backup section to automatically delete old backups sudo -u git crontab -e # Edit the crontab for the git user ``` Add the following lines at the bottom: ``` # Create a full backup of the GitLab repositories and SQL database every day at 4am 0 4 * * * cd /home/git/gitlab && PATH=/usr/local/bin:/usr/bin:/bin bundle exec rake gitlab:backup:create RAILS_ENV=production CRON=1 ``` The `CRON=1` environment setting tells the backup script to suppress all progress output if there are no errors. This is recommended to reduce cron spam. ## Restore GitLab provides a simple command line interface to backup your whole installation, and is flexible enough to fit your needs. The [restore prerequisites section](#restore-prerequisites) includes crucial information. Make sure to read and test the whole restore process at least once before attempting to perform it in a production environment. You can only restore a backup to **exactly the same version and type (CE/EE)** of GitLab that you created it on, for example CE 9.1.0. ### Restore prerequisites You need to have a working GitLab installation before you can perform a restore. This is mainly because the system user performing the restore actions ('git') is usually not allowed to create or delete the SQL database it needs to import data into ('gitlabhq_production'). All existing data will be either erased (SQL) or moved to a separate directory (repositories, uploads). To restore a backup, you will also need to restore `/etc/gitlab/gitlab-secrets.json` (for Omnibus packages) or `/home/git/gitlab/.secret` (for installations from source). This file contains the database encryption key, [CI secret variables](../ci/variables/README.md#secret-variables), and secret variables used for [two-factor authentication](../user/profile/account/two_factor_authentication.md). If you fail to restore this encryption key file along with the application data backup, users with two-factor authentication enabled and GitLab Runners will lose access to your GitLab server. Depending on your case, you might want to run the restore command with one or more of the following options: - `BACKUP=timestamp_of_backup` - Required if more than one backup exists. Read what the [backup timestamp is about](#backup-timestamp). - `force=yes` - Do not ask if the authorized_keys file should get regenerated. ### Restore for installation from source ``` # Stop processes that are connected to the database sudo service gitlab stop bundle exec rake gitlab:backup:restore RAILS_ENV=production ``` Example output: ``` Unpacking backup... [DONE] Restoring database tables: -- create_table("events", {:force=>true}) -> 0.2231s [...] - Loading fixture events...[DONE] - Loading fixture issues...[DONE] - Loading fixture keys...[SKIPPING] - Loading fixture merge_requests...[DONE] - Loading fixture milestones...[DONE] - Loading fixture namespaces...[DONE] - Loading fixture notes...[DONE] - Loading fixture projects...[DONE] - Loading fixture protected_branches...[SKIPPING] - Loading fixture schema_migrations...[DONE] - Loading fixture services...[SKIPPING] - Loading fixture snippets...[SKIPPING] - Loading fixture taggings...[SKIPPING] - Loading fixture tags...[SKIPPING] - Loading fixture users...[DONE] - Loading fixture users_projects...[DONE] - Loading fixture web_hooks...[SKIPPING] - Loading fixture wikis...[SKIPPING] Restoring repositories: - Restoring repository abcd... [DONE] Deleting tmp directories...[DONE] ``` ### Restore for Omnibus installations This procedure assumes that: - You have installed the **exact same version and type (CE/EE)** of GitLab Omnibus with which the backup was created. - You have run `sudo gitlab-ctl reconfigure` at least once. - GitLab is running. If not, start it using `sudo gitlab-ctl start`. First make sure your backup tar file is in the backup directory described in the `gitlab.rb` configuration `gitlab_rails['backup_path']`. The default is `/var/opt/gitlab/backups`. ```shell sudo cp 1493107454_2017_04_25_9.1.0_gitlab_backup.tar /var/opt/gitlab/backups/ ``` Stop the processes that are connected to the database. Leave the rest of GitLab running: ```shell sudo gitlab-ctl stop unicorn sudo gitlab-ctl stop sidekiq # Verify sudo gitlab-ctl status ``` Next, restore the backup, specifying the timestamp of the backup you wish to restore: ```shell # This command will overwrite the contents of your GitLab database! sudo gitlab-rake gitlab:backup:restore BACKUP=1493107454_2017_04_25_9.1.0 ``` Restart and check GitLab: ```shell sudo gitlab-ctl start sudo gitlab-rake gitlab:check SANITIZE=true ``` If there is a GitLab version mismatch between your backup tar file and the installed version of GitLab, the restore command will abort with an error. Install the [correct GitLab version](https://packages.gitlab.com/gitlab/) and try again. ## Alternative backup strategies If your GitLab server contains a lot of Git repository data you may find the GitLab backup script to be too slow. In this case you can consider using filesystem snapshots as part of your backup strategy. Example: Amazon EBS > A GitLab server using omnibus-gitlab hosted on Amazon AWS. > An EBS drive containing an ext4 filesystem is mounted at `/var/opt/gitlab`. > In this case you could make an application backup by taking an EBS snapshot. > The backup includes all repositories, uploads and Postgres data. Example: LVM snapshots + rsync > A GitLab server using omnibus-gitlab, with an LVM logical volume mounted at `/var/opt/gitlab`. > Replicating the `/var/opt/gitlab` directory using rsync would not be reliable because too many files would change while rsync is running. > Instead of rsync-ing `/var/opt/gitlab`, we create a temporary LVM snapshot, which we mount as a read-only filesystem at `/mnt/gitlab_backup`. > Now we can have a longer running rsync job which will create a consistent replica on the remote server. > The replica includes all repositories, uploads and Postgres data. If you are running GitLab on a virtualized server you can possibly also create VM snapshots of the entire GitLab server. It is not uncommon however for a VM snapshot to require you to power down the server, so this approach is probably of limited practical use. ## Additional notes This documentation is for GitLab Community and Enterprise Edition. We backup GitLab.com and make sure your data is secure, but you can't use these methods to export / backup your data yourself from GitLab.com. Issues are stored in the database. They can't be stored in Git itself. To migrate your repositories from one server to another with an up-to-date version of GitLab, you can use the [import rake task](import.md) to do a mass import of the repository. Note that if you do an import rake task, rather than a backup restore, you will have all your repositories, but not any other data. ## Troubleshooting ### Restoring database backup using omnibus packages outputs warnings If you are using backup restore procedures you might encounter the following warnings: ``` psql:/var/opt/gitlab/backups/db/database.sql:22: ERROR: must be owner of extension plpgsql psql:/var/opt/gitlab/backups/db/database.sql:2931: WARNING: no privileges could be revoked for "public" (two occurrences) psql:/var/opt/gitlab/backups/db/database.sql:2933: WARNING: no privileges were granted for "public" (two occurrences) ``` Be advised that, backup is successfully restored in spite of these warnings. The rake task runs this as the `gitlab` user which does not have the superuser access to the database. When restore is initiated it will also run as `gitlab` user but it will also try to alter the objects it does not have access to. Those objects have no influence on the database backup/restore but they give this annoying warning. For more information see similar questions on postgresql issue tracker[here](http://www.postgresql.org/message-id/201110220712.30886.adrian.klaver@gmail.com) and [here](http://www.postgresql.org/message-id/2039.1177339749@sss.pgh.pa.us) as well as [stack overflow](http://stackoverflow.com/questions/4368789/error-must-be-owner-of-language-plpgsql).
{ "content_hash": "45c3344d476d81d4fa3d85951aba2f94", "timestamp": "", "source": "github", "line_count": 545, "max_line_length": 349, "avg_line_length": 38.04954128440367, "alnum_prop": 0.7429232772339297, "repo_name": "t-zuehlsdorff/gitlabhq", "id": "10f5ab3370d4c8231fda2d2937b163866bac9421", "size": "20772", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/raketasks/backup_restore.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "558077" }, { "name": "Gherkin", "bytes": "115565" }, { "name": "HTML", "bytes": "1054670" }, { "name": "JavaScript", "bytes": "2305094" }, { "name": "Ruby", "bytes": "12136142" }, { "name": "Shell", "bytes": "27385" }, { "name": "Vue", "bytes": "222165" } ], "symlink_target": "" }
@interface MTBAdvancedExampleViewController () @property (nonatomic, weak) IBOutlet UIView *previewView; @property (nonatomic, weak) IBOutlet UIButton *toggleScanningButton; @property (nonatomic, weak) IBOutlet UILabel *instructions; @property (nonatomic, weak) IBOutlet UIView *viewOfInterest; @property (nonatomic, strong) MTBBarcodeScanner *scanner; @property (nonatomic, strong) NSMutableDictionary *overlayViews; @property (nonatomic, assign) BOOL didShowAlert; @end @implementation MTBAdvancedExampleViewController #pragma mark - Lifecycle - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if (!self.didShowAlert && !self.instructions) { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Advanced Example" message:@"To view this example, point the camera at the sample barcodes on the official MTBBarcodeScanner README." preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:action]; [self presentViewController:alertController animated:YES completion:nil]; } } - (void)viewWillDisappear:(BOOL)animated { [self.scanner stopScanning]; [super viewWillDisappear:animated]; } #pragma mark - Scanner - (MTBBarcodeScanner *)scanner { if (!_scanner) { _scanner = [[MTBBarcodeScanner alloc] initWithPreviewView:_previewView]; } return _scanner; } #pragma mark - Overlay Views - (NSMutableDictionary *)overlayViews { if (!_overlayViews) { _overlayViews = [[NSMutableDictionary alloc] init]; } return _overlayViews; } #pragma mark - Scanning - (void)startScanning { __weak MTBAdvancedExampleViewController *weakSelf = self; self.scanner.didStartScanningBlock = ^{ NSLog(@"The scanner started scanning!"); // Optionally set a rectangle of interest to scan codes. Only codes within this rect will be scanned. weakSelf.scanner.scanRect = weakSelf.viewOfInterest.frame; }; self.scanner.didTapToFocusBlock = ^(CGPoint point){ NSLog(@"The user tapped the screen to focus. \ Here we could present a view at %@", NSStringFromCGPoint(point)); [weakSelf.scanner captureStillImage:^(UIImage *image, NSError *error) { NSLog(@"Image captured. Add a breakpoint here to preview it!"); }]; }; NSError *error; [self.scanner startScanningWithResultBlock:^(NSArray *codes) { [self drawOverlaysOnCodes:codes]; } error:&error]; if (error) { NSLog(@"An error occurred: %@", error.localizedDescription); } [self.toggleScanningButton setTitle:@"Stop Scanning" forState:UIControlStateNormal]; self.toggleScanningButton.backgroundColor = [UIColor redColor]; } - (void)drawOverlaysOnCodes:(NSArray *)codes { // Get all of the captured code strings NSMutableArray *codeStrings = [[NSMutableArray alloc] init]; for (AVMetadataMachineReadableCodeObject *code in codes) { if (code.stringValue) { [codeStrings addObject:code.stringValue]; } } // Remove any code overlays no longer on the screen for (NSString *code in self.overlayViews.allKeys) { if ([codeStrings indexOfObject:code] == NSNotFound) { // A code that was on the screen is no longer // in the list of captured codes, remove its overlay [self.overlayViews[code] removeFromSuperview]; [self.overlayViews removeObjectForKey:code]; } } for (AVMetadataMachineReadableCodeObject *code in codes) { UIView *view = nil; NSString *codeString = code.stringValue; if (codeString) { if (self.overlayViews[codeString]) { // The overlay is already on the screen view = self.overlayViews[codeString]; // Move it to the new location view.frame = code.bounds; } else { // First time seeing this code BOOL isValidCode = [self isValidCodeString:codeString]; // Create an overlay UIView *overlayView = [self overlayForCodeString:codeString bounds:code.bounds valid:isValidCode]; self.overlayViews[codeString] = overlayView; // Add the overlay to the preview view [self.previewView addSubview:overlayView]; } } } } - (BOOL)isValidCodeString:(NSString *)codeString { BOOL stringIsValid = ([codeString rangeOfString:@"Valid"].location != NSNotFound); return stringIsValid; } - (UIView *)overlayForCodeString:(NSString *)codeString bounds:(CGRect)bounds valid:(BOOL)valid { UIColor *viewColor = valid ? [UIColor greenColor] : [UIColor redColor]; UIView *view = [[UIView alloc] initWithFrame:bounds]; UILabel *label = [[UILabel alloc] initWithFrame:view.bounds]; // Configure the view view.layer.borderWidth = 5.0; view.backgroundColor = [viewColor colorWithAlphaComponent:0.75]; view.layer.borderColor = viewColor.CGColor; // Configure the label label.font = [UIFont boldSystemFontOfSize:12]; label.text = codeString; label.textColor = [UIColor blackColor]; label.textAlignment = NSTextAlignmentCenter; label.numberOfLines = 0; // Add constraints to label to improve text size? // Add the label to the view [view addSubview:label]; return view; } - (void)stopScanning { [self.scanner stopScanning]; [self.toggleScanningButton setTitle:@"Start Scanning" forState:UIControlStateNormal]; self.toggleScanningButton.backgroundColor = self.view.tintColor; for (NSString *code in self.overlayViews.allKeys) { [self.overlayViews[code] removeFromSuperview]; } } #pragma mark - Actions - (IBAction)toggleScanningTapped:(id)sender { if ([self.scanner isScanning]) { [self stopScanning]; } else { [MTBBarcodeScanner requestCameraPermissionWithSuccess:^(BOOL success) { if (success) { [self startScanning]; } else { [self displayPermissionMissingAlert]; } }]; } } - (IBAction)switchCameraTapped:(id)sender { [self.scanner flipCamera]; } - (void)backTapped { [self.navigationController dismissViewControllerAnimated:YES completion:nil]; } #pragma mark - Notifications - (void)deviceOrientationDidChange:(NSNotification *)notification { self.scanner.scanRect = self.viewOfInterest.frame; } #pragma mark - Helper Methods - (void)displayPermissionMissingAlert { NSString *message = nil; if ([MTBBarcodeScanner scanningIsProhibited]) { message = @"This app does not have permission to use the camera."; } else if (![MTBBarcodeScanner cameraIsPresent]) { message = @"This device does not have a camera."; } else { message = @"An unknown error occurred."; } UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Scanning Unavaialble" message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:action]; [self presentViewController:alertController animated:YES completion:nil]; } @end
{ "content_hash": "8bc1d0cd850a07e1b49f9db6cf3bed56", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 268, "avg_line_length": 34.472573839662445, "alnum_prop": 0.652141982864137, "repo_name": "mikebuss/MTBBarcodeScanner", "id": "c263fe64b87f104866d6df699d5377893bc8b9a9", "size": "8364", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Project/MTBBarcodeScannerExample/Classes/Controllers/MTBAdvancedExampleViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "104" }, { "name": "Objective-C", "bytes": "66585" }, { "name": "Ruby", "bytes": "6438" }, { "name": "Swift", "bytes": "2375" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class CornealSize extends AbstractTag { protected $Id = '0046,0046'; protected $Name = 'CornealSize'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Corneal Size'; }
{ "content_hash": "81e71d1796bc9a539c5283dd6a137a27", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 46, "avg_line_length": 16, "alnum_prop": 0.6553571428571429, "repo_name": "romainneutron/PHPExiftool", "id": "4f75248058006d68fbd08bfc901790154e7d90c3", "size": "782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/DICOM/CornealSize.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22042446" } ], "symlink_target": "" }
A simple nodejs server for IoT devices, like the Raspberry Pi, to intercept non-HTTPS event data from a local network and relay them to initialstate.com over HTTPS. ## Purpose of project To provide a means for low-powered networked devices to communicate event data to Initial State without having the overhead of TLS on the local network while still using TLS from the hub over the Internet to initialstate.com ## Getting started This is a nodejs express application that can be run inside a resin.io container. To setup the application on a Raspberry Pi with resin.io, follow instructions here: http://docs.resin.io/#/pages/installing/gettingStarted.md To associate the hub with an Initial State account, set an environmental variable named `IS_API_ACCESS_KEY` to an account access key. To make working with resin.io easier, we recommend that the repo be forked before doing work.
{ "content_hash": "71a53bda94e21e4816804130599c655f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 224, "avg_line_length": 74, "alnum_prop": 0.8006756756756757, "repo_name": "InitialState/node-hub", "id": "92d15e045b4c42cf327fd00e31fb2a79f24d197c", "size": "900", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2199" }, { "name": "Shell", "bytes": "3535" } ], "symlink_target": "" }
define( [ 'osg/Utils', 'osg/Matrix', 'osg/Transform', 'osg/TransformEnums' ], function ( MACROUTILS, Matrix, Transform, TransformEnums ) { 'use strict'; /** * MatrixTransform is a Transform Node that can be customized with user matrix * @class MatrixTransform */ var MatrixTransform = function () { Transform.call( this ); this.matrix = Matrix.create(); }; /** @lends MatrixTransform.prototype */ MatrixTransform.prototype = MACROUTILS.objectLibraryClass( MACROUTILS.objectInherit( Transform.prototype, { getMatrix: function () { return this.matrix; }, setMatrix: function ( m ) { this.matrix = m; this.dirtyBound(); }, // local to "local world" (not Global World) computeLocalToWorldMatrix: function ( matrix /*, nodeVisitor */ ) { if ( this.referenceFrame === TransformEnums.RELATIVE_RF ) { Matrix.preMult( matrix, this.matrix ); } else { Matrix.copy( this.matrix, matrix ); } return true; }, computeWorldToLocalMatrix: ( function () { var minverse = Matrix.create(); return function ( matrix /*, nodeVisitor */ ) { Matrix.inverse( this.matrix, minverse ); if ( this.referenceFrame === TransformEnums.RELATIVE_RF ) { Matrix.postMult( minverse, matrix ); } else { // absolute Matrix.copy( minverse, matrix ); } return true; }; } )() } ), 'osg', 'MatrixTransform' ); MACROUTILS.setTypeID( MatrixTransform ); return MatrixTransform; } );
{ "content_hash": "fef68f533adc81917d481bb61747449c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 111, "avg_line_length": 30.10169491525424, "alnum_prop": 0.5394144144144144, "repo_name": "jmirabel/osgjs", "id": "c6498994c4dcfb0d0ea91561688c1f4238c1ae35", "size": "1776", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "sources/osg/MatrixTransform.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7857" }, { "name": "GLSL", "bytes": "42058" }, { "name": "HTML", "bytes": "27085" }, { "name": "JavaScript", "bytes": "1698611" }, { "name": "Shell", "bytes": "377" } ], "symlink_target": "" }
define([], function() { return { 'PropertyPaneDescription': 'Configurez le formulaire de la liste ici. Une fois la liste configurée, les champs peuvent être déplacés, insérés et supprimés dans le contenu du webpart.', 'BasicGroupName': 'Paramètres', 'TitleFieldLabel': 'Titre', 'DescriptionFieldLabel': 'Description', 'ListFieldLabel': 'Liste', 'FormTypeFieldLabel': 'Type de formulaire', 'ItemIdFieldLabel': 'ID de l\'item', 'ItemIdFieldDescription' : 'Entrez un nombre pour l\'ID ou le nom du paramètre de chaîne de requête à utiliser pour l\'ID.', 'ShowUnsupportedFieldsLabel': 'Afficher les champs non pris en charge', 'RedirectUrlFieldLabel': 'URL de redirection après l\'enregistrement (facultatif)', 'RedirectUrlFieldDescription': 'Peut contenir [ID] comme placeholder remplacable par l\'ID de l\'élément mis à jour ou créé. Exemple: /list/Test/DispForm.aspx?ID=[ID]', 'LocalWorkbenchUnsupported': 'L\'exécution du WebPart dans votre Workbench local n\'est pas prise en charge. Veuillez l\'exécuter dans votre site SharePoint.', 'MissingListConfiguration': 'Veuillez configurer une liste SharePoint dans les propriétés du WebPart.', 'ConfigureWebpartButtonText': 'Configurer le WebPart', 'ErrorOnLoadingLists': 'Erreur de chargement des listes : ', } });
{ "content_hash": "ff097920699114d56e44cf11c5197f28", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 188, "avg_line_length": 69.89473684210526, "alnum_prop": 0.7341867469879518, "repo_name": "vman/sp-dev-fx-webparts", "id": "f13170a18fff714a853f7b4676ef2e32682a5a9e", "size": "1350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/react-list-form/src/webparts/listForm/loc/fr-fr.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15907" }, { "name": "JavaScript", "bytes": "11884" }, { "name": "TypeScript", "bytes": "57801" } ], "symlink_target": "" }
package raftstore import ( "github.com/deepfabric/elasticell/pkg/pb/raftcmdpb" "github.com/deepfabric/elasticell/pkg/pool" "github.com/fagongzi/log" "github.com/fagongzi/util/uuid" "github.com/fagongzi/goetty" ) const ( read = iota write admin ) type reqCtx struct { admin *raftcmdpb.AdminRequest req *raftcmdpb.Request cb func(*raftcmdpb.RaftCMDResponse) } func (r *reqCtx) reset() { r.admin = nil r.cb = nil r.req = nil } type proposeBatch struct { pr *PeerReplicate buf *goetty.ByteBuf lastType int cmds []*cmd } func newBatch(pr *PeerReplicate) *proposeBatch { return &proposeBatch{ pr: pr, buf: goetty.NewByteBuf(512), } } func (b *proposeBatch) getType(c *reqCtx) int { if c.admin != nil { return admin } if b.pr.isWrite(c.req) { return write } return read } func (b *proposeBatch) size() int { return len(b.cmds) } func (b *proposeBatch) isEmpty() bool { return 0 == b.size() } func (b *proposeBatch) isFull(lastSize uint64) bool { return globalCfg.BatchSizeProposal == lastSize } func (b *proposeBatch) pop() *cmd { if b.isEmpty() { return nil } value := b.cmds[0] b.cmds[0] = nil b.cmds = b.cmds[1:] queueGauge.WithLabelValues(labelQueueBatchSize).Set(float64(len(value.req.Requests))) queueGauge.WithLabelValues(labelQueueBatch).Set(float64(b.size())) return value } func (b *proposeBatch) push(c *reqCtx) { adminReq := c.admin req := c.req cb := c.cb tp := b.getType(c) releaseReqCtx(c) isAdmin := tp == admin // use data key to store if !isAdmin { key := req.Cmd[1] req.Cmd[1] = getDataKey0(key, b.buf) b.buf.Clear() } last := b.lastCmd() if last == nil || isAdmin || // admin request must in a single batch b.lastType != tp || b.isFull(uint64(len(last.req.Requests))) { cell := b.pr.getCell() raftCMD := pool.AcquireRaftCMDRequest() raftCMD.Header = pool.AcquireRaftRequestHeader() raftCMD.Header.CellId = cell.ID raftCMD.Header.Peer = b.pr.getPeer() raftCMD.Header.ReadQuorum = true raftCMD.Header.UUID = uuid.NewV4().Bytes() raftCMD.Header.CellEpoch = cell.Epoch if isAdmin { raftCMD.AdminRequest = adminReq } else { raftCMD.Requests = append(raftCMD.Requests, req) if log.DebugEnabled() { log.Debugf("req: add to new batch. uuid=<%d>", req.UUID) } } b.cmds = append(b.cmds, newCMD(raftCMD, cb)) queueGauge.WithLabelValues(labelQueueBatch).Set(float64(b.size())) } else { if isAdmin { log.Fatal("bug: admin request must in a single batch") } last.req.Requests = append(last.req.Requests, req) if log.DebugEnabled() { log.Debugf("req: add to exists batch. uuid=<%d>, batch size=<%d>", req.UUID, len(last.req.Requests)) } } b.lastType = tp } func (b *proposeBatch) lastCmd() *cmd { if b.isEmpty() { return nil } return b.cmds[b.size()-1] }
{ "content_hash": "09275dcbe370db0e32ad060b7aeb8f63", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 86, "avg_line_length": 19.312925170068027, "alnum_prop": 0.6696019725255372, "repo_name": "deepfabric/elasticell", "id": "40dee9e6a5a30d937bd44fcd2c67c7f01efd2ed3", "size": "2839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/raftstore/propose_batch.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "10271" }, { "name": "Dockerfile", "bytes": "212" }, { "name": "Go", "bytes": "857489" }, { "name": "Makefile", "bytes": "1697" }, { "name": "Shell", "bytes": "2917" } ], "symlink_target": "" }
using System.Collections.Generic; using Rxns.Hosting; namespace Rxns.Redis { public class RedisModule : IAppModule { public IRxnLifecycle Load(IRxnLifecycle lifecycle) { return lifecycle.CreatesOncePerApp<RedisCacheFactory>() .CreateGenericOncePerAppAs(typeof(RedisDictionary<,>), typeof(IDictionary<,>)); } } }
{ "content_hash": "75d77c3b14082527f2957a302110ccb6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 95, "avg_line_length": 27, "alnum_prop": 0.6666666666666666, "repo_name": "captainjono/rxns", "id": "88a086a4b9ad34cc503b0f39b10f0f544586754a", "size": "380", "binary": false, "copies": "1", "ref": "refs/heads/vnext", "path": "Rxns.Redis/RedisModule.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "322" }, { "name": "C#", "bytes": "2033635" }, { "name": "CSS", "bytes": "151935" }, { "name": "HTML", "bytes": "17988" }, { "name": "JavaScript", "bytes": "548381" }, { "name": "Less", "bytes": "5143" }, { "name": "Smalltalk", "bytes": "15112" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will try guess the protocol, domain | and path to your installation. However, you should always configure this | explicitly and never rely on auto-guessing, especially in production | environments. | */ $config['base_url'] = ''; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Set this to TRUE if you want to use different cache files depending on the | URL query string. Please be aware this might result in numerous cache files. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = '7afd8f11b16c5acf927c321adba7aac7'; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependant. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurences with the PHP_EOL value. | | This is particularly useful for portability between UNIX-based OSes, | (usually \n) and Windows (\r\n). | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'dbless_csrf'; $config['csrf_cookie_name'] = 'dbless_cookings'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
{ "content_hash": "c6dedec9f741cc7d790f44ed3e172470", "timestamp": "", "source": "github", "line_count": 500, "max_line_length": 83, "avg_line_length": 35.008, "alnum_prop": 0.5413619744058501, "repo_name": "avenirer/DBless-CI", "id": "f3bc7e5f31800a91aef828865bd895b89220e82d", "size": "17504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/config/config.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "467" }, { "name": "CSS", "bytes": "9421" }, { "name": "HTML", "bytes": "2178" }, { "name": "JavaScript", "bytes": "128146" }, { "name": "PHP", "bytes": "158882" } ], "symlink_target": "" }
package com.intellij.codeInsight.editorActions.enter; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.util.IncorrectOperationException; import com.intellij.codeInsight.CodeInsightSettings; public class EnterBetweenBracesHandler implements EnterHandlerDelegate { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.enter.EnterBetweenBracesHandler"); public Result preprocessEnter(final PsiFile file, final Editor editor, final Ref<Integer> caretOffsetRef, final Ref<Integer> caretAdvance, final DataContext dataContext, final EditorActionHandler originalHandler) { Document document = editor.getDocument(); CharSequence text = document.getCharsSequence(); int caretOffset = caretOffsetRef.get().intValue(); if (CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) { // special case: enter inside "()" or "{}" if (caretOffset > 0 && caretOffset < text.length() && ((text.charAt(caretOffset - 1) == '(' && text.charAt(caretOffset) == ')') || (text.charAt(caretOffset - 1) == '{' && text.charAt(caretOffset) == '}'))) { originalHandler.execute(editor, dataContext); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); try { CodeStyleManager.getInstance(file.getProject()).adjustLineIndent(file, editor.getCaretModel().getOffset()); } catch (IncorrectOperationException e) { LOG.error(e); } return Result.Default; } } return Result.Continue; } }
{ "content_hash": "7baf3b3cc7a42538735cd39897a76fba", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 140, "avg_line_length": 48.333333333333336, "alnum_prop": 0.7123152709359606, "repo_name": "jexp/idea2", "id": "d81a4bb39a803d962a8f25ed9983a7efc60a9cc3", "size": "2630", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/lang-impl/src/com/intellij/codeInsight/editorActions/enter/EnterBetweenBracesHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6350" }, { "name": "C#", "bytes": "103" }, { "name": "C++", "bytes": "30760" }, { "name": "Erlang", "bytes": "10" }, { "name": "Java", "bytes": "72888555" }, { "name": "JavaScript", "bytes": "910" }, { "name": "PHP", "bytes": "133" }, { "name": "Perl", "bytes": "6523" }, { "name": "Shell", "bytes": "4068" } ], "symlink_target": "" }
package org.spotter.eclipse.ui.util; import junit.framework.Assert; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridLayout; import org.junit.Test; public class WidgetUtilsTest { @Test public void testCreateGridLayout() { final int numColumns = 7; GridLayout gridLayout = WidgetUtils.createGridLayout(numColumns); Assert.assertEquals(false, gridLayout.makeColumnsEqualWidth); Assert.assertEquals(numColumns, gridLayout.numColumns); assertDefaultGridLayout(gridLayout); gridLayout = WidgetUtils.createGridLayout(numColumns, true); Assert.assertEquals(true, gridLayout.makeColumnsEqualWidth); Assert.assertEquals(numColumns, gridLayout.numColumns); assertDefaultGridLayout(gridLayout); } @Test public void testCreateFillLayout() { FillLayout fillLayout = WidgetUtils.createFillLayout(SWT.HORIZONTAL); Assert.assertEquals(SWT.HORIZONTAL, fillLayout.type); assertDefaultFillLayout(fillLayout); fillLayout = WidgetUtils.createFillLayout(SWT.VERTICAL); Assert.assertEquals(SWT.VERTICAL, fillLayout.type); assertDefaultFillLayout(fillLayout); } private void assertDefaultGridLayout(GridLayout gridLayout) { Assert.assertEquals(WidgetUtils.DEFAULT_MARGIN_WIDTH, gridLayout.marginWidth); Assert.assertEquals(WidgetUtils.DEFAULT_MARGIN_HEIGHT, gridLayout.marginHeight); Assert.assertEquals(WidgetUtils.DEFAULT_VERTICAL_SPACING, gridLayout.verticalSpacing); Assert.assertEquals(WidgetUtils.DEFAULT_HORIZONTAL_SPACING, gridLayout.horizontalSpacing); Assert.assertEquals(0, gridLayout.marginBottom); Assert.assertEquals(0, gridLayout.marginTop); Assert.assertEquals(0, gridLayout.marginLeft); Assert.assertEquals(0, gridLayout.marginRight); } private void assertDefaultFillLayout(FillLayout fillLayout) { Assert.assertEquals(WidgetUtils.DEFAULT_MARGIN_WIDTH, fillLayout.marginWidth); Assert.assertEquals(WidgetUtils.DEFAULT_MARGIN_HEIGHT, fillLayout.marginHeight); Assert.assertEquals(WidgetUtils.DEFAULT_VERTICAL_SPACING, fillLayout.spacing); } }
{ "content_hash": "1089a32f5ebd39fd41942519183cd730", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 92, "avg_line_length": 37.56363636363636, "alnum_prop": 0.8151016456921588, "repo_name": "CloudScale-Project/DynamicSpotter", "id": "e0a8536aef97a7dae3aacda1f4d0199ab31ccc9e", "size": "2656", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "org.spotter.eclipse.ui.test/test/org/spotter/eclipse/ui/util/WidgetUtilsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1052395" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.jcabi</groupId> <artifactId>DynamoDBLocal</artifactId> <version>2014-01-08</version> <packaging>zip</packaging> <name>DynamoDB Local</name> <description>AWS DynamoDB Local Distribution</description> <url>http://www.jcabi.com</url> <inceptionYear>2013</inceptionYear> <licenses> <license> <name>BSD</name> <url>http://www.jcabi.com/LICENSE.txt</url> <distribution>repo</distribution> <comments><![CDATA[ This is free open source project, feel free to redistribute it ]]></comments> </license> </licenses> <developers> <developer> <id>1</id> <name>Yegor Bugayenko</name> <email>yegor@tpc2.com</email> <organization>tpc2.com</organization> <organizationUrl>http://www.tpc2.com</organizationUrl> <roles> <role>Architect</role> <role>Developer</role> </roles> <timezone>+1</timezone> </developer> </developers> <scm> <connection>scm:git:github.com:jcabi/jcabi-dynamodb-maven-plugin.git</connection> <developerConnection>scm:git:github.com:jcabi/jcabi-dynamodb-maven-plugin.git</developerConnection> <url>https://github.com/jcabi/jcabi-dynamodb-maven-plugin</url> </scm> </project>
{ "content_hash": "7e79fc2fdb2eebab86e7f85f115b2506", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 149, "avg_line_length": 40.38095238095238, "alnum_prop": 0.6073113207547169, "repo_name": "jamiepg1/jcabi-dynamodb-maven-plugin", "id": "a2a00eb23d77ac0a192441a435f18530408d7e63", "size": "1697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deploy/pom.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_45) on Sun Mar 27 18:44:33 IDT 2016 --> <title>DnxDocumentHelper.GrantedRightsStatement</title> <meta name="date" content="2016-03-27"> <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="DnxDocumentHelper.GrantedRightsStatement"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GeneralRepCharacteristics.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.Inhibitors.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html" target="_top">Frames</a></li> <li><a href="DnxDocumentHelper.GrantedRightsStatement.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.exlibris.digitool.common.dnx</div> <h2 title="Class DnxDocumentHelper.GrantedRightsStatement" class="title">Class DnxDocumentHelper.GrantedRightsStatement</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.exlibris.digitool.common.dnx.DnxDocumentHelper.GrantedRightsStatement</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.html" title="class in com.exlibris.digitool.common.dnx">DnxDocumentHelper</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">DnxDocumentHelper.GrantedRightsStatement</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#GRANTEDRIGHTSSTATEMENTIDENTIFIER">GRANTEDRIGHTSSTATEMENTIDENTIFIER</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#GRANTEDRIGHTSSTATEMENTVALUE">GRANTEDRIGHTSSTATEMENTVALUE</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#sectionId">sectionId</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#GrantedRightsStatement--">GrantedRightsStatement</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#GrantedRightsStatement-java.lang.String-java.lang.String-">GrantedRightsStatement</a></span>(java.lang.String&nbsp;grantedRightsStatementIdentifier, java.lang.String&nbsp;grantedRightsStatementValue)</code> <div class="block">Creates the GrantedRightsStatement section.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#getGrantedRightsStatementIdentifier--">getGrantedRightsStatementIdentifier</a></span>()</code> <div class="block">Gets the GrantedRightsStatement grantedRightsStatementIdentifier.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#getGrantedRightsStatementValue--">getGrantedRightsStatementValue</a></span>()</code> <div class="block">Gets the GrantedRightsStatement grantedRightsStatementValue.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code><a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#getRecord--">getRecord</a></span>()</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#setGrantedRightsStatementIdentifier-java.lang.String-">setGrantedRightsStatementIdentifier</a></span>(java.lang.String&nbsp;s)</code> <div class="block">Sets the GrantedRightsStatement grantedRightsStatementIdentifier.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#setGrantedRightsStatementValue-java.lang.String-">setGrantedRightsStatementValue</a></span>(java.lang.String&nbsp;s)</code> <div class="block">Sets the GrantedRightsStatement grantedRightsStatementValue.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html#setRecord-com.exlibris.digitool.common.dnx.DnxSectionRecord-">setRecord</a></span>(<a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a>&nbsp;record)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="sectionId"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sectionId</h4> <pre>public static final&nbsp;java.lang.String sectionId</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.GrantedRightsStatement.sectionId">Constant Field Values</a></dd> </dl> </li> </ul> <a name="GRANTEDRIGHTSSTATEMENTIDENTIFIER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>GRANTEDRIGHTSSTATEMENTIDENTIFIER</h4> <pre>public static final&nbsp;java.lang.String GRANTEDRIGHTSSTATEMENTIDENTIFIER</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.GrantedRightsStatement.GRANTEDRIGHTSSTATEMENTIDENTIFIER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="GRANTEDRIGHTSSTATEMENTVALUE"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>GRANTEDRIGHTSSTATEMENTVALUE</h4> <pre>public static final&nbsp;java.lang.String GRANTEDRIGHTSSTATEMENTVALUE</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.GrantedRightsStatement.GRANTEDRIGHTSSTATEMENTVALUE">Constant Field Values</a></dd> </dl> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="GrantedRightsStatement--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>GrantedRightsStatement</h4> <pre>public&nbsp;GrantedRightsStatement()</pre> </li> </ul> <a name="GrantedRightsStatement-java.lang.String-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>GrantedRightsStatement</h4> <pre>public&nbsp;GrantedRightsStatement(java.lang.String&nbsp;grantedRightsStatementIdentifier, java.lang.String&nbsp;grantedRightsStatementValue)</pre> <div class="block">Creates the GrantedRightsStatement section.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>grantedRightsStatementIdentifier</code> - ID of the statement<br/></dd> <dd><code>grantedRightsStatementValue</code> - Actual content of the statement<br/></dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getRecord--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRecord</h4> <pre>public&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a>&nbsp;getRecord()</pre> </li> </ul> <a name="setRecord-com.exlibris.digitool.common.dnx.DnxSectionRecord-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setRecord</h4> <pre>public&nbsp;void&nbsp;setRecord(<a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a>&nbsp;record)</pre> </li> </ul> <a name="getGrantedRightsStatementIdentifier--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getGrantedRightsStatementIdentifier</h4> <pre>public&nbsp;java.lang.String&nbsp;getGrantedRightsStatementIdentifier()</pre> <div class="block">Gets the GrantedRightsStatement grantedRightsStatementIdentifier.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>grantedRightsStatementIdentifier ID of the statement<br/></dd> </dl> </li> </ul> <a name="setGrantedRightsStatementIdentifier-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setGrantedRightsStatementIdentifier</h4> <pre>public&nbsp;void&nbsp;setGrantedRightsStatementIdentifier(java.lang.String&nbsp;s)</pre> <div class="block">Sets the GrantedRightsStatement grantedRightsStatementIdentifier.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>s</code> - ID of the statement<br/></dd> </dl> </li> </ul> <a name="getGrantedRightsStatementValue--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getGrantedRightsStatementValue</h4> <pre>public&nbsp;java.lang.String&nbsp;getGrantedRightsStatementValue()</pre> <div class="block">Gets the GrantedRightsStatement grantedRightsStatementValue.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>grantedRightsStatementValue Actual content of the statement<br/></dd> </dl> </li> </ul> <a name="setGrantedRightsStatementValue-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setGrantedRightsStatementValue</h4> <pre>public&nbsp;void&nbsp;setGrantedRightsStatementValue(java.lang.String&nbsp;s)</pre> <div class="block">Sets the GrantedRightsStatement grantedRightsStatementValue.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>s</code> - Actual content of the statement<br/></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.GeneralRepCharacteristics.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.Inhibitors.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html" target="_top">Frames</a></li> <li><a href="DnxDocumentHelper.GrantedRightsStatement.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "de379e89aa0e144f8d11dfac963e8768", "timestamp": "", "source": "github", "line_count": 462, "max_line_length": 422, "avg_line_length": 41.16450216450217, "alnum_prop": 0.6830371227258387, "repo_name": "ExLibrisGroup/Rosetta.dps-sdk-projects", "id": "a54be38757ed60ce8cd931c1c4d2489dfed9dc7a", "size": "19018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "5.0.1/javadoc/com/exlibris/digitool/common/dnx/DnxDocumentHelper.GrantedRightsStatement.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "4697410" }, { "name": "Shell", "bytes": "297" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Solocast.Core.Contracts { public class Podcast : IEquatable<Podcast> { public int PodcastId { get; set; } public string Title { get; set; } public string Description { get; set; } public string Author { get; set; } public string FeedUrl { get; set; } public string ImageUrl { get; set; } public DateTime DateAdded { get; set; } public List<Episode> Episodes { get; set; } public Podcast(string name, string description, string author, string feedUrl, string imageUrl, DateTime dateAdded) { this.Title = name; this.Description = description; this.Author = author; this.FeedUrl = feedUrl; this.ImageUrl = imageUrl; this.DateAdded = dateAdded; } public Podcast() { } public void SetEpisodes(IEnumerable<Episode> episode) { this.Episodes = episode.OrderByDescending(e => e.Published).ToList(); } public bool Equals(Podcast other) { //not the best logic, but it will do if (this.FeedUrl == other.FeedUrl) { if (this.Episodes.Count == other.Episodes.Count) { return true; } } return false; } } }
{ "content_hash": "1ff530a59439f0ed6ba2eeaf13a5596a", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 81, "avg_line_length": 26.46031746031746, "alnum_prop": 0.5500899820035993, "repo_name": "robertiagar/Podcasts-WindowsUniversal", "id": "323cb665f2dcc388f4576564b19b7de928740ae8", "size": "1669", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/Solocast/Solocast.Core/Contracts/Podcast.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "126579" } ], "symlink_target": "" }
<?php namespace app\modules\catalogs\controllers; use Yii; use app\modules\catalogs\models\Facultad; use app\modules\catalogs\models\Universidad; use app\modules\catalogs\models\FacultadSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use \yii\web\Response; use yii\helpers\Html; use yii\helpers\Json; use yii\helpers\ArrayHelper; /** * FacultadController implements the CRUD actions for Facultad model. */ class FacultadController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], 'bulk-delete' => ['post'], ], ], ]; } /** * Lists all Facultad models. * @return mixed */ public function actionIndex() { $searchModel = new FacultadSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } public function actionGetFacultades() { $out = []; if (isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if ($parents != null) { $universidad_id = $parents[0]; $out = Facultad::find()->select(['IdFacultad', 'Nombre'])->where(['idUniversidad' => $universidad_id])->all(); foreach($out as $o) { $opt[] = ['id'=>$o->IdFacultad, 'name'=>$o->Nombre]; } if(count($out) > 0) { echo Json::encode(['output'=>$opt, 'selected'=>'']); } else { echo Json::encode(['output'=>'', 'selected'=>'']); } return; } } echo Json::encode(['output'=>'', 'selected'=>'']); } /** * Displays a single Facultad model. * @param integer $id * @return mixed */ public function actionView($id) { $request = Yii::$app->request; if($request->isAjax){ Yii::$app->response->format = Response::FORMAT_JSON; return [ 'title'=> "Facultad #".$id, 'content'=>$this->renderAjax('view', [ 'model' => $this->findModel($id), ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::a('Editar',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote']) ]; }else{ return $this->render('view', [ 'model' => $this->findModel($id), ]); } } /** * Creates a new Facultad model. * For ajax request will return json object * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $request = Yii::$app->request; $model = new Facultad(); $universidades = ArrayHelper::map(Universidad::find()->all(), 'IdUniversidad', 'Nombre'); if($request->isAjax){ /* * Process for ajax request */ Yii::$app->response->format = Response::FORMAT_JSON; if($request->isGet){ return [ 'title'=> "Crear una nuevaFacultad", 'content'=>$this->renderAjax('create', [ 'model' => $model, 'universidades' => $universidades, ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Guardar',['class'=>'btn btn-primary','type'=>"submit"]) ]; }else if($model->load($request->post()) && $model->save()){ return [ 'forceReload'=>'#crud-datatable-pjax', 'title'=> "Crear una nueva Facultad", 'content'=>'<span class="text-success">Facultad creada exitosamente</span>', 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::a('Crear más',['create'],['class'=>'btn btn-primary','role'=>'modal-remote']) ]; }else{ return [ 'title'=> "Crear una nueva Facultad", 'content'=>$this->renderAjax('create', [ 'model' => $model, 'universidades' => $universidades, ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Guardar',['class'=>'btn btn-primary','type'=>"submit"]) ]; } }else{ /* * Process for non-ajax request */ if ($model->load($request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->IdFacultad]); } else { return $this->render('create', [ 'model' => $model, 'universidades' => $universidades, ]); } } } /** * Updates an existing Facultad model. * For ajax request will return json object * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $request = Yii::$app->request; $model = $this->findModel($id); $universidades = ArrayHelper::map(Universidad::find()->all(), 'IdUniversidad', 'Nombre'); if($request->isAjax){ /* * Process for ajax request */ Yii::$app->response->format = Response::FORMAT_JSON; if($request->isGet){ return [ 'title'=> "Editar la Facultad #".$id, 'content'=>$this->renderAjax('update', [ 'model' => $model, 'universidades' => $universidades, ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Guardar',['class'=>'btn btn-primary','type'=>"submit"]) ]; }else if($model->load($request->post()) && $model->save()){ return [ 'forceReload'=>'#crud-datatable-pjax', 'title'=> "Facultad #".$id, 'content'=>$this->renderAjax('view', [ 'model' => $model, ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::a('Editar',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote']) ]; }else{ return [ 'title'=> "Editar la Facultad #".$id, 'content'=>$this->renderAjax('update', [ 'model' => $model, 'universidades' => $universidades, ]), 'footer'=> Html::button('Cerrar',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Guardar',['class'=>'btn btn-primary','type'=>"submit"]) ]; } }else{ /* * Process for non-ajax request */ if ($model->load($request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->IdFacultad]); } else { return $this->render('update', [ 'model' => $model, 'universidades' => $universidades, ]); } } } /** * Delete an existing Facultad model. * For ajax request will return json object * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $request = Yii::$app->request; $this->findModel($id)->delete(); if($request->isAjax){ /* * Process for ajax request */ Yii::$app->response->format = Response::FORMAT_JSON; return ['forceClose'=>true,'forceReload'=>'#crud-datatable-pjax']; }else{ /* * Process for non-ajax request */ return $this->redirect(['index']); } } /** * Delete multiple existing Facultad model. * For ajax request will return json object * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionBulkDelete() { $request = Yii::$app->request; $pks = explode(',', $request->post( 'pks' )); // Array or selected records primary keys foreach ( $pks as $pk ) { $model = $this->findModel($pk); $model->delete(); } if($request->isAjax){ /* * Process for ajax request */ Yii::$app->response->format = Response::FORMAT_JSON; return ['forceClose'=>true,'forceReload'=>'#crud-datatable-pjax']; }else{ /* * Process for non-ajax request */ return $this->redirect(['index']); } } /** * Finds the Facultad model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Facultad the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Facultad::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
{ "content_hash": "257f01f81ca357a8040b76c25295b0b1", "timestamp": "", "source": "github", "line_count": 308, "max_line_length": 126, "avg_line_length": 35.62987012987013, "alnum_prop": 0.4604519774011299, "repo_name": "jacastaneda/hosouees", "id": "c253b200daa1157d275ed4b5bca2a59db5ff4a7d", "size": "10975", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/catalogs/controllers/FacultadController.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "243" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "JavaScript", "bytes": "529" }, { "name": "PHP", "bytes": "558504" } ], "symlink_target": "" }
layout: page title: Arnold Productions Dinner date: 2016-05-24 author: Megan Dean tags: weekly links, java status: published summary: Pellentesque tempor vehicula volutpat. Nunc id. banner: images/banner/wedding.jpg booking: startDate: 04/12/2019 endDate: 04/17/2019 ctyhocn: FSDNOHX groupCode: APD published: true --- Fusce sed dignissim orci. Nam id ex ut massa sodales efficitur. Maecenas eu porttitor nunc. Quisque at semper ipsum, vitae pulvinar velit. In consequat vulputate leo, sit amet mattis neque rutrum ac. Aenean tempor mauris urna, eget suscipit odio auctor non. Mauris pellentesque nibh augue, eget lacinia lacus rhoncus vel. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris nec justo turpis. Vestibulum sit amet volutpat massa, sed auctor justo. Duis mauris sapien, imperdiet at viverra eget, imperdiet ut magna. Integer egestas, nisi eget rutrum sagittis, justo justo dapibus elit, non pharetra turpis arcu vitae risus. Donec metus nisl, iaculis quis ultricies ac, tempus varius nisi. Quisque arcu sapien, eleifend id mauris et, cursus egestas purus. Pellentesque rutrum sollicitudin sem et fringilla. Quisque vel arcu in diam rhoncus posuere nec sit amet turpis. In hac habitasse platea dictumst. Duis tellus tellus, laoreet vel venenatis dignissim, porttitor quis sem. Ut non convallis orci. Ut volutpat, mauris ac hendrerit rhoncus, enim risus tempor ante, nec maximus turpis orci vel enim. Suspendisse sed leo vel libero consectetur molestie eget at urna. Integer interdum, dui quis vehicula tristique, ipsum enim pulvinar mi, ut hendrerit enim augue sed elit. Curabitur consectetur diam consequat nisl finibus ullamcorper. 1 Sed sollicitudin elit eu dignissim pharetra 1 Etiam bibendum nisl feugiat scelerisque semper. Praesent gravida orci quis sagittis finibus. Nunc feugiat, sapien at dapibus egestas, nisi nisi lacinia dui, et sagittis lectus tellus ut est. Sed in eleifend leo, vestibulum dictum mi. Phasellus gravida vestibulum bibendum. Praesent vitae augue tincidunt, congue est quis, hendrerit dolor. Quisque et turpis nunc. Suspendisse in suscipit massa, eu rutrum erat.
{ "content_hash": "2f4fc7b2f1f7fb3a94f7e4e99a0a508d", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 734, "avg_line_length": 98.4090909090909, "alnum_prop": 0.8106235565819861, "repo_name": "KlishGroup/prose-pogs", "id": "3ca43dcdcd9b778919ee7338395636d3fe2e5067", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/F/FSDNOHX/APD/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
var mongoose = require('mongoose'); module.exports.init = function () { var messagesSchema = new mongoose.Schema({ text: { type: String, required: '{PATH} is required', maxlength: 1000, minlenght: 1 }, from : { type: String }, to: { type: String } }); Message = mongoose.model('Message', messagesSchema); console.log('Message model created...'); };
{ "content_hash": "fcb534d9d608f8cf20784fd4facad3fd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 56, "avg_line_length": 23.95, "alnum_prop": 0.5010438413361169, "repo_name": "clangelov/TelerikAcademyHomework", "id": "eb7e362977e93892312c58023dfcd89e7e4b0425", "size": "479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "15_EndToEndJSApps/MondoDB-Homework/models/Message.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "33594" }, { "name": "C#", "bytes": "1623921" }, { "name": "CSS", "bytes": "43045" }, { "name": "HTML", "bytes": "218721" }, { "name": "JavaScript", "bytes": "494441" }, { "name": "XSLT", "bytes": "4030" } ], "symlink_target": "" }
import common import os import sys def main(): ast = common.Ami() ast.username = sys.argv[1] ast.password = sys.argv[2] if ast.conn() == False: print("Could not connect.") return 1 # get dialing print("Getting dialing all") ret = ast.sendCmd("OutDialingShow") if ret[0]["Response"] != "Success": print("Couldn not pass the test_dialing. ret[%s]" % ret) raise "test_dialing" # get summary print("Getting dialing summary") ret = ast.sendCmd("OutDialingSummary") if ret[0]["Response"] != "Success": print("Couldn not pass the test_dialing. ret[%s]" % ret) raise "test_dialing" return 0 if __name__ == '__main__': main()
{ "content_hash": "01b423cb67ebe741725a85d270e8b5c6", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 64, "avg_line_length": 23.677419354838708, "alnum_prop": 0.5790190735694822, "repo_name": "pchero/asterisk-outbound", "id": "cf915dcb41cce2a611e1a8b0ced5eda58ac26170", "size": "802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_dialing.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "343104" }, { "name": "C++", "bytes": "322" }, { "name": "HTML", "bytes": "478" }, { "name": "JavaScript", "bytes": "5943" }, { "name": "Makefile", "bytes": "5574" }, { "name": "Python", "bytes": "127421" } ], "symlink_target": "" }
import Vue from 'vue'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill function isExist (obj) { return typeof obj !== 'undefined' && obj !== null } function isFunction (obj) { return typeof obj === 'function' } function isString (obj) { return typeof obj === 'string' } function hasOwnProperty (o, k) { return Object.prototype.hasOwnProperty.call(o, k) } var EVENTS = { MOUSE_ENTER: 'mouseenter', MOUSE_LEAVE: 'mouseleave', MOUSE_DOWN: 'mousedown', MOUSE_UP: 'mouseup', FOCUS: 'focus', BLUR: 'blur', CLICK: 'click', INPUT: 'input', KEY_DOWN: 'keydown', KEY_UP: 'keyup', KEY_PRESS: 'keypress', RESIZE: 'resize', SCROLL: 'scroll', TOUCH_START: 'touchstart', TOUCH_END: 'touchend' }; var TRIGGERS = { CLICK: 'click', HOVER: 'hover', FOCUS: 'focus', HOVER_FOCUS: 'hover-focus', OUTSIDE_CLICK: 'outside-click', MANUAL: 'manual' }; var PLACEMENTS = { TOP: 'top', RIGHT: 'right', BOTTOM: 'bottom', LEFT: 'left' }; function getViewportSize () { /* istanbul ignore next */ var width = Math.max(document.documentElement.clientWidth, window.innerWidth) || 0; /* istanbul ignore next */ var height = Math.max(document.documentElement.clientHeight, window.innerHeight) || 0; return { width: width, height: height } } function on (element, event, handler) { /* istanbul ignore next */ element.addEventListener(event, handler); } function off (element, event, handler) { /* istanbul ignore next */ element.removeEventListener(event, handler); } function isElement (el) { return el && el.nodeType === Node.ELEMENT_NODE } function removeFromDom (el) { isElement(el) && isElement(el.parentNode) && el.parentNode.removeChild(el); } function ensureElementMatchesFunction () { /* istanbul ignore next */ if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function (s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s); var i = matches.length; // eslint-disable-next-line no-empty while (--i >= 0 && matches.item(i) !== this) {} return i > -1 }; } } function addClass (el, className) { if (!isElement(el)) { return } if (el.className) { var classes = el.className.split(' '); if (classes.indexOf(className) < 0) { classes.push(className); el.className = classes.join(' '); } } else { el.className = className; } } function removeClass (el, className) { if (!isElement(el)) { return } if (el.className) { var classes = el.className.split(' '); var newClasses = []; for (var i = 0, l = classes.length; i < l; i++) { if (classes[i] !== className) { newClasses.push(classes[i]); } } el.className = newClasses.join(' '); } } function hasClass (el, className) { if (!isElement(el)) { return false } var classes = el.className.split(' '); for (var i = 0, l = classes.length; i < l; i++) { if (classes[i] === className) { return true } } return false } function isAvailableAtPosition (trigger, popup, placement) { var triggerRect = trigger.getBoundingClientRect(); var popupRect = popup.getBoundingClientRect(); var viewPortSize = getViewportSize(); var top = true; var right = true; var bottom = true; var left = true; switch (placement) { case PLACEMENTS.TOP: top = triggerRect.top >= popupRect.height; left = triggerRect.left + triggerRect.width / 2 >= popupRect.width / 2; right = triggerRect.right - triggerRect.width / 2 + popupRect.width / 2 <= viewPortSize.width; break case PLACEMENTS.BOTTOM: bottom = triggerRect.bottom + popupRect.height <= viewPortSize.height; left = triggerRect.left + triggerRect.width / 2 >= popupRect.width / 2; right = triggerRect.right - triggerRect.width / 2 + popupRect.width / 2 <= viewPortSize.width; break case PLACEMENTS.RIGHT: right = triggerRect.right + popupRect.width <= viewPortSize.width; top = triggerRect.top + triggerRect.height / 2 >= popupRect.height / 2; bottom = triggerRect.bottom - triggerRect.height / 2 + popupRect.height / 2 <= viewPortSize.height; break case PLACEMENTS.LEFT: left = triggerRect.left >= popupRect.width; top = triggerRect.top + triggerRect.height / 2 >= popupRect.height / 2; bottom = triggerRect.bottom - triggerRect.height / 2 + popupRect.height / 2 <= viewPortSize.height; break } return top && right && bottom && left } function setTooltipPosition (tooltip, trigger, placement, auto, appendTo, positionBy, viewport) { if (!isElement(tooltip) || !isElement(trigger)) { return } var isPopover = tooltip && tooltip.className && tooltip.className.indexOf('popover') >= 0; var containerScrollTop; var containerScrollLeft; if (!isExist(appendTo) || appendTo === 'body' || positionBy === 'body') { var doc = document.documentElement; containerScrollLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); containerScrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); } else { var container = getElementBySelectorOrRef(positionBy || appendTo); containerScrollLeft = container.scrollLeft; containerScrollTop = container.scrollTop; } // auto adjust placement if (auto) { // Try: right -> bottom -> left -> top // Cause the default placement is top var placements = [PLACEMENTS.RIGHT, PLACEMENTS.BOTTOM, PLACEMENTS.LEFT, PLACEMENTS.TOP]; // The class switch helper function var changePlacementClass = function (placement) { // console.log(placement) placements.forEach(function (placement) { removeClass(tooltip, placement); }); addClass(tooltip, placement); }; // No need to adjust if the default placement fits if (!isAvailableAtPosition(trigger, tooltip, placement)) { for (var i = 0, l = placements.length; i < l; i++) { // Re-assign placement class changePlacementClass(placements[i]); // Break if new placement fits if (isAvailableAtPosition(trigger, tooltip, placements[i])) { placement = placements[i]; break } } changePlacementClass(placement); } } // fix left and top for tooltip var rect = trigger.getBoundingClientRect(); var tooltipRect = tooltip.getBoundingClientRect(); var top; var left; if (placement === PLACEMENTS.BOTTOM) { top = containerScrollTop + rect.top + rect.height; left = containerScrollLeft + rect.left + rect.width / 2 - tooltipRect.width / 2; } else if (placement === PLACEMENTS.LEFT) { top = containerScrollTop + rect.top + rect.height / 2 - tooltipRect.height / 2; left = containerScrollLeft + rect.left - tooltipRect.width; } else if (placement === PLACEMENTS.RIGHT) { top = containerScrollTop + rect.top + rect.height / 2 - tooltipRect.height / 2; // https://github.com/uiv-lib/uiv/issues/272 // add 1px to fix above issue left = containerScrollLeft + rect.left + rect.width + 1; } else { top = containerScrollTop + rect.top - tooltipRect.height; left = containerScrollLeft + rect.left + rect.width / 2 - tooltipRect.width / 2; } var viewportEl; // viewport option if (isString(viewport)) { viewportEl = document.querySelector(viewport); } else if (isFunction(viewport)) { viewportEl = viewport(trigger); } if (isElement(viewportEl)) { var popoverFix = isPopover ? 11 : 0; var viewportReact = viewportEl.getBoundingClientRect(); var viewportTop = containerScrollTop + viewportReact.top; var viewportLeft = containerScrollLeft + viewportReact.left; var viewportBottom = viewportTop + viewportReact.height; var viewportRight = viewportLeft + viewportReact.width; // fix top if (top < viewportTop) { top = viewportTop; } else if (top + tooltipRect.height > viewportBottom) { top = viewportBottom - tooltipRect.height; } // fix left if (left < viewportLeft) { left = viewportLeft; } else if (left + tooltipRect.width > viewportRight) { left = viewportRight - tooltipRect.width; } // fix for popover pointer if (placement === PLACEMENTS.BOTTOM) { top -= popoverFix; } else if (placement === PLACEMENTS.LEFT) { left += popoverFix; } else if (placement === PLACEMENTS.RIGHT) { left -= popoverFix; } else { top += popoverFix; } } // set position finally tooltip.style.top = top + "px"; tooltip.style.left = left + "px"; } var MODAL_BACKDROP = 'modal-backdrop'; function getOpenModals () { return document.querySelectorAll(("." + MODAL_BACKDROP)) } function getOpenModalNum () { return getOpenModals().length } function getElementBySelectorOrRef (q) { if (isString(q)) { // is selector return document.querySelector(q) } else if (isElement(q)) { // is element return q } else if (isElement(q.$el)) { // is component return q.$el } else { return null } } var SHOW_CLASS = 'in'; var popupMixin = { props: { value: { type: Boolean, default: false }, tag: { type: String, default: 'span' }, placement: { type: String, default: PLACEMENTS.TOP }, autoPlacement: { type: Boolean, default: true }, appendTo: { type: null, default: 'body' }, positionBy: { type: null, default: null }, transition: { type: Number, default: 150 }, hideDelay: { type: Number, default: 0 }, showDelay: { type: Number, default: 0 }, enable: { type: Boolean, default: true }, enterable: { type: Boolean, default: true }, target: null, viewport: null, customClass: String }, data: function data () { return { triggerEl: null, hideTimeoutId: 0, showTimeoutId: 0, transitionTimeoutId: 0, autoTimeoutId: 0 } }, watch: { value: function value (v) { v ? this.show() : this.hide(); }, trigger: function trigger () { this.clearListeners(); this.initListeners(); }, target: function target (value) { this.clearListeners(); this.initTriggerElByTarget(value); this.initListeners(); }, allContent: function allContent (value) { var this$1$1 = this; // can not use value because it can not detect slot changes if (this.isNotEmpty()) { // reset position while content changed & is shown // nextTick is required this.$nextTick(function () { /* istanbul ignore else */ if (this$1$1.isShown()) { this$1$1.resetPosition(); } }); } else { this.hide(); } }, enable: function enable (value) { // hide if enable changed to false /* istanbul ignore else */ if (!value) { this.hide(); } } }, mounted: function mounted () { var this$1$1 = this; ensureElementMatchesFunction(); removeFromDom(this.$refs.popup); this.$nextTick(function () { this$1$1.initTriggerElByTarget(this$1$1.target); this$1$1.initListeners(); if (this$1$1.value) { this$1$1.show(); } }); }, beforeDestroy: function beforeDestroy () { this.clearListeners(); removeFromDom(this.$refs.popup); }, methods: { initTriggerElByTarget: function initTriggerElByTarget (target) { if (target) { // target exist this.triggerEl = getElementBySelectorOrRef(target); } else { // find special element var trigger = this.$el.querySelector('[data-role="trigger"]'); if (trigger) { this.triggerEl = trigger; } else { // use the first child var firstChild = this.$el.firstChild; this.triggerEl = firstChild === this.$refs.popup ? null : firstChild; } } }, initListeners: function initListeners () { if (this.triggerEl) { if (this.trigger === TRIGGERS.HOVER) { on(this.triggerEl, EVENTS.MOUSE_ENTER, this.show); on(this.triggerEl, EVENTS.MOUSE_LEAVE, this.hide); } else if (this.trigger === TRIGGERS.FOCUS) { on(this.triggerEl, EVENTS.FOCUS, this.show); on(this.triggerEl, EVENTS.BLUR, this.hide); } else if (this.trigger === TRIGGERS.HOVER_FOCUS) { on(this.triggerEl, EVENTS.MOUSE_ENTER, this.handleAuto); on(this.triggerEl, EVENTS.MOUSE_LEAVE, this.handleAuto); on(this.triggerEl, EVENTS.FOCUS, this.handleAuto); on(this.triggerEl, EVENTS.BLUR, this.handleAuto); } else if (this.trigger === TRIGGERS.CLICK || this.trigger === TRIGGERS.OUTSIDE_CLICK) { on(this.triggerEl, EVENTS.CLICK, this.toggle); } } on(window, EVENTS.CLICK, this.windowClicked); }, clearListeners: function clearListeners () { if (this.triggerEl) { off(this.triggerEl, EVENTS.FOCUS, this.show); off(this.triggerEl, EVENTS.BLUR, this.hide); off(this.triggerEl, EVENTS.MOUSE_ENTER, this.show); off(this.triggerEl, EVENTS.MOUSE_LEAVE, this.hide); off(this.triggerEl, EVENTS.CLICK, this.toggle); off(this.triggerEl, EVENTS.MOUSE_ENTER, this.handleAuto); off(this.triggerEl, EVENTS.MOUSE_LEAVE, this.handleAuto); off(this.triggerEl, EVENTS.FOCUS, this.handleAuto); off(this.triggerEl, EVENTS.BLUR, this.handleAuto); } off(window, EVENTS.CLICK, this.windowClicked); this.clearTimeouts(); }, clearTimeouts: function clearTimeouts () { if (this.hideTimeoutId) { clearTimeout(this.hideTimeoutId); this.hideTimeoutId = 0; } if (this.showTimeoutId) { clearTimeout(this.showTimeoutId); this.showTimeoutId = 0; } if (this.transitionTimeoutId) { clearTimeout(this.transitionTimeoutId); this.transitionTimeoutId = 0; } if (this.autoTimeoutId) { clearTimeout(this.autoTimeoutId); this.autoTimeoutId = 0; } }, resetPosition: function resetPosition () { var popup = this.$refs.popup; /* istanbul ignore else */ if (popup) { setTooltipPosition(popup, this.triggerEl, this.placement, this.autoPlacement, this.appendTo, this.positionBy, this.viewport); popup.offsetHeight; } }, hideOnLeave: function hideOnLeave () { if (this.trigger === TRIGGERS.HOVER || (this.trigger === TRIGGERS.HOVER_FOCUS && !this.triggerEl.matches(':focus'))) { this.$hide(); } }, toggle: function toggle () { if (this.isShown()) { this.hide(); } else { this.show(); } }, show: function show () { var this$1$1 = this; if (this.enable && this.triggerEl && this.isNotEmpty() && !this.isShown()) { var popUpAppendedContainer = this.hideTimeoutId > 0; // weird condition if (popUpAppendedContainer) { clearTimeout(this.hideTimeoutId); this.hideTimeoutId = 0; } if (this.transitionTimeoutId > 0) { clearTimeout(this.transitionTimeoutId); this.transitionTimeoutId = 0; } clearTimeout(this.showTimeoutId); this.showTimeoutId = setTimeout(function () { this$1$1.showTimeoutId = 0; var popup = this$1$1.$refs.popup; if (popup) { var alreadyOpenModalNum = getOpenModalNum(); if (alreadyOpenModalNum > 1) { var defaultZ = this$1$1.name === 'popover' ? 1060 : 1070; var offset = (alreadyOpenModalNum - 1) * 20; popup.style.zIndex = "" + (defaultZ + offset); } // add to dom if (!popUpAppendedContainer) { popup.className = (this$1$1.name) + " " + (this$1$1.placement) + " " + (this$1$1.customClass ? this$1$1.customClass : '') + " fade"; var container = getElementBySelectorOrRef(this$1$1.appendTo); container.appendChild(popup); this$1$1.resetPosition(); } addClass(popup, SHOW_CLASS); this$1$1.$emit('input', true); this$1$1.$emit('show'); } }, this.showDelay); } }, hide: function hide () { var this$1$1 = this; if (this.showTimeoutId > 0) { clearTimeout(this.showTimeoutId); this.showTimeoutId = 0; } if (!this.isShown()) { return } if (this.enterable && (this.trigger === TRIGGERS.HOVER || this.trigger === TRIGGERS.HOVER_FOCUS)) { clearTimeout(this.hideTimeoutId); this.hideTimeoutId = setTimeout(function () { this$1$1.hideTimeoutId = 0; var popup = this$1$1.$refs.popup; if (popup && !popup.matches(':hover')) { this$1$1.$hide(); } }, 100); } else { this.$hide(); } }, $hide: function $hide () { var this$1$1 = this; if (this.isShown()) { clearTimeout(this.hideTimeoutId); this.hideTimeoutId = setTimeout(function () { this$1$1.hideTimeoutId = 0; removeClass(this$1$1.$refs.popup, SHOW_CLASS); // gives fade out time this$1$1.transitionTimeoutId = setTimeout(function () { this$1$1.transitionTimeoutId = 0; removeFromDom(this$1$1.$refs.popup); this$1$1.$emit('input', false); this$1$1.$emit('hide'); }, this$1$1.transition); }, this.hideDelay); } }, isShown: function isShown () { return hasClass(this.$refs.popup, SHOW_CLASS) }, windowClicked: function windowClicked (event) { if (this.triggerEl && isFunction(this.triggerEl.contains) && !this.triggerEl.contains(event.target) && this.trigger === TRIGGERS.OUTSIDE_CLICK && !(this.$refs.popup && this.$refs.popup.contains(event.target)) && this.isShown()) { this.hide(); } }, handleAuto: function handleAuto () { var this$1$1 = this; clearTimeout(this.autoTimeoutId); this.autoTimeoutId = setTimeout(function () { this$1$1.autoTimeoutId = 0; if (this$1$1.triggerEl.matches(':hover, :focus')) { this$1$1.show(); } else { this$1$1.hide(); } }, 20); // 20ms make firefox happy } } }; var Tooltip = { mixins: [popupMixin], data: function data () { return { name: 'tooltip' } }, render: function render (h) { return h( this.tag, [ this.$slots.default, h('div', { ref: 'popup', attrs: { role: 'tooltip' }, on: { mouseleave: this.hideOnLeave } }, [ h('div', { class: 'tooltip-arrow' }), h('div', { class: 'tooltip-inner', domProps: { innerHTML: this.text } }) ] ) ] ) }, props: { text: { type: String, default: '' }, trigger: { type: String, default: TRIGGERS.HOVER_FOCUS } }, computed: { allContent: function allContent () { return this.text } }, methods: { isNotEmpty: function isNotEmpty () { return this.text } } }; var INSTANCE = '_uiv_tooltip_instance'; var bind = function (el, binding) { // console.log('bind') unbind(el); var Constructor = Vue.extend(Tooltip); var vm = new Constructor({ propsData: { target: el, appendTo: binding.arg && '#' + binding.arg, text: typeof binding.value === 'string' ? (binding.value && binding.value.toString()) : (binding.value && binding.value.text && binding.value.text.toString()), positionBy: binding.value && binding.value.positionBy && binding.value.positionBy.toString(), viewport: binding.value && binding.value.viewport && binding.value.viewport.toString(), customClass: binding.value && binding.value.customClass && binding.value.customClass.toString(), showDelay: binding.value && binding.value.showDelay, hideDelay: binding.value && binding.value.hideDelay } }); var options = []; for (var key in binding.modifiers) { if (hasOwnProperty(binding.modifiers, key) && binding.modifiers[key]) { options.push(key); } } options.forEach(function (option) { if (/(top)|(left)|(right)|(bottom)/.test(option)) { vm.placement = option; } else if (/(hover)|(focus)|(click)/.test(option)) { vm.trigger = option; } else if (/unenterable/.test(option)) { vm.enterable = false; } }); vm.$mount(); el[INSTANCE] = vm; }; var unbind = function (el) { // console.log('unbind') var vm = el[INSTANCE]; if (vm) { vm.$destroy(); } delete el[INSTANCE]; }; var update = function (el, binding) { // console.log('update') if (binding.value !== binding.oldValue) { bind(el, binding); } }; var tooltip = { bind: bind, unbind: unbind, update: update }; export default tooltip; //# sourceMappingURL=v_tooltip.js.map
{ "content_hash": "ca1505a58b1f351bc695b63484a2c9d5", "timestamp": "", "source": "github", "line_count": 726, "max_line_length": 165, "avg_line_length": 29.774104683195592, "alnum_prop": 0.5996021465581051, "repo_name": "cdnjs/cdnjs", "id": "4570e778a14e17cdbb1c5599c19874cb96b517c9", "size": "21616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/uiv/1.3.1/v_tooltip.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.pentaho.di.concurrency; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.commons.vfs2.provider.AbstractFileProvider; import org.junit.After; import org.junit.Test; import org.pentaho.di.core.vfs.KettleVFS; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; public class ConcurrentFileSystemManagerTest { private DefaultFileSystemManager fileSystemManager = (DefaultFileSystemManager) KettleVFS.getInstance().getFileSystemManager(); @After public void tearUp() { this.fileSystemManager.freeUnusedResources(); this.fileSystemManager.close(); } @Test public void getAndPutConcurrently() throws Exception { int numberOfGetters = 5; int numberOfPutters = 1; AtomicBoolean condition = new AtomicBoolean( true ); List<Getter> getters = new ArrayList<>(); for ( int i = 0; i < numberOfGetters; i++ ) { getters.add( new Getter( condition, this.fileSystemManager ) ); } List<Putter> putters = new ArrayList<>(); for ( int i = 0; i < numberOfPutters; i++ ) { putters.add( new Putter( condition, this.fileSystemManager ) ); } ConcurrencyTestRunner.runAndCheckNoExceptionRaised( putters, getters, condition ); } private class Getter extends StopOnErrorCallable<Object> { private DefaultFileSystemManager fsm; Getter( AtomicBoolean condition, DefaultFileSystemManager fsm ) { super( condition ); this.fsm = fsm; } @Override Object doCall() throws Exception { while ( condition.get() ) { this.fsm.getSchemes(); } return null; } } private class Putter extends StopOnErrorCallable<Object> { private DefaultFileSystemManager fsm; AbstractFileProvider provider; Putter( AtomicBoolean condition, DefaultFileSystemManager fsm ) { super( condition ); this.fsm = fsm; provider = mock( AbstractFileProvider.class ); doNothing().when( provider ).freeUnusedResources(); } @Override Object doCall() throws Exception { while ( condition.get() ) { this.fsm.addProvider( "scheme", provider ); // to register only one provider with a given scheme condition.set( false ); } return null; } } }
{ "content_hash": "cfb1d9934939d0824b98256acf12f397", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 86, "avg_line_length": 27.666666666666668, "alnum_prop": 0.6958869962609057, "repo_name": "alina-ipatina/pentaho-kettle", "id": "a4608e0c29bbc761cf72ab1e9d5c9bf0ce1355f5", "size": "3311", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "engine/test-src/org/pentaho/di/concurrency/ConcurrentFileSystemManagerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14382" }, { "name": "CSS", "bytes": "30418" }, { "name": "GAP", "bytes": "4005" }, { "name": "HTML", "bytes": "55153" }, { "name": "Java", "bytes": "40086635" }, { "name": "JavaScript", "bytes": "49292" }, { "name": "Shell", "bytes": "19927" }, { "name": "XSLT", "bytes": "5600" } ], "symlink_target": "" }
module Enjoy::News module Models module Mongoid module Category extend ActiveSupport::Concern include Enjoy::HtmlField included do field :name, type: String, localize: Enjoy::News.configuration.localize, default: "" scope :sorted, -> { order_by([:lft, :asc]) } enjoy_cms_html_field :excerpt, type: String, localize: Enjoy::News.configuration.localize, default: "" enjoy_cms_html_field :content, type: String, localize: Enjoy::News.configuration.localize, default: "" end def news news_class.in(category_ids: self.id) end def all_news news_class.any_in(category_ids: self.self_and_descendants.map(&:id)) end end end end end
{ "content_hash": "80753611477f99110871e8405bd3e659", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 114, "avg_line_length": 27.892857142857142, "alnum_prop": 0.6081946222791293, "repo_name": "enjoycreative/enjoy_cms_news", "id": "65a1b6a36a8b1a34dc613c455bf2d7f10be287c3", "size": "781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/enjoy/news/models/mongoid/category.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4041" }, { "name": "Ruby", "bytes": "39602" }, { "name": "Shell", "bytes": "225" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\devel_generate\Plugin\DevelGenerate\TermDevelGenerate. */ namespace Drupal\devel_generate\Plugin\DevelGenerate; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Language\Language; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\devel_generate\DevelGenerateBase; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a TermDevelGenerate plugin. * * @DevelGenerate( * id = "term", * label = @Translation("terms"), * description = @Translation("Generate a given number of terms. Optionally delete current terms."), * url = "term", * permission = "administer devel_generate", * settings = { * "num" = 10, * "title_length" = 12, * "kill" = FALSE, * } * ) */ class TermDevelGenerate extends DevelGenerateBase implements ContainerFactoryPluginInterface { /** * The vocabulary storage. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $vocabularyStorage; /** * The term storage. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $termStorage; /** * Constructs a new TermDevelGenerate object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Entity\EntityStorageInterface $vocabulary_storage * The vocabulary storage. * @param \Drupal\Core\Entity\EntityStorageInterface $term_storage * The term storage. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityStorageInterface $vocabulary_storage, EntityStorageInterface $term_storage) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->vocabularyStorage = $vocabulary_storage; $this->termStorage = $term_storage; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { $entity_manager = $container->get('entity.manager'); return new static( $configuration, $plugin_id, $plugin_definition, $entity_manager->getStorage('taxonomy_vocabulary'), $entity_manager->getStorage('taxonomy_term') ); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $options = array(); foreach ($this->vocabularyStorage->loadMultiple() as $vocabulary) { $options[$vocabulary->id()] = $vocabulary->label(); } $form['vids'] = array( '#type' => 'select', '#multiple' => TRUE, '#title' => $this->t('Vocabularies'), '#required' => TRUE, '#default_value' => 'tags', '#options' => $options, '#description' => $this->t('Restrict terms to these vocabularies.'), ); $form['num'] = array( '#type' => 'number', '#title' => $this->t('Number of terms?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0, ); $form['title_length'] = array( '#type' => 'number', '#title' => $this->t('Maximum number of characters in term names'), '#default_value' => $this->getSetting('title_length'), '#required' => TRUE, '#min' => 2, '#max' => 255, ); $form['kill'] = array( '#type' => 'checkbox', '#title' => $this->t('Delete existing terms in specified vocabularies before generating new terms.'), '#default_value' => $this->getSetting('kill'), ); return $form; } /** * {@inheritdoc} */ public function generateElements(array $values) { if ($values['kill']) { $this->deleteVocabularyTerms($values['vids']); $this->setMessage($this->t('Deleted existing terms.')); } $vocabs = $this->vocabularyStorage->loadMultiple($values['vids']); $new_terms = $this->generateTerms($values['num'], $vocabs, $values['title_length']); if (!empty($new_terms)) { $this->setMessage($this->t('Created the following new terms: @terms', array('@terms' => implode(', ', $new_terms)))); } } /** * Deletes all terms of given vocabularies. * * @param array $vids * Array of vocabulary vid. */ protected function deleteVocabularyTerms($vids) { $tids = $this->vocabularyStorage->getToplevelTids($vids); $terms = $this->termStorage->loadMultiple($tids); $this->termStorage->delete($terms); } /** * Generates taxonomy terms for a list of given vocabularies. * * @param int $records * Number of terms to create in total. * @param \Drupal\taxonomy\TermInterface[] $vocabs * List of vocabularies to populate. * @param int $maxlength * (optional) Maximum length per term. * * @return array * The list of names of the created terms. */ protected function generateTerms($records, $vocabs, $maxlength = 12) { $terms = array(); // Insert new data: $max = db_query('SELECT MAX(tid) FROM {taxonomy_term_data}')->fetchField(); $start = time(); for ($i = 1; $i <= $records; $i++) { $name = $this->getRandom()->word(mt_rand(2, $maxlength)); $values = array( 'name' => $name, 'description' => 'description of ' . $name, 'format' => filter_fallback_format(), 'weight' => mt_rand(0, 10), 'langcode' => Language::LANGCODE_NOT_SPECIFIED, ); switch ($i % 2) { case 1: $vocab = $vocabs[array_rand($vocabs)]; $values['vid'] = $vocab->id(); $values['parent'] = array(0); break; default: while (TRUE) { // Keep trying to find a random parent. $candidate = mt_rand(1, $max); $query = db_select('taxonomy_term_data', 't'); $parent = $query ->fields('t', array('tid', 'vid')) ->condition('t.vid', array_keys($vocabs), 'IN') ->condition('t.tid', $candidate, '>=') ->range(0, 1) ->execute() ->fetchAssoc(); if ($parent['tid']) { break; } } $values['parent'] = array($parent['tid']); // Slight speedup due to this property being set. $values['vid'] = $parent['vid']; break; } $term = $this->termStorage->create($values); // Populate all fields with sample values. $this->populateFields($term); $term->save(); $max++; if (function_exists('drush_log')) { $feedback = drush_get_option('feedback', 1000); if ($i % $feedback == 0) { $now = time(); drush_log(dt('Completed @feedback terms (@rate terms/min)', array('@feedback' => $feedback, '@rate' => $feedback * 60 / ($now - $start))), 'ok'); $start = $now; } } // Limit memory usage. Only report first 20 created terms. if ($i < 20) { $terms[] = $term->label(); } unset($term); } return $terms; } /** * {@inheritdoc} */ public function validateDrushParams($args) { $vname = array_shift($args); $values = array( 'num' => array_shift($args), 'kill' => drush_get_option('kill'), 'title_length' => 12, ); // Try to convert machine name to a vocab ID if (!$vocab = $this->vocabularyStorage->load($vname)) { return drush_set_error('DEVEL_GENERATE_INVALID_INPUT', dt('Invalid vocabulary name: @name', array('@name' => $vname))); } if ($this->isNumber($values['num']) == FALSE) { return drush_set_error('DEVEL_GENERATE_INVALID_INPUT', dt('Invalid number of terms: @num', array('@num' => $values['num']))); } $values['vids'] = array($vocab->id()); return $values; } }
{ "content_hash": "795c8d16b1188fd2c81ba4b9d3b409dd", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 167, "avg_line_length": 30.597701149425287, "alnum_prop": 0.5886551465063862, "repo_name": "edwardchan/d8-drupalvm", "id": "ef610552c27d18f89a31190885c6232beb14b1e3", "size": "7986", "binary": false, "copies": "30", "ref": "refs/heads/master", "path": "drupal/modules/devel/devel_generate/src/Plugin/DevelGenerate/TermDevelGenerate.php", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "50616" }, { "name": "CSS", "bytes": "1250515" }, { "name": "HTML", "bytes": "646836" }, { "name": "JavaScript", "bytes": "1018469" }, { "name": "PHP", "bytes": "31387248" }, { "name": "Shell", "bytes": "675" }, { "name": "SourcePawn", "bytes": "31943" } ], "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.kubernetesconfiguration.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Specifies that the scope of the extension is Namespace. */ @Fluent public final class ScopeNamespace { /* * Namespace where the extension will be created for an Namespace scoped * extension. If this namespace does not exist, it will be created */ @JsonProperty(value = "targetNamespace") private String targetNamespace; /** * Get the targetNamespace property: Namespace where the extension will be created for an Namespace scoped * extension. If this namespace does not exist, it will be created. * * @return the targetNamespace value. */ public String targetNamespace() { return this.targetNamespace; } /** * Set the targetNamespace property: Namespace where the extension will be created for an Namespace scoped * extension. If this namespace does not exist, it will be created. * * @param targetNamespace the targetNamespace value to set. * @return the ScopeNamespace object itself. */ public ScopeNamespace withTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
{ "content_hash": "5a9565acf36ee5aebdc1255552bd44d8", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 110, "avg_line_length": 33.42857142857143, "alnum_prop": 0.7045177045177046, "repo_name": "Azure/azure-sdk-for-java", "id": "558620cda1565b62673afef11b090957e9ab8063", "size": "1638", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/src/main/java/com/azure/resourcemanager/kubernetesconfiguration/models/ScopeNamespace.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": "" }
The goal of YINsolidated is to generate a single JSON document with all augments and submodules merged together. Because the native `yin` format is XML there are some oddities when converting to JSON. What would be a XML node becomes a JSON Object that represents a single `YinElement` with the following schema: - Each object always has a `"keyword": string`. This would be the XML element tag. - Sub-objects are grouped under `"children": YinElement[]`. - Each object has `namespace: string` - Each object has `nsmap: { [prefix: string]: string }` which is a mapping of namespace-prefix to uri - All other attributes are optional. Additionally the following transformations are applied: ## Submodules All data definitions within a `submodule` are included as child elements of the main module element. ## Augments * All `augment` statements are resolved such that all data definition statements within the `augment` are added as child elements to the element indicated by the `augment`'s target node. * Any `when` sub-statements of an `augment` are added as child elements to each of the augmenting data definition elements described above. To differentiate these from actual `when` sub-statements of those data definitions, the added `when` elements are given a `context-node="parent"` attribute. This way, the `when` statement still makes the data definition conditional, and the XPath expression can be evaluated against the proper context node. * Similarly, any `if-feature` sub-statements of an `augment` are added as child elements to each of the augmenting data definitions. No modifications to these elements are necessary because they still make the data definition dependent on the feature. E.g. this YANG snippet: ```yang container augmented-container; augment "augmented-container" { if-feature my-feature; when "a-leaf != 'foo'"; container augmenting-container; leaf augmenting-leaf { type string; } } ``` Becomes: ```json { "keyword": "container", "name": "augmented-container", "children": [ { "keyword": "container", "name": "augmenting-container", "children": [ { "keyword": "if-feature", "name": "my-feature" }, { "keyword": "when", "condition": "a-leaf != 'foo'", "context-node": "parent" } ] }, { "keyword": "leaf", "name": "augmenting-leaf", "children": [ { "keyword": "if-feature", "name": "my-feature"}, { "keyword": "when", "condition": "a-leaf != 'foo'", "context-node": "parent" } { "keyword": "type", "name": "string" } ] } ] } ``` ## Uses * All `uses` statements are resolved such that all data definitions sub- statements of the used `grouping` (grouped data definitions) are added as elements in place of the `uses` statement. * All `when` sub-statements of a `uses` are handled exactly the same way as those of an `augment`, except they are added to the grouped data definition elements. * All `if-feature` sub-statements of a `uses` are handled in the same way as those of an `augment`, except they are added to the grouped data definition elements. E.g. this YANG snippet: ```yang grouping my-grouping { if-feature my-feature; when "a-leaf != 'foo'"; container grouped-container; leaf grouped-leaf { type string; } } container root { uses my-grouping; } ``` Becomes: ```json { "keyword": "root", "name": "grouped-container", "children": [ { "keyword": "container", "name": "grouped-container", "children": [ { "keyword": "if-feature", "name": "my-feature" }, { "keyword": "when", "condition": "a-leaf != 'foo'", "context-node": "parent" } ] }, { "keyword": "leaf", "name": "grouped-leaf", "children": [ { "keyword": "if-feature", "name": "my-feature"}, { "keyword": "when", "condition": "a-leaf != 'foo'", "context-node": "parent" } { "keyword": "type", "name": "string" } ] } ] } ``` ## Typedefs Any `type` statement that refers to a `typedef` is resolved recursively, such that the `typedef` is added as a child element of the `type` element. The `typedef` itself has a child `type` element, which will also be resolved if it refers to another `typedef`. E.g. this YANG snippet: ```yang typedef base-type { type string { length 1..255; } } typedef derived-type { type base-type { length 10; } } leaf my-leaf { type derived-type { pattern "[A-Z]*"; } } ``` Becomes: ```json { "keyword": "leaf", "name": "my-leaf", "children": [ { "keyword": "type", "name": "derived-type", "children": [ { "keyword": "pattern", "value": "[A-Z]*" }, { "keyword": "typedef", "name": "derived-type", "children": [ { "keyword": "type", "name": "base-type", "children": [ { "keyword": "length", "value": "10" }, { "keyword": "typedef", "name": "base-type", "children": [ { "keyword": "type", "name": "string", "children": [{ "keyword": "length", "value": "1..255" }] } ] } ] } ] } ] } ] } ``` ## Leafrefs Any `leafref` type is resolved such that the `type` statement of the referenced `leaf` is added as a child element to the `type` element. If the type of the referenced `leaf` is a `typedef`, it will be resolved as described in the [Typedefs](#typedefs) section. E.g. this YANG snippet: ```yang leaf referenced-leaf { type string; } leaf referring-leaf { type leafref { path "/referenced-leaf"; } } ``` Becomes: ```json { "keyword": "leaf", "name": "referenced-string", }, { "keyword": "leaf", "name": "referring-leaf", "children": [ { "keyword": "type", "name": "leafref", "children": [ { "keyword": "path", "value": "/referenced-leaf" }, { "keyword": "type", "name": "string" }, ] } ] } ``` ## Extensions `extension` statements can be represented in the **YINsolidated** model in two different ways. ### Simple Extensions This is the default format, which provides a simplified representation over the traditional YIN format. Each `extension` statement is simply added as a child element of its parent statement, and its argument is set as the text of that element. E.g. this YANG snippet: ```yang namespace "foo:ns"; prefix foo; extension element-ext { argument element-arg { yin-element true; } } extension attribute-ext { argument attribute-arg { yin-element false; } } foo:element-ext "Element text"; foo:attribute-ext "Attribute text" { description "This won't appear in YINsolidated"; } ``` Becomes: ```json { "keyword": "element-ext", "namespace": "foo:ns", "nsmap": { "foo": "foo:ns" }, "text": "Element text" }, { "keyword": "attribute-ext", "namespace": "foo:ns", "nsmap": { "foo": "foo:ns" }, "text": "Attribute text" } ``` ### Complex (YIN-formatted) Extensions The simple format does not support sub-statements on extensions. To support this use case, the traditional YIN format can be enabled by adding the tag `#yinformat` to the extension description. In this format, each `extension` statement is added as a child element of its parent statement, and its argument can be set either as an attribute on that element or as a child element. E.g. this YANG snippet: ```yang namespace "foo:ns"; prefix foo; extension element-ext { argument element-arg { yin-element true; } description "This should follow #yinformat"; } extension attribute-ext { argument attribute-arg { yin-element false; } description "This should follow #yinformat"; } foo:element-ext "Element text"; foo:attribute-ext "Attribute text" { description "This will appear in YINsolidated"; } ``` Becomes: ```json { "keyword": "element-ext", "namespace": "foo:ns", "nsmap": { "foo": "foo:ns" }, "text": "Element text" }, { "keyword": "attribute-ext", "namespace": "foo:ns", "nsmap": { "foo": "foo:ns" }, "attribute-arg": "Attribute text", "children": [{ "keyword": "description", "text": "This will appear in YINsolidated" }] } ``` ## Cases The `case` statement can be omitted in YANG if the `case` only consists of a single data definition statement. When converted to the **YINsolidated** model, this data definition element will be wrapped in a `case` element even if the `case` statement is omitted. E.g. this YANG snippet: ```yang choice my-choice { case foo { container foo; } container bar; } ``` Becomes: ```json { "keyword": "choice", "name": "my-choice", "children": [ { "keyword": "case", "name": "foo", "children": [{ "keyword": "container", "name": "foo" }] }, { "keyword": "case", "name": "bar", "children": [{ "keyword": "container", "name": "bar" }] } ] } ``` ## Omitting Resolved Statements Any statements that are resolved by the above rules become useless in the **YINsolidated** model because the information they convey is represented in- place. Thus, the following statements are **NOT** added as elements in the **YINsolidated** model: * `augment` * `belongs-to` * `grouping` * `import` * `include` * `refine` * `submodule` * `uses` ## Namespaces and Prefixes Each module has its own local mapping of prefixes to namespaces for the modules it imports, and text values within the module may use these locally defined prefixes. Thus, for any given element in the document, it is also necessary to know the current namespace mapping. This is accomplished by adding the appropriate namespace mappings to the top-level `module` element as well as to any augmenting data definitions from external modules. In addition, each YANG module has its own namespace and associated prefix which scopes the data definitions contained in that module. When parsing the model, it is important to know the namespace and prefix to which a data definition belongs. To accomplish this, the prefix for the main module is stored as an attribute of the top-level module element, and the prefix of any module augmenting the main module is stored as an attribute of each augmenting data definition element. This way, any data definition element within the document is scoped to the prefix of the closest ancestor element with the `module-prefix` attribute. The namespace associated with this prefix can be acquired using the namespace mapping. E.g. these YANG modules: ```yang module main { namespace "urn:main"; prefix main; container root; } module augmenting { namespace "urn:augmenting"; prefix aug; import main { prefix m; } augment "/m:root" { leaf my-leaf { types string; } } } ``` Become: ```json { "keyword": "module", "name": "main", "module-prefix": "main", "namespace": "urn:main", "nsmap": { "main": "urn:main", "yin": "urn:ietf:params:xml:ns:yang:yin:1" }, "children": [ { "keyword": "container", "name": "root", "children": [ { "keyword": "leaf", "name": "my-leaf", "module-prefix": "aug", "namespace": "urn:augmenting", "nsmap": { "m": "urn:main", "yin": "urn:ietf:params:xml:ns:yang:yin:1" }, "children": [{ "keyword": "type", "name": "string" }] }, ] } ] } ``` ## Identities Since the **YINsolidated** model contains only one module element, `identity` statements defined in other modules are included as children of the module element. In order to properly represent namespaces, each identity element is given the namespace map from its original module as well as a `module-prefix` attribute to indicate the namespace in which it was defined. E.g. these YANG modules: ```yang module main { namespace "urn:main"; prefix main; identity base-identity; } module augmenting { namespace "urn:augmenting"; prefix aug; import main { prefix m; } identity derived-identity { base m:base-identity; } } ``` Become: ```json { "keyword": "module", "name": "main", "module-prefix": "main", "namespace": "urn:main", "nsmap": { "main": "urn:main", "yin": "urn:ietf:params:xml:ns:yang:yin:1" }, "children": [ { "keyword": "identity", "name": "base-identity", "module-prefix": "main", "namespace": "urn:main", "nsmap": { "main": "urn:main", "yin": "urn:ietf:params:xml:ns:yang:yin:1" }, }, { "keyword": "identity", "name": "derived-identity", "module-prefix": "aug", "namespace": "urn:augmenting", "nsmap": { "m": "urn:main", "yin": "urn:ietf:params:xml:ns:yang:yin:1", "aug": "url:augmenting" }, "children": [{ "keyword": "base", "name": "m:base-identity" }] } ] } ```
{ "content_hash": "9567b574ec197aa6558ce6fb04fcfdf7", "timestamp": "", "source": "github", "line_count": 549, "max_line_length": 243, "avg_line_length": 24.18943533697632, "alnum_prop": 0.6199548192771084, "repo_name": "128technology/yinsolidated", "id": "dcf7760c269eeaef1a58ec99564646a8eec0fbe9", "size": "13303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/JSONFormat.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "125435" } ], "symlink_target": "" }
namespace Simple.Web.TestHelpers.Xml { using System.Xml.Linq; using Xunit.Sdk; public static class XNameExtensions { public static void ShouldEqual(this XName actual, XName expected) { if (actual.ToString() != expected.ToString()) { throw new EqualException(expected, actual); } } public static void ShouldEqual(this XName actual, string expected) { if (actual.ToString() != expected) { throw new EqualException(expected, actual.ToString()); } } } }
{ "content_hash": "4a1a283dd5e7b98c0399157a8167eb72", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 68, "avg_line_length": 20.833333333333332, "alnum_prop": 0.684, "repo_name": "markrendle/Simple.Web", "id": "35d8f7ca0e2faea633d4d6e35dbe993f72543503", "size": "500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Simple.Web.TestHelpers/Xml/XNameExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "633005" }, { "name": "PowerShell", "bytes": "3370" }, { "name": "Puppet", "bytes": "819" }, { "name": "Ruby", "bytes": "14058" }, { "name": "Shell", "bytes": "438" } ], "symlink_target": "" }
using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace Messaging { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public enum Pages { MainPage } public override Task OnInitializeAsync(IActivatedEventArgs args) { var keys = PageKeys<Pages>(); keys.Add(Pages.MainPage, typeof(Views.MainPage)); return base.OnInitializeAsync(args); } public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(Pages.MainPage, 2); return Task.CompletedTask; } } }
{ "content_hash": "c300b7c417c4a9e4df2ecaeb09d32ea0", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 88, "avg_line_length": 26.035714285714285, "alnum_prop": 0.6337448559670782, "repo_name": "ivesely/Template10", "id": "7de3618c755c8b9f10a7cbf24d7e95b9802f6e97", "size": "731", "binary": false, "copies": "2", "ref": "refs/heads/Master", "path": "Samples/PageKeys/App.xaml.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2414" }, { "name": "C#", "bytes": "482871" }, { "name": "CSS", "bytes": "1778" }, { "name": "HTML", "bytes": "584" }, { "name": "PowerShell", "bytes": "151" } ], "symlink_target": "" }
module.exports = function(grunt) { grunt.initConfig({ 'shell': { 'options': { 'stdout': true, 'stderr': true, 'failOnError': true }, 'cover-html': { 'command': 'istanbul cover --report "html" --verbose --dir "coverage" "tests/tests.js"' }, 'cover-coveralls': { 'command': 'istanbul cover --verbose --dir "coverage" "tests/tests.js" && coveralls < coverage/lcov.info; rm -rf coverage/lcov*' }, 'test-node': { 'command': 'echo "Testing in Node..."; npm test' }, 'test-browser': { 'command': 'echo "Testing in a browser..."; open "tests/index.html"; open "tests/index.html?norequire=true"' } }, 'template': { 'build': { 'options': { 'data': function() { return require('./scripts/export-data.js'); } }, 'files': { 'base64.js': ['src/base64.js'] } } } }); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-template'); grunt.registerTask('cover', 'shell:cover-html'); grunt.registerTask('ci', [ 'template', 'shell:test-node' ]); grunt.registerTask('test', [ 'ci', 'shell:test-browser' ]); grunt.registerTask('fetch', [ 'shell:fetch', 'build' ]); grunt.registerTask('build', [ 'default' ]); grunt.registerTask('default', [ 'template', 'shell:test-node' ]); };
{ "content_hash": "fa3b1d0e98450129274091b992f97a2d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 132, "avg_line_length": 20.53125, "alnum_prop": 0.578386605783866, "repo_name": "mathiasbynens/base64", "id": "1c7fb410adabab064ce51af2a6bc00a44da054b7", "size": "1314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gruntfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "33283" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "fdadaec393064bc72ab5e9528e2a0de0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "e63be9fc4d86a00086258ee95795f0d943cf8e4d", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Persea/Persea dulcis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package lu.ing.gameofcode.fragments; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.model.LatLng; import com.octo.android.robospice.SpiceManager; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.request.listener.RequestListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; import lu.ing.gameofcode.R; import lu.ing.gameofcode.line.LineBean; import lu.ing.gameofcode.line.LineBeanSorter; import lu.ing.gameofcode.model.BusStop; import lu.ing.gameofcode.requests.LineBeansRequest; import lu.ing.gameofcode.services.BusService; import lu.ing.gameofcode.services.BusServiceImpl; import lu.ing.gameofcode.utils.MySpiceService; import lu.ing.gameofcode.utils.SharedPreferencesUtils; import lu.ing.gameofcode.veloh.VelohAlternative; import lu.ing.gameofcode.veloh.VelohStationBean; public class BusFragment extends Fragment { @Bind(R.id.timeline_rv) RecyclerView mRecyclerView; @Bind(R.id.buslines_sp) Spinner busLinesSpinner; @Bind(R.id.loading_pb) ProgressBar loadingView; private SpiceManager spiceManager = new SpiceManager(MySpiceService.class); private BusService busService; private List<BusStop> busStops; private List<VelohStationBean> velohStationBeen; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_bus, container, false); ButterKnife.bind(this, rootView); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(mLayoutManager); busService = new BusServiceImpl(getContext()); return rootView; } @Override public void onStart() { super.onStart(); spiceManager.start(getContext()); loadBusLines(); } @Override public void onStop() { super.onStop(); spiceManager.shouldStop(); } private void loadBusLines() { showLoading(); SharedPreferences preferences = getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE); final String homeLongitude = Double.toString(SharedPreferencesUtils.getDouble(preferences, "homeLongitude", 0)); final String homeLatitude = Double.toString(SharedPreferencesUtils.getDouble(preferences, "homeLatitude", 0)); final String workLongitude = Double.toString(SharedPreferencesUtils.getDouble(preferences, "workLongitude", 0)); final String workLatitude = Double.toString(SharedPreferencesUtils.getDouble(preferences, "workLatitude", 0)); final LineBeansRequest request = new LineBeansRequest(getContext(), homeLatitude, homeLongitude, workLatitude, workLongitude); spiceManager.execute(request, new BusLinesRequestListener()); } private LatLng getCoordinates(final SharedPreferences preferences, final String latProp, final String longProp) { return new LatLng( SharedPreferencesUtils.getDouble(preferences, latProp, 0), SharedPreferencesUtils.getDouble(preferences, longProp, 0)); } private void loadBusStops(final String num) { showLoading(); SharedPreferences preferences = getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE); final LatLng home = getCoordinates(preferences, "homeLatitude", "homeLongitude"); final LatLng work = getCoordinates(preferences, "workLatitude", "workLongitude"); busStops = busService.getBusStops(num, home, work); if (busStops == null) { hideLoading(); return; } velohStationBeen = new ArrayList<>(); for (BusStop busStop : busStops) { } RecyclerView.Adapter mAdapter = new MyAdapter(busStops); mRecyclerView.setAdapter(mAdapter); hideLoading(); } private void showLoading() { loadingView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); } private void hideLoading() { loadingView.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE); } private void setupBusLinesSpinner(final List<LineBean> lineBeen) { Collections.sort(lineBeen, new LineBeanSorter()); final ArrayAdapter<LineBean> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, lineBeen); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); busLinesSpinner.setAdapter(adapter); busLinesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { loadBusStops(lineBeen.get(position).getNum()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public static class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<lu.ing.gameofcode.model.BusStop> mDataset; public static class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.title_tv) public TextView mTextView; public ViewHolder(View v) { super(v); ButterKnife.bind(this, v); } } public MyAdapter(List<lu.ing.gameofcode.model.BusStop> myDataset) { mDataset = myDataset; } @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_timeline, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final lu.ing.gameofcode.model.BusStop busStop = mDataset.get(position); holder.mTextView.setText(String.format(Locale.FRANCE, "%s\n%d minutes de marche", busStop.getName(), busStop.getPath().getTimeFoot() / 60)); } @Override public int getItemCount() { return mDataset.size(); } } private class BusLinesRequestListener implements RequestListener<LineBean[]> { @Override public void onRequestFailure(SpiceException spiceException) { hideLoading(); } @Override public void onRequestSuccess(LineBean[] lines) { hideLoading(); setupBusLinesSpinner(Arrays.asList(lines)); } } }
{ "content_hash": "ac4a1ff42590918d90fc8ff5f387e705", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 128, "avg_line_length": 35.39622641509434, "alnum_prop": 0.6840351812366737, "repo_name": "seventy-three/gameofcode-app", "id": "e256c6378877a9b6d239fafe0c9f9b5c3d4c918a", "size": "7504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gameofcode/app/src/main/java/lu/ing/gameofcode/fragments/BusFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "85286" } ], "symlink_target": "" }
package org.apache.ignite.internal.processors.bulkload; import java.util.List; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteIllegalStateException; import org.apache.ignite.internal.processors.query.RunningQueryManager; import org.apache.ignite.internal.util.lang.IgniteClosureX; import org.apache.ignite.lang.IgniteBiTuple; /** * Bulk load (COPY) command processor used on server to keep various context data and process portions of input * received from the client side. */ public class BulkLoadProcessor implements AutoCloseable { /** Parser of the input bytes. */ private final BulkLoadParser inputParser; /** * Converter, which transforms the list of strings parsed from the input stream to the key+value entry to add to * the cache. */ private final IgniteClosureX<List<?>, IgniteBiTuple<?, ?>> dataConverter; /** Streamer that puts actual key/value into the cache. */ private final BulkLoadCacheWriter outputStreamer; /** Becomes true after {@link #close()} method is called. */ private boolean isClosed; /** Running query manager. */ private final RunningQueryManager runningQryMgr; /** Query id. */ private final Long qryId; /** Exception, current load process ended with, or {@code null} if in progress or if succeded. */ private Exception failReason; /** * Creates bulk load processor. * * @param inputParser Parser of the input bytes. * @param dataConverter Converter, which transforms the list of strings parsed from the input stream to the * key+value entry to add to the cache. * @param outputStreamer Streamer that puts actual key/value into the cache. * @param runningQryMgr Running query manager. * @param qryId Running query id. */ public BulkLoadProcessor(BulkLoadParser inputParser, IgniteClosureX<List<?>, IgniteBiTuple<?, ?>> dataConverter, BulkLoadCacheWriter outputStreamer, RunningQueryManager runningQryMgr, Long qryId) { this.inputParser = inputParser; this.dataConverter = dataConverter; this.outputStreamer = outputStreamer; this.runningQryMgr = runningQryMgr; this.qryId = qryId; isClosed = false; } /** * Returns the streamer that puts actual key/value into the cache. * * @return Streamer that puts actual key/value into the cache. */ public BulkLoadCacheWriter outputStreamer() { return outputStreamer; } /** * Processes the incoming batch and writes data to the cache by calling the data converter and output streamer. * * @param batchData Data from the current batch. * @param isLastBatch true if this is the last batch. * @throws IgniteIllegalStateException when called after {@link #close()}. */ public void processBatch(byte[] batchData, boolean isLastBatch) throws IgniteCheckedException { if (isClosed) throw new IgniteIllegalStateException("Attempt to process a batch on a closed BulkLoadProcessor"); Iterable<List<Object>> inputRecords = inputParser.parseBatch(batchData, isLastBatch); for (List<Object> record : inputRecords) { IgniteBiTuple<?, ?> kv = dataConverter.apply(record); outputStreamer.apply(kv); } } /** * Is called to notify processor, that bulk load execution, this processor is performing, failed with specified * exception. * * @param failReason why current load failed. */ public void onError(Exception failReason) { this.failReason = failReason; } /** * Aborts processing and closes the underlying objects ({@link IgniteDataStreamer}). */ @Override public void close() throws Exception { if (isClosed) return; try { isClosed = true; outputStreamer.close(); } catch (Exception e) { if (failReason == null) failReason = e; throw e; } finally { runningQryMgr.unregister(qryId, failReason); } } }
{ "content_hash": "1918132f441f454a295f4067ac1c50a3", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 116, "avg_line_length": 34.203252032520325, "alnum_prop": 0.672450677442358, "repo_name": "SomeFire/ignite", "id": "a92bbdfd9687f24498e518f5002772587756f87e", "size": "5009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/bulkload/BulkLoadProcessor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "61105" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "6461926" }, { "name": "C++", "bytes": "3681449" }, { "name": "CSS", "bytes": "281251" }, { "name": "Dockerfile", "bytes": "16105" }, { "name": "Groovy", "bytes": "15081" }, { "name": "HTML", "bytes": "821135" }, { "name": "Java", "bytes": "42676141" }, { "name": "JavaScript", "bytes": "1785625" }, { "name": "M4", "bytes": "21724" }, { "name": "Makefile", "bytes": "121296" }, { "name": "PHP", "bytes": "486991" }, { "name": "PLpgSQL", "bytes": "623" }, { "name": "PowerShell", "bytes": "12208" }, { "name": "Python", "bytes": "342274" }, { "name": "Scala", "bytes": "1386030" }, { "name": "Shell", "bytes": "612951" }, { "name": "TSQL", "bytes": "6130" }, { "name": "TypeScript", "bytes": "476855" } ], "symlink_target": "" }
package battleship.gui.client; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** * Contains fields for the player's name and the server's host name. * <p> * The "Join" button will invoke JoinPanel.JoinCallback's join() method. * </p> */ public class JoinPanel extends JPanel implements BusyListener { public interface JoinCallback { public void join(String playerName, String address, BusyListener busy); } private static final long serialVersionUID = 1L; private class JoinButtonListener implements ActionListener { private JoinCallback joinCallback; private JoinButtonListener(JoinCallback joinCallback) { this.joinCallback = joinCallback; } @Override public void actionPerformed(ActionEvent e) { String playerName = playerNameField.getText(); String address = addressField.getText(); if (playerName.isEmpty()) { JOptionPane.showMessageDialog(null, "Please enter your name"); } else if (address.isEmpty()) { JOptionPane.showMessageDialog(null, "Please enter the server address"); } else { joinCallback.join(playerName, address, JoinPanel.this); } } } private WaitingPanel wp; private JButton joinButton; private JTextField playerNameField, addressField; public JoinPanel(final JoinCallback joinCallback) { super(new GridBagLayout()); playerNameField = new JTextField(); addressField = new JTextField("localhost"); joinButton = new JButton("Join"); joinButton.addActionListener(new JoinButtonListener(joinCallback)); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.ipadx = 10; c.weightx = 0; c.gridx = 0; c.gridy = 0; add(new JLabel("Your name:"), c); c.gridy++; add(new JLabel("Server:"), c); c.weightx = 0.0; c.gridwidth = 2; c.gridx = 1; c.gridy = 0; add(playerNameField, c); c.gridy++; add(addressField, c); // Add a dummy label for padding c.weightx = 1.0; c.gridwidth = 1; c.gridx = 1; c.gridy++; add(new JLabel(), c); c.weightx = 0.5; c.gridx = 2; add(joinButton, c); wp = new WaitingPanel(); wp.setVisible(false); JLabel dummy = new JLabel(); dummy.setPreferredSize(wp.getPreferredSize()); c.gridx = 0; c.weightx = 0; c.gridy++; add(dummy, c); c.gridx++; add(wp, c); } public JButton getDefaultButton() { return joinButton; } @Override public void busy() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { joinButton.setEnabled(false); playerNameField.setEnabled(false); addressField.setEnabled(false); wp.setVisible(true); } }); } @Override public void unbusy() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { wp.setVisible(false); addressField.setEnabled(true); playerNameField.setEnabled(true); joinButton.setEnabled(true); } }); } }
{ "content_hash": "8b7749dd9fc7d634e900609ee90da62b", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 87, "avg_line_length": 27.62857142857143, "alnum_prop": 0.5747156153050672, "repo_name": "nukep/battleship", "id": "2e0d46eae177269ad2f79e568547a2caf4cff308", "size": "3868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/battleship/gui/client/JoinPanel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "179" }, { "name": "Java", "bytes": "115147" } ], "symlink_target": "" }
<?php /** * @author Andre Lohmann * * @package bootstrap-extra-fields */ class BootstrapAceEditorField extends TextareaField { protected $theme = "textmate"; protected $mode = "javascript"; /** * Set the theme * * @param string $theme * * @return $this */ public function setTheme($theme) { $this->theme = $theme; return $this; } /** * Set the mode * * @param string $mode * * @return $this */ public function setMode($mode) { $this->mode = $mode; return $this; } public function Field($properties = array()) { $css = <<<CSS #{$this->ID()}-ace-editor { height: 300px; } CSS; Requirements::customCSS($css, 'BootstrapAceEditorField_Css_'.$this->ID()); Requirements::javascript('bootstrap_extra_fields/thirdparty/ace-min-noconflict/ace.js'); // set caption if required $js = <<<JS $(document).ready(function() { var editor = ace.edit("{$this->ID()}-ace-editor"); editor.setValue($('#{$this->ID()}').val()); editor.setTheme("ace/theme/{$this->theme}"); editor.getSession().setMode("ace/mode/{$this->mode}"); editor.getSession().on('change', function(e) { $('#{$this->ID()}').html(editor.getValue()); }); }); JS; Requirements::customScript($js, 'BootstrapAceEditorField_Js_'.$this->ID()); return parent::Field($properties); } }
{ "content_hash": "5ecb1a768443d2fae5c464a03473ec3b", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 90, "avg_line_length": 20.584615384615386, "alnum_prop": 0.6128550074738416, "repo_name": "andrelohmann/silverstripe-bootstrap_extra_fields", "id": "c7c1556c00bb1c858a9f8b15a506bedb5715f90e", "size": "1338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/forms/BootstrapAceEditorField.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "143" }, { "name": "JavaScript", "bytes": "194318" }, { "name": "PHP", "bytes": "108638" }, { "name": "Scheme", "bytes": "58790" } ], "symlink_target": "" }
package dmlgen import ( "bytes" "crypto/md5" "fmt" ) type tables []*Table // hasFeature returns false when any of the tables does not have the feature/s. func (ts tables) hasFeature(g *Generator, feature FeatureToggle) bool { for _, tbl := range ts { if g.hasFeature(tbl.featuresInclude, tbl.featuresExclude, feature) { return true } } return false } func (ts tables) names() []string { names := make([]string, len(ts)) for i, tbl := range ts { names[i] = tbl.Table.Name } return names } // nameID returns a consistent md5 hash of the table names. func (ts tables) nameID() string { var buf bytes.Buffer for _, tbl := range ts { buf.WriteString(tbl.Table.Name) } return fmt.Sprintf("%x", md5.Sum(buf.Bytes())) }
{ "content_hash": "faef4710401175acd2c7fa8daf37180e", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 79, "avg_line_length": 20.61111111111111, "alnum_prop": 0.6765498652291105, "repo_name": "corestoreio/csfw", "id": "55bfd0967e63ce7f7ffb4ae8c866f1602173542b", "size": "742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sql/dmlgen/tables.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "5341817" }, { "name": "Makefile", "bytes": "2473" }, { "name": "Shell", "bytes": "559" }, { "name": "Yacc", "bytes": "21579" } ], "symlink_target": "" }
require 'test_helper' module ActiveModel class Serializer class AssociationsTest < Minitest::Test class Model def initialize(hash={}) @attributes = hash end def read_attribute_for_serialization(name) @attributes[name] end def method_missing(meth, *args) if meth.to_s =~ /^(.*)=$/ @attributes[$1.to_sym] = args[0] elsif @attributes.key?(meth) @attributes[meth] else super end end end def setup @author = Author.new(name: 'Steve K.') @author.bio = nil @author.roles = [] @blog = Blog.new({ name: 'AMS Blog' }) @post = Post.new({ title: 'New Post', body: 'Body' }) @tag = Tag.new({name: '#hashtagged'}) @comment = Comment.new({ id: 1, body: 'ZOMG A COMMENT' }) @post.comments = [@comment] @post.tags = [@tag] @post.blog = @blog @comment.post = @post @comment.author = nil @post.author = @author @author.posts = [@post] @post_serializer = PostSerializer.new(@post, {custom_options: true}) @author_serializer = AuthorSerializer.new(@author) @comment_serializer = CommentSerializer.new(@comment) end def test_has_many_and_has_one assert_equal( { posts: { type: :has_many, association_options: { embed: :ids } }, roles: { type: :has_many, association_options: { embed: :ids } }, bio: { type: :has_one, association_options: {} } }, @author_serializer.class._associations ) @author_serializer.each_association do |name, serializer, options| if name == :posts assert_equal({embed: :ids}, options) assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer) elsif name == :bio assert_equal({}, options) assert_nil serializer elsif name == :roles assert_equal({embed: :ids}, options) assert_kind_of(ActiveModel::Serializer.config.array_serializer, serializer) else flunk "Unknown association: #{name}" end end end def test_has_many_with_no_serializer PostWithTagsSerializer.new(@post).each_association do |name, serializer, options| assert_equal name, :tags assert_equal serializer, nil assert_equal [{ attributes: { name: "#hashtagged" }}].to_json, options[:virtual_value].to_json end end def test_serializer_options_are_passed_into_associations_serializers @post_serializer.each_association do |name, association| if name == :comments assert association.first.custom_options[:custom_options] end end end def test_belongs_to assert_equal( { post: { type: :belongs_to, association_options: {} }, author: { type: :belongs_to, association_options: {} } }, @comment_serializer.class._associations ) @comment_serializer.each_association do |name, serializer, options| if name == :post assert_equal({}, options) assert_kind_of(PostSerializer, serializer) elsif name == :author assert_equal({}, options) assert_nil serializer else flunk "Unknown association: #{name}" end end end def test_belongs_to_with_custom_method blog_is_present = false @post_serializer.each_association do |name, serializer, options| blog_is_present = true if name == :blog end assert blog_is_present end def test_associations_inheritance inherited_klass = Class.new(PostSerializer) assert_equal(PostSerializer._associations, inherited_klass._associations) end def test_associations_inheritance_with_new_association inherited_klass = Class.new(PostSerializer) do has_many :top_comments, serializer: CommentSerializer end expected_associations = PostSerializer._associations.merge( top_comments: { type: :has_many, association_options: { serializer: CommentSerializer } } ) assert_equal(inherited_klass._associations, expected_associations) end end end end
{ "content_hash": "3d9166e85cbf8f6451b8802c8352a017", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 104, "avg_line_length": 32.76642335766423, "alnum_prop": 0.572287814658053, "repo_name": "Rodrigora/active_model_serializers", "id": "04681d2c4916380b57e68b61637ce34abe78fed1", "size": "4489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/serializers/associations_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "125426" } ], "symlink_target": "" }
.class Lcom/android/internal/os/BatteryStatsImpl$TimeBase; .super Ljava/lang/Object; .source "BatteryStatsImpl.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/internal/os/BatteryStatsImpl; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x8 name = "TimeBase" .end annotation # instance fields .field private final mObservers:Ljava/util/ArrayList; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/ArrayList", "<", "Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs;", ">;" } .end annotation .end field .field private mPastRealtime:J .field private mPastUptime:J .field private mRealtime:J .field private mRealtimeStart:J .field private mRunning:Z .field private mUnpluggedRealtime:J .field private mUnpluggedUptime:J .field private mUptime:J .field private mUptimeStart:J # direct methods .method constructor <init>()V .locals 1 .prologue .line 509 invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 510 new-instance v0, Ljava/util/ArrayList; invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V iput-object v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; .line 509 return-void .end method # virtual methods .method public add(Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs;)V .locals 1 .param p1, "observer" # Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs; .prologue .line 554 iget-object v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z .line 553 return-void .end method .method public computeRealtime(JI)J .locals 5 .param p1, "curTime" # J .param p3, "which" # I .prologue .line 599 packed-switch p3, :pswitch_data_0 .line 607 const-wide/16 v0, 0x0 return-wide v0 .line 601 :pswitch_0 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v2 add-long/2addr v0, v2 return-wide v0 .line 603 :pswitch_1 invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v0 return-wide v0 .line 605 :pswitch_2 invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v0 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J sub-long/2addr v0, v2 return-wide v0 .line 599 nop :pswitch_data_0 .packed-switch 0x0 :pswitch_0 :pswitch_1 :pswitch_2 .end packed-switch .end method .method public computeUptime(JI)J .locals 5 .param p1, "curTime" # J .param p3, "which" # I .prologue .line 587 packed-switch p3, :pswitch_data_0 .line 595 const-wide/16 v0, 0x0 return-wide v0 .line 589 :pswitch_0 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v2 add-long/2addr v0, v2 return-wide v0 .line 591 :pswitch_1 invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v0 return-wide v0 .line 593 :pswitch_2 invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v0 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J sub-long/2addr v0, v2 return-wide v0 .line 587 nop :pswitch_data_0 .packed-switch 0x0 :pswitch_0 :pswitch_1 :pswitch_2 .end packed-switch .end method .method public dump(Ljava/io/PrintWriter;Ljava/lang/String;)V .locals 7 .param p1, "pw" # Ljava/io/PrintWriter; .param p2, "prefix" # Ljava/lang/String; .prologue const/4 v6, 0x0 const-wide/16 v4, 0x3e8 .line 525 new-instance v0, Ljava/lang/StringBuilder; const/16 v1, 0x80 invoke-direct {v0, v1}, Ljava/lang/StringBuilder;-><init>(I)V .line 526 .local v0, "sb":Ljava/lang/StringBuilder; invoke-virtual {p1, p2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V const-string/jumbo v1, "mRunning=" invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V iget-boolean v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Z)V .line 527 invoke-virtual {v0, v6}, Ljava/lang/StringBuilder;->setLength(I)V .line 528 invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 529 const-string/jumbo v1, "mUptime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 530 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 531 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V .line 532 invoke-virtual {v0, v6}, Ljava/lang/StringBuilder;->setLength(I)V .line 533 invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 534 const-string/jumbo v1, "mRealtime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 535 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 536 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V .line 537 invoke-virtual {v0, v6}, Ljava/lang/StringBuilder;->setLength(I)V .line 538 invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 539 const-string/jumbo v1, "mPastUptime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 540 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V const-string/jumbo v1, "mUptimeStart=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 541 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 542 const-string/jumbo v1, "mUnpluggedUptime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 543 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V .line 544 invoke-virtual {v0, v6}, Ljava/lang/StringBuilder;->setLength(I)V .line 545 invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 546 const-string/jumbo v1, "mPastRealtime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 547 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V const-string/jumbo v1, "mRealtimeStart=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; .line 548 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 549 const-string/jumbo v1, "mUnpluggedRealtime=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J div-long/2addr v2, v4 invoke-static {v0, v2, v3}, Lcom/android/internal/os/BatteryStatsImpl;->formatTimeMs(Ljava/lang/StringBuilder;J)V .line 550 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V .line 524 return-void .end method .method public getRealtime(J)J .locals 5 .param p1, "curTime" # J .prologue .line 619 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J .line 620 .local v0, "time":J iget-boolean v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z if-eqz v2, :cond_0 .line 621 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J sub-long v2, p1, v2 add-long/2addr v0, v2 .line 623 :cond_0 return-wide v0 .end method .method public getRealtimeStart()J .locals 2 .prologue .line 631 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J return-wide v0 .end method .method public getUptime(J)J .locals 5 .param p1, "curTime" # J .prologue .line 611 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J .line 612 .local v0, "time":J iget-boolean v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z if-eqz v2, :cond_0 .line 613 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J sub-long v2, p1, v2 add-long/2addr v0, v2 .line 615 :cond_0 return-wide v0 .end method .method public getUptimeStart()J .locals 2 .prologue .line 627 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J return-wide v0 .end method .method public init(JJ)V .locals 3 .param p1, "uptime" # J .param p3, "realtime" # J .prologue const-wide/16 v0, 0x0 .line 564 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J .line 565 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J .line 566 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J .line 567 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J .line 568 iput-wide p1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J .line 569 iput-wide p3, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J .line 570 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J invoke-virtual {p0, v0, v1}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J .line 571 iget-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J invoke-virtual {p0, v0, v1}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J .line 563 return-void .end method .method public isRunning()Z .locals 1 .prologue .line 635 iget-boolean v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z return v0 .end method .method public readFromParcel(Landroid/os/Parcel;)V .locals 2 .param p1, "in" # Landroid/os/Parcel; .prologue .line 677 const/4 v0, 0x0 iput-boolean v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z .line 678 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J .line 679 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J .line 680 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J .line 681 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J .line 682 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J .line 683 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J .line 684 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J .line 685 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J .line 676 return-void .end method .method public readSummaryFromParcel(Landroid/os/Parcel;)V .locals 2 .param p1, "in" # Landroid/os/Parcel; .prologue .line 667 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J .line 668 invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J .line 666 return-void .end method .method public remove(Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs;)V .locals 3 .param p1, "observer" # Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs; .prologue .line 558 iget-object v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v0, p1}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z move-result v0 if-nez v0, :cond_0 .line 559 const-string/jumbo v0, "BatteryStatsImpl" new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "Removed unknown observer: " invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Slog;->wtf(Ljava/lang/String;Ljava/lang/String;)I .line 557 :cond_0 return-void .end method .method public reset(JJ)V .locals 5 .param p1, "uptime" # J .param p3, "realtime" # J .prologue const-wide/16 v2, 0x0 .line 575 iget-boolean v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z if-nez v0, :cond_0 .line 576 iput-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J .line 577 iput-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J .line 574 :goto_0 return-void .line 579 :cond_0 iput-wide p1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J .line 580 iput-wide p3, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J .line 581 invoke-virtual {p0, p1, p2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J .line 582 invoke-virtual {p0, p3, p4}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v0 iput-wide v0, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J goto :goto_0 .end method .method public setRunning(ZJJ)Z .locals 10 .param p1, "running" # Z .param p2, "uptime" # J .param p4, "realtime" # J .prologue const/4 v2, 0x0 .line 639 iget-boolean v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z if-eq v1, p1, :cond_2 .line 640 iput-boolean p1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRunning:Z .line 641 if-eqz p1, :cond_0 .line 642 iput-wide p2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J .line 643 iput-wide p4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J .line 644 invoke-virtual {p0, p2, p3}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v4 iput-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J .line 645 .local v4, "batteryUptime":J invoke-virtual {p0, p4, p5}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v6 iput-wide v6, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J .line 647 .local v6, "batteryRealtime":J iget-object v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v1}, Ljava/util/ArrayList;->size()I move-result v1 add-int/lit8 v0, v1, -0x1 .local v0, "i":I :goto_0 if-ltz v0, :cond_1 .line 648 iget-object v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v1, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object; move-result-object v1 check-cast v1, Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs; move-wide v2, p4 invoke-interface/range {v1 .. v7}, Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs;->onTimeStarted(JJJ)V .line 647 add-int/lit8 v0, v0, -0x1 goto :goto_0 .line 651 .end local v0 # "i":I .end local v4 # "batteryUptime":J .end local v6 # "batteryRealtime":J :cond_0 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J iget-wide v8, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J sub-long v8, p2, v8 add-long/2addr v2, v8 iput-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastUptime:J .line 652 iget-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J iget-wide v8, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J sub-long v8, p4, v8 add-long/2addr v2, v8 iput-wide v2, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mPastRealtime:J .line 654 invoke-virtual {p0, p2, p3}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v4 .line 655 .restart local v4 # "batteryUptime":J invoke-virtual {p0, p4, p5}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v6 .line 657 .restart local v6 # "batteryRealtime":J iget-object v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v1}, Ljava/util/ArrayList;->size()I move-result v1 add-int/lit8 v0, v1, -0x1 .restart local v0 # "i":I :goto_1 if-ltz v0, :cond_1 .line 658 iget-object v1, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mObservers:Ljava/util/ArrayList; invoke-virtual {v1, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object; move-result-object v1 check-cast v1, Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs; move-wide v2, p4 invoke-interface/range {v1 .. v7}, Lcom/android/internal/os/BatteryStatsImpl$TimeBaseObs;->onTimeStopped(JJJ)V .line 657 add-int/lit8 v0, v0, -0x1 goto :goto_1 .line 661 :cond_1 const/4 v1, 0x1 return v1 .line 663 .end local v0 # "i":I .end local v4 # "batteryUptime":J .end local v6 # "batteryRealtime":J :cond_2 return v2 .end method .method public writeSummaryToParcel(Landroid/os/Parcel;JJ)V .locals 4 .param p1, "out" # Landroid/os/Parcel; .param p2, "uptime" # J .param p4, "realtime" # J .prologue const/4 v2, 0x0 .line 672 invoke-virtual {p0, p2, p3, v2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->computeUptime(JI)J move-result-wide v0 invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V .line 673 invoke-virtual {p0, p4, p5, v2}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->computeRealtime(JI)J move-result-wide v0 invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V .line 671 return-void .end method .method public writeToParcel(Landroid/os/Parcel;JJ)V .locals 6 .param p1, "out" # Landroid/os/Parcel; .param p2, "uptime" # J .param p4, "realtime" # J .prologue .line 689 invoke-virtual {p0, p2, p3}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getUptime(J)J move-result-wide v2 .line 690 .local v2, "runningUptime":J invoke-virtual {p0, p4, p5}, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->getRealtime(J)J move-result-wide v0 .line 691 .local v0, "runningRealtime":J iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptime:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 692 invoke-virtual {p1, v2, v3}, Landroid/os/Parcel;->writeLong(J)V .line 693 iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUptimeStart:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 694 iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtime:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 695 invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V .line 696 iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mRealtimeStart:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 697 iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedUptime:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 698 iget-wide v4, p0, Lcom/android/internal/os/BatteryStatsImpl$TimeBase;->mUnpluggedRealtime:J invoke-virtual {p1, v4, v5}, Landroid/os/Parcel;->writeLong(J)V .line 688 return-void .end method
{ "content_hash": "f96c524d3cf444723cb88a37894bcf3d", "timestamp": "", "source": "github", "line_count": 926, "max_line_length": 117, "avg_line_length": 26.65766738660907, "alnum_prop": 0.6920397002228074, "repo_name": "libnijunior/patchrom_bullhead", "id": "53940f8bb77d025e25a4e0b17bdb22dcaeefdc52", "size": "24685", "binary": false, "copies": "2", "ref": "refs/heads/mtc20k", "path": "framework.jar.out/smali/com/android/internal/os/BatteryStatsImpl$TimeBase.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3334" }, { "name": "Groff", "bytes": "8687" }, { "name": "Makefile", "bytes": "2098" }, { "name": "Shell", "bytes": "26769" }, { "name": "Smali", "bytes": "172301453" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Section 23</title> <meta id="xcode-display" name="xcode-display" content="render"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="viewport" content="width=device-width, maximum-scale=1.0"> <link rel="stylesheet" type="text/css" href="stylesheet.css"> </head> <body> <div class="content-wrapper"> <section class="section"> <p>This uses a very similar technique to the one above that collected names. And just like before, there&#39;s a better way to do it. </p> </section> </div> </body> </html>
{ "content_hash": "e7b542c502492317f3309ae10a256d7f", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 142, "avg_line_length": 31.473684210526315, "alnum_prop": 0.68561872909699, "repo_name": "ashfurrow/NSSpain2014", "id": "995d8d54416e0ec18ac72eb6aaa707645e1d8ca1", "size": "598", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Playground.playground/Documentation/section-22.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "266" }, { "name": "Swift", "bytes": "4362" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/appwidget_layout" android:minHeight="180dp" android:minWidth="100dp" android:updatePeriodMillis="45000"> </appwidget-provider>
{ "content_hash": "a4a9909abcb7886a788400e3e3287938", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 78, "avg_line_length": 32.55555555555556, "alnum_prop": 0.7372013651877133, "repo_name": "topsecretabc/GraduationProject", "id": "157a8740dd483cbca0702e16fcfba4e4c893805e", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/xml/appwidget.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "428561" } ], "symlink_target": "" }
GitHub Auto Deployer ==================== This is a simple program to perform deploys on web hooks. It has the following redeeming features: - Single self contained binary - easy to deploy. - Supports GitHub HMAC authentication to validate incoming requests. Deploying --------- - Drop the binary somewhere useful, lets say `/usr/local/bin` for this guide. - Decide on how to make sure it stays running. This is platform dependent, but upstart, svrun, systemd, SMF and so on are all valid choices. - Generate a secret key. This will be used to authenticate requests from GitHub. - Set configuration through environment variables: - `GAD_LISTEN_ADDRESS`: the address to listen for HTTP requests on - `GAD_DEPLOY_COMMAND`: the command to run when performing deploys - `GAD_GITHUB_SECRET`: the secret generated above, used to authenticate requests from GitHub - Start it up. - Configure GitHub. - Add a WebHook. - Set the "Payload URL" to the address and listen port of the machine to receive the push hooks. - Set the "Secret" to the secret generated above. - Test it; you can see requests and responses under "Recent Deliveries". Example ------- A simple script to correctly start `gad` might then look like this: ```sh cd /srv/www/my-site-to-deploy export GAD_LISTEN_ADDRESS=:8876 export GAD_DEPLOY_COMMAND="git pull" export GAD_GITHUB_SECRET=86486a6c-b488-11e4-9ff9-679075158ddc exec /usr/local/bin/gad ``` Note that we `cd` to the working directory where the deploy command will be run. This would then correspond to the payload URL `http://your-site-address:8876/` and the secret `86486a6c-b488-11e4-9ff9-679075158ddc`. For security reasons, the command is not run through a shell, so wildcards and semicolon separated commands can't be used un `GAD_DEPLOY_COMMAND`. You you need that, create a shell script for the deploy and set this as the deploy command.
{ "content_hash": "6a82269251bb9832450658c299867e7e", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 74, "avg_line_length": 27.728571428571428, "alnum_prop": 0.7320968572900567, "repo_name": "calmh/gad", "id": "d2b147c1aeb7b513bfb2f4041e99859882e85c13", "size": "1941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "3213" } ], "symlink_target": "" }
#include "Button.h" /** 0 = nothing 1 = normal click 2 = dubble click? 3 = hold 4 = "long" hold */ Button::Button(int button_pin) { // pin to use _button_pin = button_pin; // init the button state _last_button_state = BUTTON_STATE_NONE; // timing settings _debounce_ms = 25; // ms debounce period to prevent flickering when pressing or releasing the button _doubleclick_gap_ms = 250; // max ms between clicks for a double click event _hold_time_ms = 2000; // ms hold period: how long to wait for press+hold event _long_hold_time_ms = 4000; // ms long hold period: how long to wait for press+hold event // Button variables init _last_button_value = LOW; // buffered value of the button's previous state _is_dc_waiting = false; // whether we're waiting for a double click (down) _dc_on_up = false; // whether to register a double click on next release, or whether to wait and click _is_single_ok = true; // whether it's OK to do a single click _downtime = -1; // time the button was pressed down _uptime = -1; // time the button was released _ignore_up = false; // whether to ignore the button release because the click+hold was triggered _wait_for_up = false; // when held, whether to wait for the up event _hold_past_event = false; // whether or not the hold event happened already _hold_past_event_long = false; // whether or not the long hold event happened already //timing _prefcheck = 0; } void Button::update() { // get the current timing unsigned long milliseconds = millis(); // presume the last state int button_state = BUTTON_STATE_NONE; // read the current pin value int currentButtonValue = digitalRead(_button_pin); // Button pressed down if (currentButtonValue == HIGH && _last_button_value == LOW && (milliseconds - _uptime) > _debounce_ms) { _downtime = milliseconds; _ignore_up = _hold_past_event_long = _wait_for_up = _hold_past_event = false; _is_single_ok = true; if ((milliseconds-_uptime) < _doubleclick_gap_ms && _dc_on_up == false && _is_dc_waiting == true) { _dc_on_up = true; } else { _dc_on_up = false; } _is_dc_waiting = false; } // Button released check dubble clicks else if (currentButtonValue == LOW && _last_button_value == HIGH && (milliseconds - _downtime) > _debounce_ms) { if (!_ignore_up) { _uptime = milliseconds; if (_dc_on_up == false) { _is_dc_waiting = true; } else { button_state = BUTTON_STATE_DUBBLE_CLICK; _dc_on_up = false; _is_dc_waiting = false; _is_single_ok = false; } } } // Test for normal click event: _doubleclick_gap_ms expired if ( currentButtonValue == LOW && // button now released (milliseconds-_uptime) >= _doubleclick_gap_ms && // not in double-click gap _is_dc_waiting == true && _dc_on_up == false && _is_single_ok == true // all other states ok && button_state != BUTTON_STATE_DUBBLE_CLICK) // and not in double-click state? { button_state = BUTTON_STATE_CLICK; _is_dc_waiting = false; } // Test for hold if ( currentButtonValue == HIGH && (milliseconds - _downtime) >= _hold_time_ms) { // Trigger "normal" hold if (! _hold_past_event) { button_state = BUTTON_STATE_HOLD; _dc_on_up = _is_dc_waiting = false; _wait_for_up = _ignore_up = _hold_past_event = true; } // Trigger "long" hold if ((milliseconds - _downtime) >= _long_hold_time_ms) { if (! _hold_past_event_long) { button_state = BUTTON_STATE_HOLD_LONG; _hold_past_event_long = true; } } } // prefent sending out "NONE" when on "hold" if (currentButtonValue == HIGH && // we are still down button_state != BUTTON_STATE_HOLD && button_state != BUTTON_STATE_HOLD_LONG && (_last_button_state == BUTTON_STATE_HOLD || _last_button_state == BUTTON_STATE_HOLD_LONG )) { button_state = _last_button_state; } _last_button_value = currentButtonValue; _last_button_state = button_state; } int Button::getState() { return _last_button_state; } int Button::getButtonPin() { return _button_pin; }
{ "content_hash": "513bc1246b413b591f831655e0dc0dff", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 124, "avg_line_length": 36.21705426356589, "alnum_prop": 0.5648544520547946, "repo_name": "mielemilos/interactivemap", "id": "83e8004ac4e5bbf0718c3a1f690996f126c0d277", "size": "4672", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "policemap/Button.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "4111" }, { "name": "C++", "bytes": "23732" } ], "symlink_target": "" }
#!/usr/bin/python # Copyright (c) 2014 Wladmir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCCAA (IPv4 little-endian old pnSeeds format) The output will be two data structures with the peers in binary format: static SeedSpec6 pnSeed6_main[]={ ... } static SeedSpec6 pnSeed6_test[]={ ... } These should be pasted into `src/chainparamsseeds.h`. ''' from __future__ import print_function, division from base64 import b32decode from binascii import a2b_hex import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.split('.'))) elif ':' in addr: # IPv6 sub = [[], []] # prefix, suffix x = 0 addr = addr.split(':') for i,comp in enumerate(addr): if comp == '': if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end continue x += 1 # :: skips to suffix assert(x < 2) else: # two bytes per component val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) return bytearray(sub[0] + ([0] * nullbytes) + sub[1]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixed seed nodes for the bitcoin network\n') g.write(' * AUTOGENERATED by share/seeds/generate-seeds.py\n') g.write(' *\n') g.write(' * Each line contains a 16-byte IPv6 address and a port.\n') g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n') g.write(' */\n') with open(os.path.join(indir,'nodes_main.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_main', 9988) g.write('\n') with open(os.path.join(indir,'nodes_test.txt'),'r') as f: process_nodes(g, f, 'pnSeed6_test', 9988) g.write('#endif // BITCOIN_CHAINPARAMSSEEDS_H\n') if __name__ == '__main__': main()
{ "content_hash": "fb50793e24c3a19f465c27305c8d7847", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 98, "avg_line_length": 31.822222222222223, "alnum_prop": 0.5758845437616388, "repo_name": "tropa/axecoin", "id": "5b6b4f7b2c2a9b461d073042582ebf99bbc04496", "size": "4296", "binary": false, "copies": "1", "ref": "refs/heads/master-0.10", "path": "share/seeds/generate-seeds.py", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "7639" }, { "name": "C", "bytes": "320976" }, { "name": "C++", "bytes": "3542102" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "M4", "bytes": "142312" }, { "name": "Makefile", "bytes": "84115" }, { "name": "Objective-C", "bytes": "3283" }, { "name": "Objective-C++", "bytes": "7236" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "221281" }, { "name": "QMake", "bytes": "2019" }, { "name": "Roff", "bytes": "36588" }, { "name": "Shell", "bytes": "44911" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
{ "content_hash": "71e42c189e1e8a0f9f24b00c467dc248", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 88, "avg_line_length": 25.333333333333332, "alnum_prop": 0.6842105263157895, "repo_name": "laiso/iOSSamples", "id": "221e2b47aae710be170beb7fa648d71d9263b44f", "size": "265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SVSShootViewController/SVSShootViewController/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "77855" }, { "name": "Ruby", "bytes": "402" } ], "symlink_target": "" }
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var DocumentationContainer = (function (_super) { __extends(DocumentationContainer, _super); function DocumentationContainer() { var _this = this; if (DocumentationContainer.instance) { return DocumentationContainer.instance; } _this = _super.call(this) || this; _this.IsDefault = true; return _this; } DocumentationContainer.instance = new DocumentationContainer(); return DocumentationContainer; }(SingleViewContainer)); //# sourceMappingURL=DocumentationViewController.js.map
{ "content_hash": "9f03d492c3ec3dcf0f79755e3b01ad30", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 93, "avg_line_length": 42.04, "alnum_prop": 0.6013320647002854, "repo_name": "DNCarroll/mace", "id": "fdf5c78001a6b708732856fc97247e5560744d8a", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mace/TestScripts/DocumentationViewController.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "285" }, { "name": "C#", "bytes": "42884" }, { "name": "CSS", "bytes": "63210" }, { "name": "HTML", "bytes": "118317" }, { "name": "JavaScript", "bytes": "19450" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "1030" }, { "name": "TypeScript", "bytes": "588579" }, { "name": "Vim Snippet", "bytes": "22861" } ], "symlink_target": "" }
package io.reactivesocket.reactivestreams.extensions.internal.publishers; import io.reactivesocket.reactivestreams.extensions.Px; import io.reactivesocket.reactivestreams.extensions.Scheduler; import io.reactivesocket.reactivestreams.extensions.internal.subscribers.CancellableSubscriber; import io.reactivesocket.reactivestreams.extensions.internal.subscribers.Subscribers; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public final class TimeoutPublisher<T> implements Px<T> { @SuppressWarnings("ThrowableInstanceNeverThrown") private static final TimeoutException timeoutException = new TimeoutException() { private static final long serialVersionUID = 6195545973881750858L; @Override public synchronized Throwable fillInStackTrace() { return this; } }; private final Publisher<T> child; private final Scheduler scheduler; private final long timeout; private final TimeUnit unit; public TimeoutPublisher(Publisher<T> child, long timeout, TimeUnit unit, Scheduler scheduler) { this.child = child; this.timeout = timeout; this.unit = unit; this.scheduler = scheduler; } @Override public void subscribe(Subscriber<? super T> subscriber) { Runnable onTimeout = () -> subscriber.onError(timeoutException); CancellableSubscriber<Void> timeoutSub = Subscribers.create(null, null, throwable -> onTimeout.run(), onTimeout, null); Runnable cancelTimeout = () -> timeoutSub.cancel(); Subscriber<T> sourceSub = Subscribers.create(subscription -> subscriber.onSubscribe(subscription), t -> { cancelTimeout.run(); subscriber.onNext(t); }, throwable -> { cancelTimeout.run(); subscriber.onError(throwable); }, () -> { cancelTimeout.run(); subscriber.onComplete(); }, cancelTimeout); child.subscribe(sourceSub); scheduler.timer(timeout, unit).subscribe(timeoutSub); } }
{ "content_hash": "6cd0195d090e4e75e9892dea81242116", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 109, "avg_line_length": 45.725806451612904, "alnum_prop": 0.5350970017636685, "repo_name": "NiteshKant/reactivesocket-java", "id": "160d0250d3ee139246b37718c610445a7ffadd59", "size": "3427", "binary": false, "copies": "1", "ref": "refs/heads/0.5.x", "path": "reactivesocket-publishers/src/main/java/io/reactivesocket/reactivestreams/extensions/internal/publishers/TimeoutPublisher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1180728" }, { "name": "Shell", "bytes": "1136" } ], "symlink_target": "" }
class Projects::JobsController < Projects::ApplicationController include SendFileUpload include ContinueParams before_action :build, except: [:index] before_action :authorize_read_build! before_action :authorize_update_build!, except: [:index, :show, :status, :raw, :trace, :erase] before_action :authorize_erase_build!, only: [:erase] before_action :authorize_use_build_terminal!, only: [:terminal, :terminal_websocket_authorize] before_action :verify_api_request!, only: :terminal_websocket_authorize layout 'project' # rubocop: disable CodeReuse/ActiveRecord def index @scope = params[:scope] @all_builds = project.builds.relevant @builds = @all_builds.order('ci_builds.id DESC') @builds = case @scope when 'pending' @builds.pending.reverse_order when 'running' @builds.running.reverse_order when 'finished' @builds.finished else @builds end @builds = @builds.includes([ { pipeline: :project }, :project, :tags ]) @builds = @builds.page(params[:page]).per(30).without_count end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def show @pipeline = @build.pipeline @builds = @pipeline.builds .order('id DESC') .present(current_user: current_user) respond_to do |format| format.html format.json do Gitlab::PollingInterval.set_header(response, interval: 10_000) render json: BuildSerializer .new(project: @project, current_user: @current_user) .represent(@build, {}, BuildDetailsEntity) end end end # rubocop: enable CodeReuse/ActiveRecord def trace build.trace.read do |stream| respond_to do |format| format.json do result = { id: @build.id, status: @build.status, complete: @build.complete? } if stream.valid? stream.limit state = params[:state].presence trace = stream.html_with_state(state) result.merge!(trace.to_h) end render json: result end end end end def retry return respond_422 unless @build.retryable? build = Ci::Build.retry(@build, current_user) redirect_to build_path(build) end def play return respond_422 unless @build.playable? build = @build.play(current_user) redirect_to build_path(build) end def cancel return respond_422 unless @build.cancelable? @build.cancel if continue_params redirect_to continue_params[:to] else redirect_to builds_project_pipeline_path(@project, @build.pipeline.id) end end def unschedule return respond_422 unless @build.scheduled? @build.unschedule! redirect_to build_path(@build) end def status render json: BuildSerializer .new(project: @project, current_user: @current_user) .represent_status(@build) end def erase if @build.erase(erased_by: current_user) redirect_to project_job_path(project, @build), notice: "Job has been successfully erased!" else respond_422 end end def raw if trace_artifact_file workhorse_set_content_type! send_upload(trace_artifact_file, send_params: raw_send_params, redirect_params: raw_redirect_params) else build.trace.read do |stream| if stream.file? workhorse_set_content_type! send_file stream.path, type: 'text/plain; charset=utf-8', disposition: 'inline' else # In this case we can't use workhorse_set_content_type! and let # Workhorse handle the response because the data is streamed directly # to the user but, because we have the trace content, we can calculate # the proper content type and disposition here. raw_data = stream.raw send_data raw_data, type: 'text/plain; charset=utf-8', disposition: raw_trace_content_disposition(raw_data), filename: 'job.log' end end end end def terminal end # GET .../terminal.ws : implemented in gitlab-workhorse def terminal_websocket_authorize set_workhorse_internal_api_content_type render json: Gitlab::Workhorse.terminal_websocket(@build.terminal_specification) end private def authorize_update_build! return access_denied! unless can?(current_user, :update_build, build) end def authorize_erase_build! return access_denied! unless can?(current_user, :erase_build, build) end def authorize_use_build_terminal! return access_denied! unless can?(current_user, :create_build_terminal, build) end def verify_api_request! Gitlab::Workhorse.verify_api_request!(request.headers) end def raw_send_params { type: 'text/plain; charset=utf-8', disposition: 'inline' } end def raw_redirect_params { query: { 'response-content-type' => 'text/plain; charset=utf-8', 'response-content-disposition' => 'inline' } } end def trace_artifact_file @trace_artifact_file ||= build.job_artifacts_trace&.file end def build @build ||= project.builds.find(params[:id]) .present(current_user: current_user) end def build_path(build) project_job_path(build.project, build) end def raw_trace_content_disposition(raw_data) mime_type = MimeMagic.by_magic(raw_data) # if mime_type is nil can also represent 'text/plain' return 'inline' if mime_type.nil? || mime_type.type == 'text/plain' 'attachment' end end
{ "content_hash": "844ffd823be3508cd8ec6dde54f401b3", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 138, "avg_line_length": 26.96153846153846, "alnum_prop": 0.6524607703281027, "repo_name": "axilleas/gitlabhq", "id": "d5ce790e2d94c9c956424a6ba90df268ee9b20a1", "size": "5639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/projects/jobs_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "683690" }, { "name": "Clojure", "bytes": "79" }, { "name": "Dockerfile", "bytes": "1907" }, { "name": "HTML", "bytes": "1340167" }, { "name": "JavaScript", "bytes": "4309733" }, { "name": "Ruby", "bytes": "19732082" }, { "name": "Shell", "bytes": "44575" }, { "name": "Vue", "bytes": "1040466" } ], "symlink_target": "" }
<!-- Contact Section --> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2>Contact Me</h2> <hr> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <form action="//formspree.io/you@email.com" method="POST" name="sentMessage" id="contactForm" novalidate> <div class="row control-group"> <div class="form-group col-xs-12 floating-label-form-group controls"> <label>Name</label> <input type="text" name="name" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name."> <p class="help-block text-danger"></p> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12 floating-label-form-group controls"> <label>Email Address</label> <input type="email" name="_replyto" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> </div> <div> <input type="hidden" name="_subject" value="New submission!"> <input type="text" name="_gotcha" style="display:none" /> </div> <div class="row control-group"> <div class="form-group col-xs-12 floating-label-form-group controls"> <label>Message</label> <textarea rows="5" name="message" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> <br> <div id="success"></div> <div class="row"> <div class="form-group col-xs-12"> <button type="submit" class="btn btn-success btn-lg">Send</button> </div> </div> </form> </div> </div> </div> </section>
{ "content_hash": "d468f88b1434ceedac84081e4b2a94eb", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 180, "avg_line_length": 39.30612244897959, "alnum_prop": 0.6214953271028038, "repo_name": "mbiondis/mbiondis.github.io", "id": "29a524f6b6cf31153e422b91202f9fc1777b0697", "size": "1926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/contact_static.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9301" }, { "name": "HTML", "bytes": "15016" }, { "name": "JavaScript", "bytes": "43724" } ], "symlink_target": "" }
package com.hellhounds.battlefree.game.abilities; import com.hellhounds.battlefree.game.effects.CrushEffect; import com.hellhounds.battlefree.game.effects.DamageEffect; public class GolemAbility extends Ability { public GolemAbility() { super("Golem Smash", new Payment(0, 1, 1, 0), new CrushEffect(20, false, false) , new DamageEffect(10, false, false)); } }
{ "content_hash": "b09728194e1abb81a83299ceadbc033c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 88, "avg_line_length": 30.46153846153846, "alnum_prop": 0.7146464646464646, "repo_name": "pnenad/hellhounds", "id": "b9c494d59ad66e00d670fd331af1efe587452b3c", "size": "1063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/hellhounds/battlefree/game/abilities/GolemAbility.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "182600" }, { "name": "Makefile", "bytes": "378" } ], "symlink_target": "" }
 /** * parser - jQuery EasyUI * */ (function($){ $.easyui = { /** * Get the index of array item, return -1 when the item is not found. */ indexOfArray: function(a, o, id){ for(var i=0,len=a.length; i<len; i++){ if (id == undefined){ if (a[i] == o){return i;} } else { if (a[i][o] == id){return i;} } } return -1; }, /** * Remove array item, 'o' parameter can be item object or id field name. * When 'o' parameter is the id field name, the 'id' parameter is valid. */ removeArrayItem: function(a, o, id){ if (typeof o == 'string'){ for(var i=0,len=a.length; i<len; i++){ if (a[i][o] == id){ a.splice(i, 1); return; } } } else { var index = this.indexOfArray(a,o); if (index != -1){ a.splice(index, 1); } } }, /** * Add un-duplicate array item, 'o' parameter is the id field name, if the 'r' object is exists, deny the action. */ addArrayItem: function(a, o, r){ var index = this.indexOfArray(a, o, r ? r[o] : undefined); if (index == -1){ a.push(r ? r : o); } else { a[index] = r ? r : o; } }, getArrayItem: function(a, o, id){ var index = this.indexOfArray(a, o, id); return index==-1 ? null : a[index]; }, forEach: function(data, deep, callback){ var nodes = []; for(var i=0; i<data.length; i++){ nodes.push(data[i]); } while(nodes.length){ var node = nodes.shift(); if (callback(node) == false){return;} if (deep && node.children){ for(var i=node.children.length-1; i>=0; i--){ nodes.unshift(node.children[i]); } } } } }; $.parser = { auto: true, onComplete: function(context){}, plugins:['draggable','droppable','resizable','pagination','tooltip', 'linkbutton','menu','menubutton','splitbutton','switchbutton','progressbar', 'tree','textbox','passwordbox','filebox','combo','combobox','combotree','combogrid','combotreegrid','numberbox','validatebox','searchbox', 'spinner','numberspinner','timespinner','datetimespinner','calendar','datebox','datetimebox','slider', 'layout','panel','datagrid','propertygrid','treegrid','datalist','tabs','accordion','window','dialog','form' ], parse: function(context){ var aa = []; for(var i=0; i<$.parser.plugins.length; i++){ var name = $.parser.plugins[i]; var r = $('.easyui-' + name, context); if (r.length){ if (r[name]){ r.each(function(){ $(this)[name]($.data(this, 'options')||{}); }); } else { aa.push({name:name,jq:r}); } } } if (aa.length && window.easyloader){ var names = []; for(var i=0; i<aa.length; i++){ names.push(aa[i].name); } easyloader.load(names, function(){ for(var i=0; i<aa.length; i++){ var name = aa[i].name; var jq = aa[i].jq; jq.each(function(){ $(this)[name]($.data(this, 'options')||{}); }); } $.parser.onComplete.call($.parser, context); }); } else { $.parser.onComplete.call($.parser, context); } }, parseValue: function(property, value, parent, delta){ delta = delta || 0; var v = $.trim(String(value||'')); var endchar = v.substr(v.length-1, 1); if (endchar == '%'){ v = parseInt(v.substr(0, v.length-1)); if (property.toLowerCase().indexOf('width') >= 0){ v = Math.floor((parent.width()-delta) * v / 100.0); } else { v = Math.floor((parent.height()-delta) * v / 100.0); } } else { v = parseInt(v) || undefined; } return v; }, /** * parse options, including standard 'data-options' attribute. * * calling examples: * $.parser.parseOptions(target); * $.parser.parseOptions(target, ['id','title','width',{fit:'boolean',border:'boolean'},{min:'number'}]); */ parseOptions: function(target, properties){ var t = $(target); var options = {}; var s = $.trim(t.attr('data-options')); if (s){ if (s.substring(0, 1) != '{'){ s = '{' + s + '}'; } options = (new Function('return ' + s))(); } $.map(['width','height','left','top','minWidth','maxWidth','minHeight','maxHeight'], function(p){ var pv = $.trim(target.style[p] || ''); if (pv){ if (pv.indexOf('%') == -1){ pv = parseInt(pv); if (isNaN(pv)){ pv = undefined; } } options[p] = pv; } }); if (properties){ var opts = {}; for(var i=0; i<properties.length; i++){ var pp = properties[i]; if (typeof pp == 'string'){ opts[pp] = t.attr(pp); } else { for(var name in pp){ var type = pp[name]; if (type == 'boolean'){ opts[name] = t.attr(name) ? (t.attr(name) == 'true') : undefined; } else if (type == 'number'){ opts[name] = t.attr(name)=='0' ? 0 : parseFloat(t.attr(name)) || undefined; } } } } $.extend(options, opts); } return options; } }; $(function(){ var d = $('<div style="position:absolute;top:-1000px;width:100px;height:100px;padding:5px"></div>').appendTo('body'); $._boxModel = d.outerWidth()!=100; d.remove(); d = $('<div style="position:fixed"></div>').appendTo('body'); $._positionFixed = (d.css('position') == 'fixed'); d.remove(); if (!window.easyloader && $.parser.auto){ $.parser.parse(); } }); /** * extend plugin to set box model width */ $.fn._outerWidth = function(width){ if (width == undefined){ if (this[0] == window){ return this.width() || document.body.clientWidth; } return this.outerWidth()||0; } return this._size('width', width); }; /** * extend plugin to set box model height */ $.fn._outerHeight = function(height){ if (height == undefined){ if (this[0] == window){ return this.height() || document.body.clientHeight; } return this.outerHeight()||0; } return this._size('height', height); }; $.fn._scrollLeft = function(left){ if (left == undefined){ return this.scrollLeft(); } else { return this.each(function(){$(this).scrollLeft(left)}); } }; $.fn._propAttr = $.fn.prop || $.fn.attr; $.fn._size = function(options, parent){ if (typeof options == 'string'){ if (options == 'clear'){ return this.each(function(){ $(this).css({width:'',minWidth:'',maxWidth:'',height:'',minHeight:'',maxHeight:''}); }); } else if (options == 'fit'){ return this.each(function(){ _fit(this, this.tagName=='BODY' ? $('body') : $(this).parent(), true); }); } else if (options == 'unfit'){ return this.each(function(){ _fit(this, $(this).parent(), false); }); } else { if (parent == undefined){ return _css(this[0], options); } else { return this.each(function(){ _css(this, options, parent); }); } } } else { return this.each(function(){ parent = parent || $(this).parent(); $.extend(options, _fit(this, parent, options.fit)||{}); var r1 = _setSize(this, 'width', parent, options); var r2 = _setSize(this, 'height', parent, options); if (r1 || r2){ $(this).addClass('easyui-fluid'); } else { $(this).removeClass('easyui-fluid'); } }); } function _fit(target, parent, fit){ if (!parent.length){return false;} var t = $(target)[0]; var p = parent[0]; var fcount = p.fcount || 0; if (fit){ if (!t.fitted){ t.fitted = true; p.fcount = fcount + 1; $(p).addClass('panel-noscroll'); if (p.tagName == 'BODY'){ $('html').addClass('panel-fit'); } } return { width: ($(p).width()||1), height: ($(p).height()||1) }; } else { if (t.fitted){ t.fitted = false; p.fcount = fcount - 1; if (p.fcount == 0){ $(p).removeClass('panel-noscroll'); if (p.tagName == 'BODY'){ $('html').removeClass('panel-fit'); } } } return false; } } function _setSize(target, property, parent, options){ var t = $(target); var p = property; var p1 = p.substr(0,1).toUpperCase() + p.substr(1); var min = $.parser.parseValue('min'+p1, options['min'+p1], parent);// || 0; var max = $.parser.parseValue('max'+p1, options['max'+p1], parent);// || 99999; var val = $.parser.parseValue(p, options[p], parent); var fluid = (String(options[p]||'').indexOf('%') >= 0 ? true : false); if (!isNaN(val)){ var v = Math.min(Math.max(val, min||0), max||99999); if (!fluid){ options[p] = v; } t._size('min'+p1, ''); t._size('max'+p1, ''); t._size(p, v); } else { t._size(p, ''); t._size('min'+p1, min); t._size('max'+p1, max); } return fluid || options.fit; } function _css(target, property, value){ var t = $(target); if (value == undefined){ value = parseInt(target.style[property]); if (isNaN(value)){return undefined;} if ($._boxModel){ value += getDeltaSize(); } return value; } else if (value === ''){ t.css(property, ''); } else { if ($._boxModel){ value -= getDeltaSize(); if (value < 0){value = 0;} } t.css(property, value+'px'); } function getDeltaSize(){ if (property.toLowerCase().indexOf('width') >= 0){ return t.outerWidth() - t.width(); } else { return t.outerHeight() - t.height(); } } } }; })(jQuery); /** * support for mobile devices */ (function($){ var longTouchTimer = null; var dblTouchTimer = null; var isDblClick = false; function onTouchStart(e){ if (e.touches.length != 1){return} if (!isDblClick){ isDblClick = true; dblClickTimer = setTimeout(function(){ isDblClick = false; }, 500); } else { clearTimeout(dblClickTimer); isDblClick = false; fire(e, 'dblclick'); // e.preventDefault(); } longTouchTimer = setTimeout(function(){ fire(e, 'contextmenu', 3); }, 1000); fire(e, 'mousedown'); if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){ e.preventDefault(); } } function onTouchMove(e){ if (e.touches.length != 1){return} if (longTouchTimer){ clearTimeout(longTouchTimer); } fire(e, 'mousemove'); if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){ e.preventDefault(); } } function onTouchEnd(e){ // if (e.touches.length > 0){return} if (longTouchTimer){ clearTimeout(longTouchTimer); } fire(e, 'mouseup'); if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){ e.preventDefault(); } } function fire(e, name, which){ var event = new $.Event(name); event.pageX = e.changedTouches[0].pageX; event.pageY = e.changedTouches[0].pageY; event.which = which || 1; $(e.target).trigger(event); } if (document.addEventListener){ document.addEventListener("touchstart", onTouchStart, true); document.addEventListener("touchmove", onTouchMove, true); document.addEventListener("touchend", onTouchEnd, true); } })(jQuery);
{ "content_hash": "9d88944980e5e3c0a607e1a2bd2c1dc1", "timestamp": "", "source": "github", "line_count": 423, "max_line_length": 143, "avg_line_length": 26.829787234042552, "alnum_prop": 0.5334390695215437, "repo_name": "nemozhang1987/justfaq", "id": "bbf0cf1687caeeb9e5d26cd9a3b53367bdb34599", "size": "11610", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "js/jquery-easyui-1/src/jquery.parser.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "600058" }, { "name": "HTML", "bytes": "579953" }, { "name": "Hack", "bytes": "3702" }, { "name": "JavaScript", "bytes": "602897" }, { "name": "PHP", "bytes": "559410" } ], "symlink_target": "" }
function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } __export(require("./debug-common")); var ScopeError = (function (_super) { __extends(ScopeError, _super); function ScopeError(inner, message) { var formattedMessage; if (message && inner.message) { formattedMessage = message + "\n > " + inner.message.replace("\n", "\n "); } else { formattedMessage = message || inner.message || undefined; } _super.call(this, formattedMessage); this.stack = inner.stack; this.message = formattedMessage; } return ScopeError; }(Error)); exports.ScopeError = ScopeError; var SourceError = (function (_super) { __extends(SourceError, _super); function SourceError(child, source, message) { _super.call(this, child, message ? message + " @" + source + "" : source + ""); } return SourceError; }(ScopeError)); exports.SourceError = SourceError; //# sourceMappingURL=debug.ios.js.map
{ "content_hash": "d4a023b168d1579761457b1ff9a78d26", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 87, "avg_line_length": 34.56666666666667, "alnum_prop": 0.6104146576663452, "repo_name": "Torgo13/CarWashApp", "id": "7f56801969a839791e69d8bdf6653a35449e8e3b", "size": "1037", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/tns-core-modules/utils/debug.ios.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3744100" }, { "name": "C++", "bytes": "2347036" }, { "name": "CSS", "bytes": "74402" }, { "name": "HTML", "bytes": "337549" }, { "name": "Java", "bytes": "55154" }, { "name": "JavaScript", "bytes": "5746507" }, { "name": "Makefile", "bytes": "232734" }, { "name": "Objective-C", "bytes": "561821" }, { "name": "Python", "bytes": "4382" }, { "name": "Ruby", "bytes": "306" }, { "name": "Shell", "bytes": "11851" }, { "name": "TypeScript", "bytes": "1496936" } ], "symlink_target": "" }
var goog = global.atom_vim_keymap.goog; goog.provide('shadow.devtools'); var shadow = goog.getObjectByName('shadow'); shadow.devtools = goog.getObjectByName('shadow.devtools'); var runtime_setup = goog.getObjectByName('runtime_setup'); var cljs = goog.getObjectByName('cljs'); cljs.core = goog.getObjectByName('cljs.core'); cljs.core.async = goog.getObjectByName('cljs.core.async'); var cognitect = goog.getObjectByName('cognitect'); cognitect.transit = goog.getObjectByName('cognitect.transit'); goog.require('cljs.core'); goog.require('cognitect.transit'); goog.require('cljs.core.async'); if(typeof shadow.devtools.custom_handlers !== 'undefined'){ } else { shadow.devtools.custom_handlers = (function (){var G__20013 = cljs.core.PersistentArrayMap.EMPTY; return (cljs.core.atom.cljs$core$IFn$_invoke$arity$1 ? cljs.core.atom.cljs$core$IFn$_invoke$arity$1(G__20013) : cljs.core.atom.call(null,G__20013)); })(); } /** @define {boolean} */ goog.define("shadow.devtools.enabled",false); /** @define {string} */ goog.define("shadow.devtools.url",""); /** @define {string} */ goog.define("shadow.devtools.before_load",""); /** @define {string} */ goog.define("shadow.devtools.after_load",""); /** @define {boolean} */ goog.define("shadow.devtools.node_eval",false); /** @define {boolean} */ goog.define("shadow.devtools.reload_with_state",false); if(typeof shadow.devtools.dump_chan !== 'undefined'){ } else { shadow.devtools.dump_chan = ((shadow.devtools.enabled)?cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(cljs.core.async.sliding_buffer((10))):null); } /** * don't use directly, use dump macro */ shadow.devtools.dump_STAR_ = (function shadow$devtools$dump_STAR_(title,data){ cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(shadow.devtools.dump_chan,cljs.core.pr_str.cljs$core$IFn$_invoke$arity$variadic(cljs.core.array_seq([new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"title","title",636505583),title,new cljs.core.Keyword(null,"id","id",-1388402092),cljs.core.random_uuid(),new cljs.core.Keyword(null,"data","data",-232669377),cljs.core.pr_str.cljs$core$IFn$_invoke$arity$variadic(cljs.core.array_seq([data], 0))], null)], 0))); return null; }); /** * don't use directly, use register! macro */ shadow.devtools.register_STAR_ = (function shadow$devtools$register_STAR_(type,handler){ return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(shadow.devtools.custom_handlers,cljs.core.assoc,type,handler); });//# sourceMappingURL=devtools.js.map?r=0.2843724475440934
{ "content_hash": "30fff5241d71702c3e4fd271256abf87", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 488, "avg_line_length": 45.836363636363636, "alnum_prop": 0.7298690995636652, "repo_name": "madeinqc/atom-vim-keymap", "id": "5b45a3111416697be28575fdff5d396822884dcf", "size": "2521", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "plugin/lib/cljs-runtime/shadow/devtools.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1128" }, { "name": "Clojure", "bytes": "517854" }, { "name": "CoffeeScript", "bytes": "868" }, { "name": "JavaScript", "bytes": "4882325" }, { "name": "Shell", "bytes": "405" } ], "symlink_target": "" }
package com.intellij.find.impl; import com.intellij.CommonBundle; import com.intellij.find.*; import com.intellij.find.actions.ShowUsagesAction; import com.intellij.ide.util.scopeChooser.ScopeChooserCombo; import com.intellij.ide.util.scopeChooser.ScopeDescriptor; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.fileTypes.PlainTextFileType; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.progress.util.ReadTask; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.*; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.projectImport.ProjectAttachProcessor; import com.intellij.psi.PsiBundle; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopeUtil; import com.intellij.psi.search.SearchScope; import com.intellij.ui.*; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.table.JBTable; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewBundle; import com.intellij.usages.*; import com.intellij.usages.impl.UsagePreviewPanel; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class FindDialog extends DialogWrapper implements FindUI { private static final Logger LOG = Logger.getInstance("#com.intellij.find.impl.FindDialog"); private final FindUIHelper myHelper; private ComboBox myInputComboBox; private ComboBox myReplaceComboBox; private StateRestoringCheckBox myCbCaseSensitive; private StateRestoringCheckBox myCbPreserveCase; private StateRestoringCheckBox myCbWholeWordsOnly; private ComboBox mySearchContext; private StateRestoringCheckBox myCbRegularExpressions; private JRadioButton myRbGlobal; private JRadioButton myRbSelectedText; private JRadioButton myRbForward; private JRadioButton myRbBackward; private JRadioButton myRbFromCursor; private JRadioButton myRbEntireScope; private JRadioButton myRbProject; private JRadioButton myRbDirectory; private JRadioButton myRbModule; private ComboBox myModuleComboBox; private ComboBox myDirectoryComboBox; private StateRestoringCheckBox myCbWithSubdirectories; private JCheckBox myCbToOpenInNewTab; private FixedSizeButton mySelectDirectoryButton; private StateRestoringCheckBox myUseFileFilter; private ComboBox myFileFilter; private JCheckBox myCbToSkipResultsWhenOneUsage; private final Project myProject; private final Map<EditorTextField, DocumentListener> myComboBoxListeners = new HashMap<>(); private Action myFindAllAction; private JRadioButton myRbCustomScope; private ScopeChooserCombo myScopeCombo; protected JLabel myReplacePrompt; private HideableTitledPanel myScopePanel; private static boolean myPreviousResultsExpandedState = true; private static boolean myPreviewResultsTabWasSelected; private static final int RESULTS_PREVIEW_TAB_INDEX = 1; private Splitter myPreviewSplitter; private JBTable myResultsPreviewTable; private UsagePreviewPanel myUsagePreviewPanel; private TabbedPane myContent; private Alarm mySearchRescheduleOnCancellationsAlarm; private static final String PREVIEW_TITLE = UIBundle.message("tool.window.name.preview"); private volatile ProgressIndicatorBase myResultsPreviewSearchProgress; public FindDialog(FindUIHelper helper){ super(helper.getProject(), true); myHelper = helper; myProject = myHelper.getProject(); setTitle(myHelper.getTitle()); setOKButtonText(FindBundle.message("find.button")); init(); } @Override public void showUI() { if (haveResultsPreview()) { ApplicationManager.getApplication().invokeLater(this::scheduleResultsUpdate, ModalityState.any()); } show(); } @Override public void doCancelAction() { // doCancel disposes fields and then calls dispose FindSettings.getInstance().setDefaultScopeName(myScopeCombo.getSelectedScopeName()); applyTo(FindManager.getInstance(myProject).getFindInProjectModel(), false); rememberResultsPreviewWasOpen(); super.doCancelAction(); } private void rememberResultsPreviewWasOpen() { if (myResultsPreviewTable != null) { int selectedIndex = myContent.getSelectedIndex(); if (selectedIndex != -1) myPreviewResultsTabWasSelected = selectedIndex == RESULTS_PREVIEW_TAB_INDEX; } } @Override protected void dispose() { finishPreviousPreviewSearch(); if (mySearchRescheduleOnCancellationsAlarm != null) Disposer.dispose(mySearchRescheduleOnCancellationsAlarm); if (myUsagePreviewPanel != null) Disposer.dispose(myUsagePreviewPanel); for(Map.Entry<EditorTextField, DocumentListener> e: myComboBoxListeners.entrySet()) { e.getKey().removeDocumentListener(e.getValue()); } myComboBoxListeners.clear(); if (myScopePanel != null) myPreviousResultsExpandedState = myScopePanel.isExpanded(); super.dispose(); } @Override public JComponent getPreferredFocusedComponent() { return myInputComboBox; } @Override protected String getDimensionServiceKey() { return myHelper.getModel().isReplaceState() ? "replaceTextDialog" : "findTextDialog"; } @NotNull @Override protected Action[] createActions() { FindModel myModel = myHelper.getModel(); if (!myModel.isMultipleFiles() && !myModel.isReplaceState() && myModel.isFindAllEnabled()) { return new Action[] { getFindAllAction(), getOKAction(), getCancelAction(), getHelpAction() }; } return new Action[] { getOKAction(), getCancelAction(), getHelpAction() }; } @NotNull private Action getFindAllAction() { return myFindAllAction = new AbstractAction(FindBundle.message("find.all.button")) { @Override public void actionPerformed(ActionEvent e) { doOKAction(true); } }; } @Override public JComponent createNorthPanel() { JPanel panel = new JPanel(new GridBagLayout()); JLabel prompt = new JLabel(FindBundle.message("find.text.to.find.label")); panel.add(prompt, new GridBagConstraints(0,0,1,1,0,1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,UIUtil.DEFAULT_VGAP,UIUtil.DEFAULT_HGAP), 0,0)); myInputComboBox = new ComboBox(300); revealWhitespaces(myInputComboBox); initCombobox(myInputComboBox); myReplaceComboBox = new ComboBox(300); revealWhitespaces(myReplaceComboBox); initCombobox(myReplaceComboBox); final Component editorComponent = myReplaceComboBox.getEditor().getEditorComponent(); editorComponent.addFocusListener( new FocusAdapter() { @Override public void focusGained(FocusEvent e) { myReplaceComboBox.getEditor().selectAll(); editorComponent.removeFocusListener(this); } } ); panel.add(myInputComboBox, new GridBagConstraints(1,0,1,1,1,1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0,UIUtil.DEFAULT_VGAP,0), 0,0)); prompt.setLabelFor(myInputComboBox.getEditor().getEditorComponent()); myReplacePrompt = new JLabel(FindBundle.message("find.replace.with.label")); panel.add(myReplacePrompt, new GridBagConstraints(0,1,1,1,0,1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,UIUtil.DEFAULT_VGAP,UIUtil.DEFAULT_HGAP), 0,0)); panel.add(myReplaceComboBox, new GridBagConstraints(1, 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, UIUtil.DEFAULT_VGAP, 0), 0, 0)); myReplacePrompt.setLabelFor(myReplaceComboBox.getEditor().getEditorComponent()); return panel; } private void revealWhitespaces(@NotNull ComboBox comboBox) { ComboBoxEditor comboBoxEditor = new RevealingSpaceComboboxEditor(myProject, comboBox); comboBox.setEditor(comboBoxEditor); comboBox.setRenderer(new EditorComboBoxRenderer(comboBoxEditor)); } private void initCombobox(@NotNull final ComboBox comboBox) { comboBox.setEditable(true); comboBox.setMaximumRowCount(8); comboBox.addActionListener(__ -> validateFindButton()); final Component editorComponent = comboBox.getEditor().getEditorComponent(); if (editorComponent instanceof EditorTextField) { final EditorTextField etf = (EditorTextField) editorComponent; DocumentListener listener = new DocumentListener() { @Override public void documentChanged(final DocumentEvent e) { handleComboBoxValueChanged(comboBox); } }; etf.addDocumentListener(listener); myComboBoxListeners.put(etf, listener); } else { if (editorComponent instanceof JTextComponent) { final javax.swing.text.Document document = ((JTextComponent)editorComponent).getDocument(); final DocumentAdapter documentAdapter = new DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { handleAnyComboBoxValueChanged(comboBox); } }; document.addDocumentListener(documentAdapter); Disposer.register(myDisposable, () -> document.removeDocumentListener(documentAdapter)); } else { assert false; } } if (!myHelper.getModel().isReplaceState()) { makeResultsPreviewActionOverride( comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "choosePrevious", () -> { int row = myResultsPreviewTable.getSelectedRow(); if (row > 0) myResultsPreviewTable.setRowSelectionInterval(row - 1, row - 1); TableUtil.scrollSelectionToVisible(myResultsPreviewTable); } ); makeResultsPreviewActionOverride( comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "chooseNext", () -> { int row = myResultsPreviewTable.getSelectedRow(); if (row >= -1 && row + 1 < myResultsPreviewTable.getRowCount()) { myResultsPreviewTable.setRowSelectionInterval(row + 1, row + 1); TableUtil.scrollSelectionToVisible(myResultsPreviewTable); } } ); makeResultsPreviewActionOverride( comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "scrollUp", () -> ScrollingUtil.movePageUp(myResultsPreviewTable) ); makeResultsPreviewActionOverride( comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "scrollDown", () -> ScrollingUtil.movePageDown(myResultsPreviewTable) ); AnAction action = new AnAction() { @Override public void actionPerformed(AnActionEvent e) { if (isResultsPreviewTabActive()) { navigateToSelectedUsage(myResultsPreviewTable); } } }; action.registerCustomShortcutSet(CommonShortcuts.getEditSource(), comboBox, myDisposable); new AnAction() { @Override public void actionPerformed(AnActionEvent e) { if (!isResultsPreviewTabActive() || myResultsPreviewTable.getSelectedRowCount() == 0) doOKAction(); else action.actionPerformed(e); } }.registerCustomShortcutSet(CommonShortcuts.ENTER, comboBox, myDisposable); } } private boolean isResultsPreviewTabActive() { return myResultsPreviewTable != null && myContent.getSelectedIndex() == RESULTS_PREVIEW_TAB_INDEX; } private void makeResultsPreviewActionOverride(final JComboBox component, KeyStroke keyStroke, String newActionKey, final Runnable newAction) { InputMap inputMap = component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); Object action = inputMap.get(keyStroke); inputMap.put(keyStroke, newActionKey); final Action previousAction = action != null ? component.getActionMap().get(action) : null; component.getActionMap().put(newActionKey, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if(isResultsPreviewTabActive() && !component.isPopupVisible()) { newAction.run(); return; } if (previousAction != null) { previousAction.actionPerformed(e); } } }); } private void handleComboBoxValueChanged(@NotNull ComboBox comboBox) { Object item = comboBox.getEditor().getItem(); if (item != null && !item.equals(comboBox.getSelectedItem())){ comboBox.setSelectedItem(item); } handleAnyComboBoxValueChanged(comboBox); } private void handleAnyComboBoxValueChanged(@NotNull ComboBox comboBox) { if (comboBox != myReplaceComboBox) scheduleResultsUpdate(); validateFindButton(); } private void findSettingsChanged() { if (haveResultsPreview()) { final ModalityState state = ModalityState.current(); if (state == ModalityState.NON_MODAL) return; // skip initial changes finishPreviousPreviewSearch(); mySearchRescheduleOnCancellationsAlarm.cancelAllRequests(); final FindModel findModel = myHelper.getModel().clone(); applyTo(findModel, false); ValidationInfo result = getValidationInfo(findModel); final ProgressIndicatorBase progressIndicatorWhenSearchStarted = new ProgressIndicatorBase(); myResultsPreviewSearchProgress = progressIndicatorWhenSearchStarted; final DefaultTableModel model = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } }; // Use previously shown usage files as hint for faster search and better usage preview performance if pattern length increased final LinkedHashSet<VirtualFile> filesToScanInitially = new LinkedHashSet<>(); if (myHelper.myPreviousModel != null && myHelper.myPreviousModel.getStringToFind().length() < findModel.getStringToFind().length()) { final DefaultTableModel previousModel = (DefaultTableModel)myResultsPreviewTable.getModel(); for (int i = 0, len = previousModel.getRowCount(); i < len; ++i) { final UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter)previousModel.getValueAt(i, 0); final VirtualFile file = usage.getFile(); if (file != null) filesToScanInitially.add(file); } } myHelper.myPreviousModel = findModel; model.addColumn("Usages"); myResultsPreviewTable.setModel(model); if (result != null) { myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE); return; } GlobalSearchScope scope = GlobalSearchScopeUtil.toGlobalSearchScope( FindInProjectUtil.getScopeFromModel(myProject, findModel), myProject); myResultsPreviewTable.getColumnModel().getColumn(0).setCellRenderer(new UsageTableCellRenderer(false, true, scope)); myResultsPreviewTable.getEmptyText().setText("Searching..."); myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE); final Component component = myInputComboBox.getEditor().getEditorComponent(); // avoid commit of search text document upon encountering / highlighting of first usage that will restart the search // (UsagePreviewPanel.highlight) if (component instanceof EditorTextField) { final Document document = ((EditorTextField)component).getDocument(); if (document != null) { PsiDocumentManager.getInstance(myProject).commitDocument(document); } } final AtomicInteger resultsCount = new AtomicInteger(); final AtomicInteger resultsFilesCount = new AtomicInteger(); ProgressIndicatorUtils.scheduleWithWriteActionPriority(myResultsPreviewSearchProgress, new ReadTask() { @Nullable @Override public Continuation performInReadAction(@NotNull ProgressIndicator indicator) throws ProcessCanceledException { final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(FindSettings.getInstance().isShowResultsInSeparateView(), findModel); final boolean showPanelIfOnlyOneUsage = !FindSettings.getInstance().isSkipResultsWithOneUsage(); final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation); ThreadLocal<VirtualFile> lastUsageFileRef = new ThreadLocal<>(); FindInProjectUtil.findUsages(findModel, myProject, info -> { if(isCancelled()) { return false; } final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); usage.getPresentation().getIcon(); // cache icon VirtualFile file = lastUsageFileRef.get(); VirtualFile usageFile = info.getVirtualFile(); if (file == null || !file.equals(usageFile)) { resultsFilesCount.incrementAndGet(); lastUsageFileRef.set(usageFile); } ApplicationManager.getApplication().invokeLater(() -> { if (isCancelled()) return; model.addRow(new Object[]{usage}); }, state); return resultsCount.incrementAndGet() < ShowUsagesAction.getUsagesPageSize(); }, processPresentation, filesToScanInitially); boolean succeeded = !progressIndicatorWhenSearchStarted.isCanceled(); if (succeeded) { return new Continuation(() -> { if (!isCancelled()) { int occurrences = resultsCount.get(); int filesWithOccurrences = resultsFilesCount.get(); if (occurrences == 0) myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); boolean foundAllUsages = occurrences < ShowUsagesAction.getUsagesPageSize(); myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE + " (" + (foundAllUsages ? Integer.valueOf(occurrences) : occurrences + "+") + UIBundle.message("message.matches", occurrences) + " in " + (foundAllUsages ? Integer.valueOf(filesWithOccurrences) : filesWithOccurrences + "+") + UIBundle.message("message.files", filesWithOccurrences) + ")"); } }, state); } return null; } boolean isCancelled() { return progressIndicatorWhenSearchStarted != myResultsPreviewSearchProgress || myResultsPreviewSearchProgress.isCanceled(); } @Override public void onCanceled(@NotNull ProgressIndicator indicator) { if (isShowing() && progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress) { scheduleResultsUpdate(); } } }); } } private void scheduleResultsUpdate() { final Alarm alarm = mySearchRescheduleOnCancellationsAlarm; if (alarm == null || alarm.isDisposed()) return; alarm.cancelAllRequests(); alarm.addRequest(() -> TransactionGuard.submitTransaction(myDisposable, this::findSettingsChanged), 100); } private void finishPreviousPreviewSearch() { if (myResultsPreviewSearchProgress != null && !myResultsPreviewSearchProgress.isCanceled()) { myResultsPreviewSearchProgress.cancel(); } } private void validateFindButton() { boolean okStatus = myHelper.canSearchThisString() || myRbDirectory != null && myRbDirectory.isSelected() && StringUtil.isEmpty(getDirectory()); setOKStatus(okStatus); } private void setOKStatus(boolean value) { setOKActionEnabled(value); if (myFindAllAction != null) { myFindAllAction.setEnabled(value); } } @Override public JComponent createCenterPanel() { JPanel optionsPanel = new JPanel(); optionsPanel.setLayout(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.weightx = 1; gbConstraints.weighty = 1; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.gridwidth = GridBagConstraints.REMAINDER; JPanel topOptionsPanel = new JPanel(); topOptionsPanel.setLayout(new GridLayout(1, 2, UIUtil.DEFAULT_HGAP, 0)); topOptionsPanel.add(createFindOptionsPanel()); optionsPanel.add(topOptionsPanel, gbConstraints); JPanel resultsOptionPanel = null; if (myHelper.getModel().isMultipleFiles()) { optionsPanel.add(createGlobalScopePanel(), gbConstraints); gbConstraints.weightx = 1; gbConstraints.weighty = 1; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridwidth = GridBagConstraints.REMAINDER; optionsPanel.add(createFilterPanel(),gbConstraints); myCbToSkipResultsWhenOneUsage = createCheckbox(myHelper.isSkipResultsWithOneUsage(), FindBundle.message("find.options.skip.results.tab.with.one.occurrence.checkbox")); myCbToSkipResultsWhenOneUsage.addActionListener(e -> myHelper.setSkipResultsWithOneUsage(myCbToSkipResultsWhenOneUsage.isSelected())); resultsOptionPanel = createResultsOptionPanel(optionsPanel, gbConstraints); resultsOptionPanel.add(myCbToSkipResultsWhenOneUsage); myCbToSkipResultsWhenOneUsage.setVisible(!myHelper.isReplaceState()); if (haveResultsPreview()) { final JBTable table = new JBTable() { @Override public Dimension getPreferredSize() { return new Dimension(myInputComboBox.getWidth(), super.getPreferredSize().height); } }; table.setShowColumns(false); table.setShowGrid(false); table.setIntercellSpacing(JBUI.emptySize()); new NavigateToSourceListener().installOn(table); Splitter previewSplitter = new Splitter(true, 0.5f, 0.1f, 0.9f); myUsagePreviewPanel = new UsagePreviewPanel(myProject, new UsageViewPresentation(), true); myUsagePreviewPanel.setBorder(IdeBorderFactory.createBorder()); registerNavigateToSourceShortcutOnComponent(table, myUsagePreviewPanel); myResultsPreviewTable = table; new TableSpeedSearch(table, o -> ((UsageInfo2UsageAdapter)o).getFile().getName()); myResultsPreviewTable.getSelectionModel().addListSelectionListener(e -> { if (e.getValueIsAdjusting()) return; int index = myResultsPreviewTable.getSelectionModel().getLeadSelectionIndex(); if (index != -1) { UsageInfo usageInfo = ((UsageInfo2UsageAdapter)myResultsPreviewTable.getModel().getValueAt(index, 0)).getUsageInfo(); myUsagePreviewPanel.updateLayout(usageInfo.isValid() ? Collections.singletonList(usageInfo) : null); VirtualFile file = usageInfo.getVirtualFile(); myUsagePreviewPanel.setBorder(IdeBorderFactory.createTitledBorder(file != null ? file.getPath() : "", false)); } else { myUsagePreviewPanel.updateLayout(null); myUsagePreviewPanel.setBorder(IdeBorderFactory.createBorder()); } }); mySearchRescheduleOnCancellationsAlarm = new Alarm(); previewSplitter.setFirstComponent(new JBScrollPane(myResultsPreviewTable)); previewSplitter.setSecondComponent(myUsagePreviewPanel.createComponent()); myPreviewSplitter = previewSplitter; } } else { JPanel leftOptionsPanel = new JPanel(); leftOptionsPanel.setLayout(new GridLayout(3, 1, 0, 4)); leftOptionsPanel.add(createDirectionPanel()); leftOptionsPanel.add(createOriginPanel()); leftOptionsPanel.add(createScopePanel()); topOptionsPanel.add(leftOptionsPanel); } if (myHelper.getModel().isOpenInNewTabVisible()){ myCbToOpenInNewTab = new JCheckBox(FindBundle.message("find.open.in.new.tab.checkbox")); myCbToOpenInNewTab.setFocusable(false); myCbToOpenInNewTab.setSelected(myHelper.isUseSeparateView()); myCbToOpenInNewTab.setEnabled(myHelper.getModel().isOpenInNewTabEnabled()); myCbToOpenInNewTab.addActionListener(e -> myHelper.setUseSeparateView(myCbToOpenInNewTab.isSelected())); if (resultsOptionPanel == null) resultsOptionPanel = createResultsOptionPanel(optionsPanel, gbConstraints); resultsOptionPanel.add(myCbToOpenInNewTab); } if (myPreviewSplitter != null) { TabbedPane pane = new JBTabsPaneImpl(myProject, SwingConstants.TOP, myDisposable); pane.insertTab("Options", null, optionsPanel, null, 0); pane.insertTab(PREVIEW_TITLE, null, myPreviewSplitter, null, RESULTS_PREVIEW_TAB_INDEX); myContent = pane; AnAction anAction = DumbAwareAction.create(e -> { int selectedIndex = myContent.getSelectedIndex(); myContent.setSelectedIndex(1 - selectedIndex); }); final ShortcutSet shortcutSet = ActionManager.getInstance().getAction(IdeActions.ACTION_SWITCHER).getShortcutSet(); anAction.registerCustomShortcutSet(shortcutSet, getRootPane(), myDisposable); if (myPreviewResultsTabWasSelected) myContent.setSelectedIndex(RESULTS_PREVIEW_TAB_INDEX); return pane.getComponent(); } return optionsPanel; } private boolean haveResultsPreview() { return Registry.is("ide.find.show.preview") && myHelper.getModel().isMultipleFiles(); } private JPanel createResultsOptionPanel(JPanel optionsPanel, GridBagConstraints gbConstraints) { JPanel resultsOptionPanel = new JPanel(); resultsOptionPanel.setLayout(new BoxLayout(resultsOptionPanel, BoxLayout.Y_AXIS)); myScopePanel = new HideableTitledPanel(FindBundle.message("results.options.group"), resultsOptionPanel, myPreviousResultsExpandedState); optionsPanel.add(myScopePanel, gbConstraints); return resultsOptionPanel; } @NotNull private JComponent createFilterPanel() { JPanel filterPanel = new JPanel(); filterPanel.setLayout(new BorderLayout()); filterPanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.filter.file.name.group"), true)); myFileFilter = new ComboBox(100); initCombobox(myFileFilter); filterPanel.add(myUseFileFilter = createCheckbox(FindBundle.message("find.filter.file.mask.checkbox")),BorderLayout.WEST); filterPanel.add(myFileFilter,BorderLayout.CENTER); initFileFilter(myFileFilter, myUseFileFilter); myUseFileFilter.addActionListener(__ -> { scheduleResultsUpdate(); validateFindButton(); }); return filterPanel; } public static void initFileFilter(@NotNull final JComboBox fileFilter, @NotNull final JCheckBox useFileFilter) { fileFilter.setEditable(true); String[] fileMasks = FindSettings.getInstance().getRecentFileMasks(); for(int i=fileMasks.length-1; i >= 0; i--) { fileFilter.addItem(fileMasks[i]); } fileFilter.setEnabled(false); useFileFilter.addActionListener( __ -> { if (useFileFilter.isSelected()) { fileFilter.setEnabled(true); fileFilter.getEditor().selectAll(); fileFilter.getEditor().getEditorComponent().requestFocusInWindow(); } else { fileFilter.setEnabled(false); } } ); } @Override public void doOKAction() { doOKAction(false); } private void doOKAction(boolean findAll) { FindModel validateModel = myHelper.getModel().clone(); applyTo(validateModel, findAll); ValidationInfo validationInfo = getValidationInfo(validateModel); if (validationInfo == null) { myHelper.getModel().copyFrom(validateModel); rememberResultsPreviewWasOpen(); super.doOKAction(); myHelper.doOKAction(); } else { String message = validationInfo.message; Messages.showMessageDialog( myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon() ); } } @Nullable("null means OK") private ValidationInfo getValidationInfo(@NotNull FindModel model) { if (myRbDirectory != null && myRbDirectory.isEnabled() && myRbDirectory.isSelected()) { VirtualFile directory = FindInProjectUtil.getDirectory(model); if (directory == null) { return new ValidationInfo(FindBundle.message("find.directory.not.found.error", getDirectory()), myDirectoryComboBox); } } if (!myHelper.canSearchThisString()) { return new ValidationInfo(FindBundle.message("find.empty.search.text.error"), myInputComboBox); } if (myCbRegularExpressions != null && myCbRegularExpressions.isSelected() && myCbRegularExpressions.isEnabled()) { String toFind = getStringToFind(); try { boolean isCaseSensitive = myCbCaseSensitive != null && myCbCaseSensitive.isSelected() && myCbCaseSensitive.isEnabled(); Pattern pattern = Pattern.compile(toFind, isCaseSensitive ? Pattern.MULTILINE : Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); if (pattern.matcher("").matches() && !toFind.endsWith("$") && !toFind.startsWith("^")) { return new ValidationInfo(FindBundle.message("find.empty.match.regular.expression.error"), myInputComboBox); } } catch (PatternSyntaxException e) { return new ValidationInfo(FindBundle.message("find.invalid.regular.expression.error", toFind, e.getDescription()), myInputComboBox); } } final String mask = getFileTypeMask(); if (mask != null) { if (mask.isEmpty()) { return new ValidationInfo(FindBundle.message("find.filter.empty.file.mask.error"), myFileFilter); } if (mask.contains(";")) { return new ValidationInfo("File masks should be comma-separated", myFileFilter); } else { try { FindInProjectUtil.createFileMaskCondition(mask); // verify that the regexp compiles } catch (PatternSyntaxException ex) { return new ValidationInfo(FindBundle.message("find.filter.invalid.file.mask.error", mask), myFileFilter); } } } return null; } @Override protected ValidationInfo doValidate() { FindModel validateModel = myHelper.getModel().clone(); applyTo(validateModel, false); ValidationInfo result = getValidationInfo(validateModel); setOKStatus(result == null); return result; } @Override public void doHelpAction() { FindModel myModel = myHelper.getModel(); String id = myModel.isReplaceState() ? myModel.isMultipleFiles() ? HelpID.REPLACE_IN_PATH : HelpID.REPLACE_OPTIONS : myModel.isMultipleFiles() ? HelpID.FIND_IN_PATH : HelpID.FIND_OPTIONS; HelpManager.getInstance().invokeHelp(id); } @NotNull private JPanel createFindOptionsPanel() { JPanel findOptionsPanel = new JPanel(); findOptionsPanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.options.group"), true)); findOptionsPanel.setLayout(new BoxLayout(findOptionsPanel, BoxLayout.Y_AXIS)); myCbCaseSensitive = createCheckbox(FindBundle.message("find.options.case.sensitive")); findOptionsPanel.add(myCbCaseSensitive); ItemListener liveResultsPreviewUpdateListener = __ -> scheduleResultsUpdate(); myCbCaseSensitive.addItemListener(liveResultsPreviewUpdateListener); myCbPreserveCase = createCheckbox(FindBundle.message("find.options.replace.preserve.case")); myCbPreserveCase.addItemListener(liveResultsPreviewUpdateListener); findOptionsPanel.add(myCbPreserveCase); myCbPreserveCase.setVisible(myHelper.isReplaceState()); myCbWholeWordsOnly = createCheckbox(FindBundle.message("find.options.whole.words.only")); myCbWholeWordsOnly.addItemListener(liveResultsPreviewUpdateListener); findOptionsPanel.add(myCbWholeWordsOnly); myCbRegularExpressions = createCheckbox(FindBundle.message("find.options.regular.expressions")); myCbRegularExpressions.addItemListener(liveResultsPreviewUpdateListener); final JPanel regExPanel = new JPanel(); regExPanel.setAlignmentX(Component.LEFT_ALIGNMENT); regExPanel.setLayout(new BoxLayout(regExPanel, BoxLayout.X_AXIS)); regExPanel.add(myCbRegularExpressions); regExPanel.add(RegExHelpPopup.createRegExLink("[Help]", regExPanel, LOG)); findOptionsPanel.add(regExPanel); mySearchContext = new ComboBox(new Object[] { getPresentableName(FindModel.SearchContext.ANY), getPresentableName(FindModel.SearchContext.IN_COMMENTS), getPresentableName(FindModel.SearchContext.IN_STRING_LITERALS), getPresentableName(FindModel.SearchContext.EXCEPT_COMMENTS), getPresentableName(FindModel.SearchContext.EXCEPT_STRING_LITERALS), getPresentableName(FindModel.SearchContext.EXCEPT_COMMENTS_AND_STRING_LITERALS)}); mySearchContext.addActionListener(__ -> scheduleResultsUpdate()); final JPanel searchContextPanel = new JPanel(new BorderLayout()); searchContextPanel.setAlignmentX(Component.LEFT_ALIGNMENT); JLabel searchContextLabel = new JLabel(FindBundle.message("find.context.combo.label")); searchContextLabel.setLabelFor(mySearchContext); JPanel panel = new JPanel(); panel.setAlignmentX(Component.LEFT_ALIGNMENT); panel.add(searchContextLabel); searchContextPanel.add(panel, BorderLayout.WEST); panel = new JPanel(new BorderLayout()); panel.add(mySearchContext, BorderLayout.NORTH); searchContextPanel.add(panel, BorderLayout.CENTER); findOptionsPanel.add(searchContextPanel); ActionListener actionListener = __ -> updateControls(); myCbRegularExpressions.addActionListener(actionListener); myCbRegularExpressions.addItemListener(__ -> setupRegExpSetting()); myCbCaseSensitive.addActionListener(actionListener); myCbPreserveCase.addActionListener(actionListener); return findOptionsPanel; } public static String getPresentableName(@NotNull FindModel.SearchContext searchContext) { @PropertyKey(resourceBundle = "messages.FindBundle") String messageKey = null; if (searchContext == FindModel.SearchContext.ANY) { messageKey = "find.context.anywhere.scope.label"; } else if (searchContext == FindModel.SearchContext.EXCEPT_COMMENTS) { messageKey = "find.context.except.comments.scope.label"; } else if (searchContext == FindModel.SearchContext.EXCEPT_STRING_LITERALS) { messageKey = "find.context.except.literals.scope.label"; } else if (searchContext == FindModel.SearchContext.EXCEPT_COMMENTS_AND_STRING_LITERALS) { messageKey = "find.context.except.comments.and.literals.scope.label"; } else if (searchContext == FindModel.SearchContext.IN_COMMENTS) { messageKey = "find.context.in.comments.scope.label"; } else if (searchContext == FindModel.SearchContext.IN_STRING_LITERALS) { messageKey = "find.context.in.literals.scope.label"; } return messageKey != null ? FindBundle.message(messageKey) : searchContext.toString(); } @NotNull static FindModel.SearchContext parseSearchContext(String presentableName) { FindModel.SearchContext searchContext = FindModel.SearchContext.ANY; if (FindBundle.message("find.context.in.literals.scope.label").equals(presentableName)) { searchContext = FindModel.SearchContext.IN_STRING_LITERALS; } else if (FindBundle.message("find.context.in.comments.scope.label").equals(presentableName)) { searchContext = FindModel.SearchContext.IN_COMMENTS; } else if (FindBundle.message("find.context.except.comments.scope.label").equals(presentableName)) { searchContext = FindModel.SearchContext.EXCEPT_COMMENTS; } else if (FindBundle.message("find.context.except.literals.scope.label").equals(presentableName)) { searchContext = FindModel.SearchContext.EXCEPT_STRING_LITERALS; } else if (FindBundle.message("find.context.except.comments.and.literals.scope.label").equals(presentableName)) { searchContext = FindModel.SearchContext.EXCEPT_COMMENTS_AND_STRING_LITERALS; } return searchContext; } @NotNull static String getSearchContextName(FindModel model) { String searchContext = FindBundle.message("find.context.anywhere.scope.label"); if (model.isInCommentsOnly()) searchContext = FindBundle.message("find.context.in.comments.scope.label"); else if (model.isInStringLiteralsOnly()) searchContext = FindBundle.message("find.context.in.literals.scope.label"); else if (model.isExceptStringLiterals()) searchContext = FindBundle.message("find.context.except.literals.scope.label"); else if (model.isExceptComments()) searchContext = FindBundle.message("find.context.except.comments.scope.label"); else if (model.isExceptCommentsAndStringLiterals()) searchContext = FindBundle.message("find.context.except.comments.and.literals.scope.label"); return searchContext; } private void setupRegExpSetting() { updateFileTypeForEditorComponent(myInputComboBox); if (myReplaceComboBox != null) updateFileTypeForEditorComponent(myReplaceComboBox); } private void updateFileTypeForEditorComponent(@NotNull ComboBox inputComboBox) { final Component editorComponent = inputComboBox.getEditor().getEditorComponent(); if (editorComponent instanceof EditorTextField) { boolean isRegexp = myCbRegularExpressions.isSelectedWhenSelectable(); FileType fileType = PlainTextFileType.INSTANCE; if (isRegexp) { Language regexpLanguage = Language.findLanguageByID("RegExp"); if (regexpLanguage != null) { LanguageFileType regexpFileType = regexpLanguage.getAssociatedFileType(); if (regexpFileType != null) { fileType = regexpFileType; } } } String fileName = isRegexp ? "a.regexp" : "a.txt"; final PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(fileName, fileType, ((EditorTextField)editorComponent).getText(), -1, true); ((EditorTextField)editorComponent).setNewDocumentAndFileType(fileType, PsiDocumentManager.getInstance(myProject).getDocument(file)); } } private void updateControls() { if (myCbRegularExpressions.isSelected()) { myCbWholeWordsOnly.makeUnselectable(false); } else { myCbWholeWordsOnly.makeSelectable(); } if (myHelper.isReplaceState()) { if (myCbRegularExpressions.isSelected() || myCbCaseSensitive.isSelected()) { myCbPreserveCase.makeUnselectable(false); } else { myCbPreserveCase.makeSelectable(); } if (myCbPreserveCase.isSelected()) { myCbRegularExpressions.makeUnselectable(false); myCbCaseSensitive.makeUnselectable(false); } else { myCbRegularExpressions.makeSelectable(); myCbCaseSensitive.makeSelectable(); } } if (!myHelper.getModel().isMultipleFiles()) { myRbFromCursor.setEnabled(myRbGlobal.isSelected()); myRbEntireScope.setEnabled(myRbGlobal.isSelected()); } } @NotNull private JPanel createDirectionPanel() { JPanel directionPanel = new JPanel(); directionPanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.direction.group"), true)); directionPanel.setLayout(new BoxLayout(directionPanel, BoxLayout.Y_AXIS)); myRbForward = new JRadioButton(FindBundle.message("find.direction.forward.radio"), true); directionPanel.add(myRbForward); myRbBackward = new JRadioButton(FindBundle.message("find.direction.backward.radio")); directionPanel.add(myRbBackward); ButtonGroup bgDirection = new ButtonGroup(); bgDirection.add(myRbForward); bgDirection.add(myRbBackward); return directionPanel; } @NotNull private JComponent createGlobalScopePanel() { JPanel scopePanel = new JPanel(); scopePanel.setLayout(new GridBagLayout()); scopePanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.scope.group"), true)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.gridx = 0; gbConstraints.gridy = 0; gbConstraints.gridwidth = 3; gbConstraints.weightx = 1; final boolean canAttach = ProjectAttachProcessor.canAttachToProject(); myRbProject = new JRadioButton(canAttach ? FindBundle.message("find.scope.all.projects.radio") : FindBundle.message("find.scope.whole.project.radio"), true); scopePanel.add(myRbProject, gbConstraints); ItemListener resultsPreviewUpdateListener = __ -> scheduleResultsUpdate(); myRbProject.addItemListener(resultsPreviewUpdateListener); gbConstraints.gridx = 0; gbConstraints.gridy++; gbConstraints.weightx = 0; gbConstraints.gridwidth = 1; myRbModule = new JRadioButton(canAttach ? FindBundle.message("find.scope.project.radio") : FindBundle.message("find.scope.module.radio"), false); scopePanel.add(myRbModule, gbConstraints); myRbModule.addItemListener(resultsPreviewUpdateListener); gbConstraints.gridx = 1; gbConstraints.gridwidth = 2; gbConstraints.weightx = 1; Module[] modules = ModuleManager.getInstance(myProject).getModules(); String[] names = new String[modules.length]; for (int i = 0; i < modules.length; i++) { names[i] = modules[i].getName(); } Arrays.sort(names,String.CASE_INSENSITIVE_ORDER); myModuleComboBox = new ComboBox(names); myModuleComboBox.addActionListener(__ -> scheduleResultsUpdate()); scopePanel.add(myModuleComboBox, gbConstraints); if (modules.length == 1) { myModuleComboBox.setVisible(false); myRbModule.setVisible(false); } gbConstraints.gridx = 0; gbConstraints.gridy++; gbConstraints.weightx = 0; gbConstraints.gridwidth = 1; myRbDirectory = new JRadioButton(FindBundle.message("find.scope.directory.radio"), false); scopePanel.add(myRbDirectory, gbConstraints); myRbDirectory.addItemListener(resultsPreviewUpdateListener); gbConstraints.gridx = 1; gbConstraints.weightx = 1; myDirectoryComboBox = new ComboBox(200); Component editorComponent = myDirectoryComboBox.getEditor().getEditorComponent(); if (editorComponent instanceof JTextField) { JTextField field = (JTextField)editorComponent; field.setColumns(40); } initCombobox(myDirectoryComboBox); myDirectoryComboBox.setSwingPopup(false); myDirectoryComboBox.addActionListener(__ -> scheduleResultsUpdate()); scopePanel.add(myDirectoryComboBox, gbConstraints); gbConstraints.weightx = 0; gbConstraints.gridx = 2; mySelectDirectoryButton = new FixedSizeButton(myDirectoryComboBox); TextFieldWithBrowseButton.MyDoClickAction.addTo(mySelectDirectoryButton, myDirectoryComboBox); mySelectDirectoryButton.setMargin(new Insets(0, 0, 0, 0)); scopePanel.add(mySelectDirectoryButton, gbConstraints); gbConstraints.gridx = 0; gbConstraints.gridy++; gbConstraints.weightx = 1; gbConstraints.gridwidth = 3; gbConstraints.insets = new Insets(0, 16, 0, 0); myCbWithSubdirectories = createCheckbox(true, FindBundle.message("find.scope.directory.recursive.checkbox")); myCbWithSubdirectories.setSelected(true); myCbWithSubdirectories.addItemListener(resultsPreviewUpdateListener); scopePanel.add(myCbWithSubdirectories, gbConstraints); gbConstraints.gridx = 0; gbConstraints.gridy++; gbConstraints.weightx = 0; gbConstraints.gridwidth = 1; gbConstraints.insets = new Insets(0, 0, 0, 0); myRbCustomScope = new JRadioButton(FindBundle.message("find.scope.custom.radio"), false); scopePanel.add(myRbCustomScope, gbConstraints); gbConstraints.gridx++; gbConstraints.weightx = 1; gbConstraints.gridwidth = 2; myScopeCombo = new ScopeChooserCombo(); myScopeCombo.init(myProject, true, true, FindSettings.getInstance().getDefaultScopeName(), new Condition<ScopeDescriptor>() { //final String projectFilesScopeName = PsiBundle.message("psi.search.scope.project"); private final String moduleFilesScopeName; { String moduleScopeName = PsiBundle.message("search.scope.module", ""); final int ind = moduleScopeName.indexOf(' '); moduleFilesScopeName = moduleScopeName.substring(0, ind + 1); } @Override public boolean value(ScopeDescriptor descriptor) { final String display = descriptor.getDisplay(); return /*!projectFilesScopeName.equals(display) &&*/ !display.startsWith(moduleFilesScopeName); } }); myScopeCombo.getComboBox().addActionListener(__ -> scheduleResultsUpdate()); myRbCustomScope.addItemListener(resultsPreviewUpdateListener); Disposer.register(myDisposable, myScopeCombo); scopePanel.add(myScopeCombo, gbConstraints); ButtonGroup bgScope = new ButtonGroup(); bgScope.add(myRbProject); bgScope.add(myRbModule); bgScope.add(myRbDirectory); bgScope.add(myRbCustomScope); myRbProject.addActionListener(__ -> { validateScopeControls(); validateFindButton(); }); myRbCustomScope.addActionListener(__ -> { validateScopeControls(); validateFindButton(); myScopeCombo.getComboBox().requestFocusInWindow(); }); myRbDirectory.addActionListener(__ -> { validateScopeControls(); validateFindButton(); myDirectoryComboBox.getEditor().getEditorComponent().requestFocusInWindow(); }); myRbModule.addActionListener(__ -> { validateScopeControls(); validateFindButton(); myModuleComboBox.requestFocusInWindow(); }); mySelectDirectoryButton.addActionListener(__ -> { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); FileChooser.chooseFiles(descriptor, myProject, null, files -> myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl())); }); return scopePanel; } @NotNull private static StateRestoringCheckBox createCheckbox(@NotNull String message) { final StateRestoringCheckBox cb = new StateRestoringCheckBox(message); cb.setFocusable(false); return cb; } @NotNull private static StateRestoringCheckBox createCheckbox(boolean selected, @NotNull String message) { final StateRestoringCheckBox cb = new StateRestoringCheckBox(message, selected); cb.setFocusable(false); return cb; } private void validateScopeControls() { if (myRbDirectory.isSelected()) { myCbWithSubdirectories.makeSelectable(); } else { myCbWithSubdirectories.makeUnselectable(myCbWithSubdirectories.isSelected()); } myDirectoryComboBox.setEnabled(myRbDirectory.isSelected()); mySelectDirectoryButton.setEnabled(myRbDirectory.isSelected()); myModuleComboBox.setEnabled(myRbModule.isSelected()); myScopeCombo.setEnabled(myRbCustomScope.isSelected()); } @NotNull private JPanel createScopePanel() { JPanel scopePanel = new JPanel(); scopePanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.scope.group"), true)); scopePanel.setLayout(new BoxLayout(scopePanel, BoxLayout.Y_AXIS)); myRbGlobal = new JRadioButton(FindBundle.message("find.scope.global.radio"), true); scopePanel.add(myRbGlobal); myRbSelectedText = new JRadioButton(FindBundle.message("find.scope.selected.text.radio")); scopePanel.add(myRbSelectedText); ButtonGroup bgScope = new ButtonGroup(); bgScope.add(myRbGlobal); bgScope.add(myRbSelectedText); ActionListener actionListener = __ -> updateControls(); myRbGlobal.addActionListener(actionListener); myRbSelectedText.addActionListener(actionListener); return scopePanel; } @NotNull private JPanel createOriginPanel() { JPanel originPanel = new JPanel(); originPanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.origin.group"), true)); originPanel.setLayout(new BoxLayout(originPanel, BoxLayout.Y_AXIS)); myRbFromCursor = new JRadioButton(FindBundle.message("find.origin.from.cursor.radio"), true); originPanel.add(myRbFromCursor); myRbEntireScope = new JRadioButton(FindBundle.message("find.origin.entire.scope.radio")); originPanel.add(myRbEntireScope); ButtonGroup bgOrigin = new ButtonGroup(); bgOrigin.add(myRbFromCursor); bgOrigin.add(myRbEntireScope); return originPanel; } @Override @NotNull public String getStringToFind() { String string = (String)myInputComboBox.getEditor().getItem(); return string == null ? "" : string; } @NotNull private String getStringToReplace() { String item = (String)myReplaceComboBox.getEditor().getItem(); return item == null ? "" : item; } private String getDirectory() { return (String)myDirectoryComboBox.getEditor().getItem(); } private static void setStringsToComboBox(@NotNull String[] strings, @NotNull ComboBox<String> combo, String selected) { if (combo.getItemCount() > 0){ combo.removeAllItems(); } if (selected != null && selected.indexOf('\n') < 0) { strings = ArrayUtil.remove(strings, selected); // this ensures that last searched string will be selected if selected == "" if (!selected.isEmpty()) strings = ArrayUtil.append(strings, selected); } for(int i = strings.length - 1; i >= 0; i--){ combo.addItem(strings[i]); } } private void setDirectories(@NotNull List<String> strings, String directoryName) { if (myDirectoryComboBox.getItemCount() > 0){ myReplaceComboBox.removeAllItems(); } int ignoredIdx = -1; if (directoryName != null && !directoryName.isEmpty()){ ignoredIdx = strings.indexOf(directoryName); myDirectoryComboBox.addItem(directoryName); } for(int i = strings.size() - 1; i >= 0; i--){ if (i == ignoredIdx) continue; myDirectoryComboBox.addItem(strings.get(i)); } if (myDirectoryComboBox.getItemCount() == 0){ myDirectoryComboBox.addItem(""); } } private void applyTo(@NotNull FindModel model, boolean findAll) { model.setCaseSensitive(myCbCaseSensitive.isSelected()); if (model.isReplaceState()) { model.setPreserveCase(myCbPreserveCase.isSelected()); } model.setWholeWordsOnly(myCbWholeWordsOnly.isSelected()); String selectedSearchContextInUi = (String)mySearchContext.getSelectedItem(); FindModel.SearchContext searchContext = parseSearchContext(selectedSearchContextInUi); model.setSearchContext(searchContext); model.setRegularExpressions(myCbRegularExpressions.isSelected()); String stringToFind = getStringToFind(); model.setStringToFind(stringToFind); if (model.isReplaceState()){ model.setPromptOnReplace(true); model.setReplaceAll(false); String stringToReplace = getStringToReplace(); model.setStringToReplace(StringUtil.convertLineSeparators(stringToReplace)); } if (!model.isMultipleFiles()){ model.setForward(myRbForward.isSelected()); model.setFromCursor(myRbFromCursor.isSelected()); model.setGlobal(myRbGlobal.isSelected()); } else{ if (myCbToOpenInNewTab != null){ model.setOpenInNewTab(myCbToOpenInNewTab.isSelected()); } model.setProjectScope(myRbProject.isSelected()); model.setDirectoryName(null); model.setModuleName(null); model.setCustomScopeName(null); model.setCustomScope(null); model.setCustomScope(false); if (myRbDirectory.isSelected()) { String directory = getDirectory(); model.setDirectoryName(directory == null ? "" : directory); model.setWithSubdirectories(myCbWithSubdirectories.isSelected()); } else if (myRbModule.isSelected()) { model.setModuleName((String)myModuleComboBox.getSelectedItem()); } else if (myRbCustomScope.isSelected()) { SearchScope selectedScope = myScopeCombo.getSelectedScope(); String customScopeName = selectedScope == null ? null : selectedScope.getDisplayName(); model.setCustomScopeName(customScopeName); model.setCustomScope(selectedScope); model.setCustomScope(true); } } model.setFindAll(findAll); String mask = getFileTypeMask(); model.setFileFilter(mask); } @Override @Nullable public String getFileTypeMask() { String mask = null; if (myUseFileFilter !=null && myUseFileFilter.isSelected()) { mask = (String)myFileFilter.getEditor().getItem(); } return mask; } @Override public void initByModel() { FindModel myModel = myHelper.getModel(); myCbCaseSensitive.setSelected(myModel.isCaseSensitive()); myCbWholeWordsOnly.setSelected(myModel.isWholeWordsOnly()); String searchContext = getSearchContextName(myModel); mySearchContext.setSelectedItem(searchContext); myCbRegularExpressions.setSelected(myModel.isRegularExpressions()); if (myModel.isMultipleFiles()) { final String dirName = myModel.getDirectoryName(); setDirectories(FindInProjectSettings.getInstance(myProject).getRecentDirectories(), dirName); if (!StringUtil.isEmptyOrSpaces(dirName)) { VirtualFile dir = LocalFileSystem.getInstance().findFileByPath(dirName); if (dir != null) { Module module = ModuleUtilCore.findModuleForFile(dir, myProject); if (module != null) { myModuleComboBox.setSelectedItem(module.getName()); } } } if (myModel.isCustomScope()) { myRbCustomScope.setSelected(true); myScopeCombo.setEnabled(true); myCbWithSubdirectories.setEnabled(false); myDirectoryComboBox.setEnabled(false); mySelectDirectoryButton.setEnabled(false); myModuleComboBox.setEnabled(false); } else if (myModel.isProjectScope()) { myRbProject.setSelected(true); myCbWithSubdirectories.setEnabled(false); myDirectoryComboBox.setEnabled(false); mySelectDirectoryButton.setEnabled(false); myModuleComboBox.setEnabled(false); myScopeCombo.setEnabled(false); } else if (dirName != null) { myRbDirectory.setSelected(true); myCbWithSubdirectories.setEnabled(true); myDirectoryComboBox.setEnabled(true); mySelectDirectoryButton.setEnabled(true); myModuleComboBox.setEnabled(false); myScopeCombo.setEnabled(false); } else if (myModel.getModuleName() != null) { myRbModule.setSelected(true); myCbWithSubdirectories.setEnabled(false); myDirectoryComboBox.setEnabled(false); mySelectDirectoryButton.setEnabled(false); myModuleComboBox.setEnabled(true); myModuleComboBox.setSelectedItem(myModel.getModuleName()); myScopeCombo.setEnabled(false); // force showing even if we have only one module myRbModule.setVisible(true); myModuleComboBox.setVisible(true); } else { assert false : myModel; } myCbWithSubdirectories.setSelected(myModel.isWithSubdirectories()); if (myModel.getFileFilter()!=null && !myModel.getFileFilter().isEmpty()) { myFileFilter.setSelectedItem(myModel.getFileFilter()); myFileFilter.setEnabled(true); myUseFileFilter.setSelected(true); } } else { if (myModel.isForward()){ myRbForward.setSelected(true); } else{ myRbBackward.setSelected(true); } if (myModel.isFromCursor()){ myRbFromCursor.setSelected(true); } else{ myRbEntireScope.setSelected(true); } if (myModel.isGlobal()){ myRbGlobal.setSelected(true); } else{ myRbSelectedText.setSelected(true); } } FindInProjectSettings findInProjectSettings = FindInProjectSettings.getInstance(myProject); setStringsToComboBox(findInProjectSettings.getRecentFindStrings(), myInputComboBox, myModel.getStringToFind()); if (myModel.isReplaceState()){ myCbPreserveCase.setSelected(myModel.isPreserveCase()); setStringsToComboBox(findInProjectSettings.getRecentReplaceStrings(), myReplaceComboBox, myModel.getStringToReplace()); } updateControls(); boolean isReplaceState = myModel.isReplaceState(); myReplacePrompt.setVisible(isReplaceState); myReplaceComboBox.setVisible(isReplaceState); if (myCbToSkipResultsWhenOneUsage != null) { myCbToSkipResultsWhenOneUsage.setVisible(!isReplaceState); } myCbPreserveCase.setVisible(isReplaceState); setTitle(myHelper.getTitle()); validateFindButton(); } private void navigateToSelectedUsage(JBTable source) { int[] rows = source.getSelectedRows(); List<Usage> navigations = null; for(int row:rows) { Object valueAt = source.getModel().getValueAt(row, 0); if (valueAt instanceof Usage) { if (navigations == null) navigations = new SmartList<>(); Usage at = (Usage)valueAt; navigations.add(at); } } if (navigations != null) { doCancelAction(); navigations.get(0).navigate(true); for(int i = 1; i < navigations.size(); ++i) navigations.get(i).highlightInEditor(); } } static class UsageTableCellRenderer extends JPanel implements TableCellRenderer { private final ColoredTableCellRenderer myUsageRenderer = new ColoredTableCellRenderer() { @Override protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) { if (value instanceof UsageInfo2UsageAdapter) { if (!((UsageInfo2UsageAdapter)value).isValid()) { myUsageRenderer.append(" "+UsageViewBundle.message("node.invalid") + " ", SimpleTextAttributes.ERROR_ATTRIBUTES); } TextChunk[] text = ((UsageInfo2UsageAdapter)value).getPresentation().getText(); // skip line number / file info for (int i = 1; i < text.length; ++i) { TextChunk textChunk = text[i]; SimpleTextAttributes attributes = getAttributes(textChunk); myUsageRenderer.append(textChunk.getText(), attributes); } } setBorder(null); } @NotNull private SimpleTextAttributes getAttributes(@NotNull TextChunk textChunk) { SimpleTextAttributes at = textChunk.getSimpleAttributesIgnoreBackground(); if (myUseBold) return at; boolean highlighted = textChunk.getType() != null || at.getFontStyle() == Font.BOLD; return highlighted ? new SimpleTextAttributes(null, at.getFgColor(), at.getWaveColor(), (at.getStyle() & ~SimpleTextAttributes.STYLE_BOLD) | SimpleTextAttributes.STYLE_SEARCH_MATCH) : at; } }; private final ColoredTableCellRenderer myFileAndLineNumber = new ColoredTableCellRenderer() { private final SimpleTextAttributes REPEATED_FILE_ATTRIBUTES = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, new JBColor(0xCCCCCC, 0x5E5E5E)); private final SimpleTextAttributes ORDINAL_ATTRIBUTES = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, new JBColor(0x999999, 0x999999)); @Override protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) { if (value instanceof UsageInfo2UsageAdapter) { UsageInfo2UsageAdapter usageAdapter = (UsageInfo2UsageAdapter)value; TextChunk[] text = usageAdapter.getPresentation().getText(); // line number / file info VirtualFile file = usageAdapter.getFile(); String uniqueVirtualFilePath = getFilePath(usageAdapter); VirtualFile prevFile = findPrevFile(table, row, column); SimpleTextAttributes attributes = Comparing.equal(file, prevFile) ? REPEATED_FILE_ATTRIBUTES : ORDINAL_ATTRIBUTES; append(uniqueVirtualFilePath, attributes); if (text.length > 0) append(" " + text[0].getText(), ORDINAL_ATTRIBUTES); } setBorder(null); } @NotNull private String getFilePath(@NotNull UsageInfo2UsageAdapter ua) { String uniquePath = UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(ua.getUsageInfo().getProject(), ua.getFile(), myScope); return myOmitFileExtension ? FileUtilRt.getNameWithoutExtension(uniquePath) : uniquePath; } @Nullable private VirtualFile findPrevFile(@NotNull JTable table, int row, int column) { if (row <= 0) return null; Object prev = table.getValueAt(row - 1, column); return prev instanceof UsageInfo2UsageAdapter ? ((UsageInfo2UsageAdapter)prev).getFile() : null; } }; private static final int MARGIN = 2; private final boolean myOmitFileExtension; private final boolean myUseBold; private final GlobalSearchScope myScope; UsageTableCellRenderer(boolean omitFileExtension, boolean useBold, GlobalSearchScope scope) { myOmitFileExtension = omitFileExtension; myUseBold = useBold; myScope = scope; setLayout(new BorderLayout()); add(myUsageRenderer, BorderLayout.CENTER); add(myFileAndLineNumber, BorderLayout.EAST); setBorder(JBUI.Borders.empty(MARGIN, MARGIN, MARGIN, 0)); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { myUsageRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); myFileAndLineNumber.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setBackground(myUsageRenderer.getBackground()); if (!isSelected && value instanceof UsageInfo2UsageAdapter) { UsageInfo2UsageAdapter usageAdapter = (UsageInfo2UsageAdapter)value; Color color = FileColorManager.getInstance(usageAdapter.getUsageInfo().getProject()).getFileColor(usageAdapter.getFile()); setBackground(color); myUsageRenderer.setBackground(color); myFileAndLineNumber.setBackground(color); } return this; } } private class NavigateToSourceListener extends DoubleClickListener { @Override protected boolean onDoubleClick(MouseEvent event) { Object source = event.getSource(); if (!(source instanceof JBTable)) return false; navigateToSelectedUsage((JBTable)source); return true; } @Override public void installOn(@NotNull final Component c) { super.installOn(c); if (c instanceof JBTable) { String key = "navigate.to.usage"; JComponent component = (JComponent)c; component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), key); component.getActionMap().put(key, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { navigateToSelectedUsage((JBTable)c); } }); //anAction.registerCustomShortcutSet(CommonShortcuts.ENTER, component); registerNavigateToSourceShortcutOnComponent((JBTable)c, component); } } } protected void registerNavigateToSourceShortcutOnComponent(@NotNull final JBTable c, JComponent component) { AnAction anAction = new AnAction() { @Override public void actionPerformed(AnActionEvent e) { navigateToSelectedUsage(c); } }; anAction.registerCustomShortcutSet(CommonShortcuts.getEditSource(), component, myDisposable); } }
{ "content_hash": "aaf9dc2d43056a169ed46504c4381ae8", "timestamp": "", "source": "github", "line_count": 1630, "max_line_length": 180, "avg_line_length": 40.70122699386503, "alnum_prop": 0.7124941591426375, "repo_name": "mglukhikh/intellij-community", "id": "f09aa8c58be9f1f8e9547bc51a48503909d30b04", "size": "66943", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platform/lang-impl/src/com/intellij/find/impl/FindDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60827" }, { "name": "C", "bytes": "211435" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "197674" }, { "name": "CMake", "bytes": "1675" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "3243028" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1899088" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "165554704" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "4611299" }, { "name": "Lex", "bytes": "147047" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "51276" }, { "name": "Objective-C", "bytes": "27861" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl 6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6680" }, { "name": "Python", "bytes": "25439881" }, { "name": "Roff", "bytes": "37534" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "66341" }, { "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": "" }
struct ViewHostMsg_TextInputState_Params; namespace content { class BrowserPluginGuest; class RenderWidgetHost; class RenderWidgetHostImpl; struct NativeWebKeyboardEvent; // See comments in render_widget_host_view.h about this class and its members. // This version is for the BrowserPlugin which handles a lot of the // functionality in a diffent place and isn't platform specific. // The BrowserPlugin is currently a special case for out-of-process rendered // content and therefore inherits from RenderWidgetHostViewChildFrame. // Eventually all RenderWidgetHostViewGuest code will be subsumed by // RenderWidgetHostViewChildFrame and this class will be removed. // // Some elements that are platform specific will be deal with by delegating // the relevant calls to the platform view. class CONTENT_EXPORT RenderWidgetHostViewGuest : public RenderWidgetHostViewChildFrame, public ui::GestureConsumer, public ui::GestureEventHelper { public: RenderWidgetHostViewGuest( RenderWidgetHost* widget, BrowserPluginGuest* guest, base::WeakPtr<RenderWidgetHostViewBase> platform_view); ~RenderWidgetHostViewGuest() override; bool OnMessageReceivedFromEmbedder(const IPC::Message& message, RenderWidgetHostImpl* embedder); // RenderWidgetHostView implementation. bool OnMessageReceived(const IPC::Message& msg) override; void InitAsChild(gfx::NativeView parent_view) override; void SetSize(const gfx::Size& size) override; void SetBounds(const gfx::Rect& rect) override; void Focus() override; bool HasFocus() const override; void Show() override; void Hide() override; gfx::NativeView GetNativeView() const override; gfx::NativeViewId GetNativeViewId() const override; gfx::NativeViewAccessible GetNativeViewAccessible() override; gfx::Rect GetViewBounds() const override; void SetBackgroundColor(SkColor color) override; gfx::Size GetPhysicalBackingSize() const override; base::string16 GetSelectedText() const override; // RenderWidgetHostViewBase implementation. void InitAsPopup(RenderWidgetHostView* parent_host_view, const gfx::Rect& bounds) override; void InitAsFullscreen(RenderWidgetHostView* reference_host_view) override; void MovePluginWindows(const std::vector<WebPluginGeometry>& moves) override; void UpdateCursor(const WebCursor& cursor) override; void SetIsLoading(bool is_loading) override; void TextInputStateChanged( const ViewHostMsg_TextInputState_Params& params) override; void ImeCancelComposition() override; #if defined(OS_MACOSX) || defined(USE_AURA) void ImeCompositionRangeChanged( const gfx::Range& range, const std::vector<gfx::Rect>& character_bounds) override; #endif void RenderProcessGone(base::TerminationStatus status, int error_code) override; void Destroy() override; void SetTooltipText(const base::string16& tooltip_text) override; void SelectionChanged(const base::string16& text, size_t offset, const gfx::Range& range) override; void SelectionBoundsChanged( const ViewHostMsg_SelectionBounds_Params& params) override; void OnSwapCompositorFrame(uint32 output_surface_id, scoped_ptr<cc::CompositorFrame> frame) override; #if defined(USE_AURA) void ProcessAckedTouchEvent(const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) override; #endif bool LockMouse() override; void UnlockMouse() override; void GetScreenInfo(blink::WebScreenInfo* results) override; bool GetScreenColorProfile(std::vector<char>* color_profile) override; #if defined(OS_MACOSX) // RenderWidgetHostView implementation. void SetActive(bool active) override; void SetWindowVisibility(bool visible) override; void WindowFrameChanged() override; void ShowDefinitionForSelection() override; bool SupportsSpeech() const override; void SpeakSelection() override; bool IsSpeaking() const override; void StopSpeaking() override; // RenderWidgetHostViewBase implementation. bool PostProcessEventForPluginIme( const NativeWebKeyboardEvent& event) override; #endif // defined(OS_MACOSX) #if defined(OS_ANDROID) || defined(USE_AURA) // RenderWidgetHostViewBase implementation. void ShowDisambiguationPopup(const gfx::Rect& rect_pixels, const SkBitmap& zoomed_bitmap) override; #endif // defined(OS_ANDROID) || defined(USE_AURA) void LockCompositingSurface() override; void UnlockCompositingSurface() override; #if defined(OS_WIN) void SetParentNativeViewAccessible( gfx::NativeViewAccessible accessible_parent) override; gfx::NativeViewId GetParentForWindowlessPlugin() const override; #endif void WheelEventAck(const blink::WebMouseWheelEvent& event, InputEventAckState ack_result) override; void GestureEventAck(const blink::WebGestureEvent& event, InputEventAckState ack_result) override; // Overridden from ui::GestureEventHelper. bool CanDispatchToConsumer(ui::GestureConsumer* consumer) override; void DispatchGestureEvent(ui::GestureEvent* event) override; void DispatchCancelTouchEvent(ui::TouchEvent* event) override; protected: friend class RenderWidgetHostView; private: // Destroys this view without calling |Destroy| on |platform_view_|. void DestroyGuestView(); // Builds and forwards a WebKitGestureEvent to the renderer. bool ForwardGestureEventToRenderer(ui::GestureEvent* gesture); // Process all of the given gestures (passes them on to renderer) void ProcessGestures(ui::GestureRecognizer::Gestures* gestures); RenderWidgetHostViewBase* GetOwnerRenderWidgetHostView() const; void OnHandleInputEvent(RenderWidgetHostImpl* embedder, int browser_plugin_instance_id, const gfx::Rect& guest_window_rect, const blink::WebInputEvent* event); // BrowserPluginGuest and RenderWidgetHostViewGuest's lifetimes are not tied // to one another, therefore we access |guest_| through WeakPtr. base::WeakPtr<BrowserPluginGuest> guest_; gfx::Size size_; // The platform view for this RenderWidgetHostView. // RenderWidgetHostViewGuest mostly only cares about stuff related to // compositing, the rest are directly forwared to this |platform_view_|. base::WeakPtr<RenderWidgetHostViewBase> platform_view_; #if defined(USE_AURA) scoped_ptr<ui::GestureRecognizer> gesture_recognizer_; #endif DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewGuest); }; } // namespace content #endif // CONTENT_BROWSER_FRAME_HOST_RENDER_WIDGET_HOST_VIEW_GUEST_H_
{ "content_hash": "56dc9cb4412dd6c912fab59df7cad1e2", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 79, "avg_line_length": 41.45398773006135, "alnum_prop": 0.7475210892407873, "repo_name": "Bysmyyr/chromium-crosswalk", "id": "62bfb6129058289a58b284a92feb1408dce4a30d", "size": "7578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/browser/frame_host/render_widget_host_view_guest.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.remind.me.fninaber.db; import java.util.ArrayList; import java.util.List; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import com.remind.me.fninaber.Constants; import com.remind.me.fninaber.model.Calendar; import com.remind.me.fninaber.model.Task; import com.remind.me.fninaber.model.Type; import com.remind.me.fninaber.util.DateUtil; public class TaskHelper { private static Uri URI = TableTask.CONTENT_URI; private static TaskHelper mInstance = null; public static TaskHelper getInstance() { if (mInstance == null) { mInstance = new TaskHelper(); } return mInstance; } public boolean insert(ContentResolver resolver, Task task) { String TID = task.getTID(); ContentValues values = new ContentValues(); values.put(TableTask.Column.TID, TID); values.put(TableTask.Column.TITLE, task.getTitle()); values.put(TableTask.Column.NOTES, task.getNotes()); values.put(TableTask.Column.TIMESTAMP, task.getTimestamp()); values.put(TableTask.Column.SNOOZE, task.getSnooze()); values.put(TableTask.Column.TYPE, task.getType()); values.put(TableTask.Column.REPEAT, task.getRepeat()); values.put(TableTask.Column.STATUS, task.getStatus()); values.put(TableTask.Column.PATH, task.getPath()); if (isExist(resolver, TID)) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; return resolver.update(URI, values, selection, args) > 0; } return resolver.insert(URI, values) != null; } public boolean setSnoozeToDefault(ContentResolver resolver, String TID) { ContentValues values = new ContentValues(); values.put(TableTask.Column.SNOOZE, -1); if (isExist(resolver, TID)) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; return resolver.update(URI, values, selection, args) > 0; } return false; } public boolean updateStatus(ContentResolver resolver, String TID, int status) { ContentValues values = new ContentValues(); values.put(TableTask.Column.STATUS, status); if (isExist(resolver, TID)) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; return resolver.update(URI, values, selection, args) > 0; } return resolver.insert(URI, values) != null; } public boolean updateTimestamp(ContentResolver resolver, String TID, long timestamp) { ContentValues values = new ContentValues(); values.put(TableTask.Column.TIMESTAMP, timestamp); if (isExist(resolver, TID)) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; return resolver.update(URI, values, selection, args) > 0; } return resolver.insert(URI, values) != null; } public boolean isExist(ContentResolver resolver, String tid) { Task task = queryByTID(resolver, tid); if (task != null && !TextUtils.isEmpty(task.getTID())) { return true; } return false; } public Task queryByTID(ContentResolver resolver, String TID) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; Cursor cursor = resolver.query(URI, null, selection, args, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); Task task = cursorToTask(cursor); cursor.close(); return task; } return null; } public int getCursorCount(ContentResolver resolver) { Cursor cursor = resolver.query(URI, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { int result = cursor.getCount(); cursor.close(); return result; } return 0; } public int update(ContentResolver resolver, ContentValues values, String where, String[] selectionArgs) { return resolver.update(URI, values, where, selectionArgs); } public int deleteByTID(ContentResolver resolver, String TID) { String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; return resolver.delete(URI, selection, args); } public List<String> deleteImageByTime(ContentResolver resolver, String timestamp) { List<String> paths = new ArrayList<String>(); String selection = TableTask.Column.TIMESTAMP + " <= ?" + " AND " + TableTask.Column.TYPE + " = ?"; String[] args = {timestamp, Type.PHOTO.toString()}; Cursor cursor = resolver.query(URI, null, selection, args, TableTask.Column.TIMESTAMP + " DESC"); Log.e("f.ninaber", "Cursor.getCount : " + cursor.getCount()); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { Task task = cursorToTask(cursor); String path = task.getPath(); Log.e("f.ninaber", "Cursor.path : " + path); if (!TextUtils.isEmpty(path)) { paths.add(path); } cursor.moveToNext(); } } resolver.delete(URI, selection, args); return paths; } public List<String> deleteAudioByTime(ContentResolver resolver, String timestamp) { List<String> paths = new ArrayList<String>(); String selection = TableTask.Column.TIMESTAMP + " <= ?" + " AND " + TableTask.Column.TYPE + " = ?"; String[] args = {timestamp, Type.AUDIO.toString()}; Cursor cursor = resolver.query(URI, null, selection, args, TableTask.Column.TIMESTAMP + " DESC"); Log.e("f.ninaber", "Cursor.getCount : " + cursor.getCount()); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { Task task = cursorToTask(cursor); String path = task.getPath(); Log.e("f.ninaber", "Cursor.path : " + path); if (!TextUtils.isEmpty(path)) { paths.add(path); } cursor.moveToNext(); } } resolver.delete(URI, selection, args); return paths; } public void deleteTaskByTime(ContentResolver resolver, String timestamp) { List<String> paths = new ArrayList<String>(); String selection = TableTask.Column.TIMESTAMP + " <= ?" + " AND " + TableTask.Column.TYPE + " = ?"; String[] args = {timestamp, Type.TEXT.toString()}; resolver.delete(URI, selection, args); } public int deleteAll(ContentResolver resolver) { return resolver.delete(URI, null, null); } public Cursor getCursorDataDesc(ContentResolver resolver, String selection) { Cursor cursor = resolver.query(URI, null, selection, null, TableTask.Column.TIMESTAMP + " DESC"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); return cursor; } return null; } public Cursor getCursorDataAsc(ContentResolver resolver, String selection) { Cursor cursor = resolver.query(URI, null, selection, null, TableTask.Column.TIMESTAMP + " ASC"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); return cursor; } return null; } public Task getTaskByTID(ContentResolver resolver, String TID) { Task task = null; String selection = TableTask.Column.TID + " = ?"; String[] args = {TID}; Cursor cursor = resolver.query(URI, null, selection, args, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); task = cursorToTask(cursor); } return task; } public Task getFirstTimestamp(ContentResolver resolver, long timestamp) { Task task = null; // String selection = TableTask.Column.TIMESTAMP + " > ?" + " AND " + // TableTask.Column.STATUS + " = ?"; // String[] args = {String.valueOf(timestamp), // String.valueOf(Constants.ON_GOING)}; String selection = TableTask.Column.STATUS + " = ?"; String[] args = {String.valueOf(Constants.ON_GOING)}; Cursor cursor = resolver.query(URI, null, selection, args, TableTask.Column.TIMESTAMP + " ASC"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); task = cursorToTask(cursor); } return task; } public Task getFirstSnooze(ContentResolver resolver, long timestamp) { Task task = null; String selection = TableTask.Column.SNOOZE + " > ?"; String[] args = {String.valueOf(timestamp)}; Cursor cursor = resolver.query(URI, null, selection, args, TableTask.Column.SNOOZE + " ASC"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); task = cursorToTask(cursor); } return task; } public List<Task> queryAll(ContentResolver resolver) { Cursor cursor = getCursorDataDesc(resolver, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); List<Task> tasks = new ArrayList<Task>(); for (int i = 0; i < cursor.getCount(); i++) { Task task = cursorToTask(cursor); if (task != null) { tasks.add(task); } cursor.moveToNext(); } cursor.close(); return tasks; } return null; } private List<Calendar> getAvailableTimestamp(ContentResolver resolver, Cursor cursor) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); List<Calendar> timestamps = new ArrayList<Calendar>(); List<String> checks = new ArrayList<String>(); for (int i = 0; i < cursor.getCount(); i++) { long timestamp = cursor.getLong(cursor.getColumnIndex(TableTask.Column.TIMESTAMP)); String day = DateUtil.dateTimestamp(timestamp); String monthYear = day.substring(day.indexOf(" "), day.length()); if (!checks.contains(monthYear)) { String d = day.substring(0, day.indexOf(",")); Calendar calendar = new Calendar(); calendar.setDay(d); calendar.setDateMonthYear(monthYear); calendar.setNumTask("1"); timestamps.add(calendar); checks.add(monthYear); } else { for (int x = 0; x < timestamps.size(); x++) { Calendar cal = timestamps.get(x); String comp = cal.getDateMonthYear(); if (comp.equalsIgnoreCase(monthYear)) { int numTask = Integer.valueOf(cal.getNumTask()); cal.setNumTask(String.valueOf(++numTask)); break; } } } cursor.moveToNext(); } cursor.close(); return timestamps; } return null; } public List<Calendar> getAvailableTimestamp(ContentResolver resolver, boolean desc) { // String selection = TableTask.Column.TIMESTAMP + " > " + "\"" + // System.currentTimeMillis() + "\""; // String selection = TableTask.Column.TIMESTAMP + " > " + "\"" + String.valueOf(DateUtil.getBeginningOfday()) + "\""; String selection = null; if (desc) { return getAvailableTimestamp(resolver, getCursorDataDesc(resolver, selection)); } return getAvailableTimestamp(resolver, getCursorDataAsc(resolver, selection)); } public Task cursorToTask(Cursor cursor) { Task task = new Task(); task.setTID(cursor.getString(cursor.getColumnIndex(TableTask.Column.TID))); task.setTitle(cursor.getString(cursor.getColumnIndex(TableTask.Column.TITLE))); task.setNotes(cursor.getString(cursor.getColumnIndex(TableTask.Column.NOTES))); task.setTimestamp(cursor.getLong(cursor.getColumnIndex(TableTask.Column.TIMESTAMP))); task.setSnooze(cursor.getLong(cursor.getColumnIndex(TableTask.Column.SNOOZE))); task.setRepeat(cursor.getInt(cursor.getColumnIndex(TableTask.Column.REPEAT))); task.setType(cursor.getString(cursor.getColumnIndex(TableTask.Column.TYPE))); task.setStatus(cursor.getInt(cursor.getColumnIndex(TableTask.Column.STATUS))); task.setPath(cursor.getString(cursor.getColumnIndex(TableTask.Column.PATH))); return task; } public void insertAsync(ContentResolver resolver, Task task) { new InsertTask(resolver).execute(task); } private class InsertTask extends AsyncTask<Task, Integer, Integer> { ContentResolver mResolver = null; public InsertTask(ContentResolver resolver) { mResolver = resolver; } @Override protected Integer doInBackground(Task... task) { insert(mResolver, task[0]); return 0; } } }
{ "content_hash": "2ff8c0e41224f590e4a01ad1b9c56185", "timestamp": "", "source": "github", "line_count": 347, "max_line_length": 119, "avg_line_length": 39.42651296829971, "alnum_prop": 0.5862144580074556, "repo_name": "ferdinb/remind.me", "id": "27bed7d8e35b99dd7093a1e8a491f0a4b69a3cdb", "size": "13681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/remind/me/fninaber/db/TaskHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "174452" } ], "symlink_target": "" }
package com.billybyte.spanjava.utils; public class CmeSpanUtils { public enum RecordType { EXCHANGE_COMPLEX_HEADER("0 "), EXCHANGE_HEADER("1 "), FIRST_COMB_COMM("2 "), SECOND_COMB_COMM("3 "), THIRD_COMB_CORR("4 "), FIRST_PHYS_REC("81"), SECOND_PHYS_REC("82"), FIRST_PHYS_REC_FLOAT("83"), SECOND_PHYS_REC_FLOAT("84"), PRICE_SPECS("P "), RISK_ARRAY_PARAMS("B "), COMM_REDEF("R "), INTRA_COMM_TIERS("C "), INTRA_COMM_SERIES("E "), TIERED_SCANNED("S "), COMB_COMM_GRPS("5 "), INTER_COMM_SPREADS("6 "), PHYS_DEBT_SEC("9 "), OPT_ON_COMB("X "), DAILY_ADJ("V "), SPLIT_ALLOC("Y "), DELTA_SPLIT_ALLOC("Z "), CURR_CONV_RATE("T "); private final String recId; RecordType(String recId){ this.recId = recId; } public static String getEnumNameByValue(String value) { String enumValue = null; for(RecordType type:RecordType.values()) { if(value.compareTo(type.toString())==0){ return type.name(); } } return enumValue; } public String toString() { return this.recId; } } }
{ "content_hash": "e81b889f68085edd05f5d1c8c78301b8", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 103, "avg_line_length": 30.6, "alnum_prop": 0.6125116713352008, "repo_name": "bgithub1/span-java", "id": "bda5f40243cbde72bc4a372eb45daab46357a0fe", "size": "1071", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/billybyte/spanjava/utils/CmeSpanUtils.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1017596" }, { "name": "Shell", "bytes": "330" } ], "symlink_target": "" }
package nquads import ( "testing" . "github.com/smartystreets/goconvey/convey" "github.com/google/cayley/graph" ) func TestParsingNTriples(t *testing.T) { Convey("When parsing", t, func() { Convey("It should not parse invalid triples", func() { x := Parse("invalid") So(x, ShouldBeNil) }) Convey("It should not parse comments", func() { x := Parse("# nominally valid triple .") So(x, ShouldBeNil) }) Convey("It should parse simple triples", func() { x := Parse("this is valid .") So(x, ShouldNotBeNil) So(x.Subject, ShouldEqual, "this") }) Convey("It should parse quoted triples", func() { x := Parse("this is \"valid too\" .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "valid too") So(x.Provenance, ShouldEqual, "") }) Convey("It should parse escaped quoted triples", func() { x := Parse("he said \"\\\"That's all folks\\\"\" .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "\"That's all folks\"") So(x.Provenance, ShouldEqual, "") }) Convey("It should parse an example real triple", func() { x := Parse("\":/guid/9202a8c04000641f80000000010c843c\" \"name\" \"George Morris\" .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "George Morris") So(x.Provenance, ShouldEqual, "") }) Convey("It should parse a pathologically spaced triple", func() { x := Parse("foo is \"\\tA big tough\\r\\nDeal\\\\\" .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "\tA big tough\r\nDeal\\") So(x.Provenance, ShouldEqual, "") }) Convey("It should parse a simple quad", func() { x := Parse("this is valid quad .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "valid") So(x.Provenance, ShouldEqual, "quad") }) Convey("It should parse a quoted quad", func() { x := Parse("this is valid \"quad thing\" .") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "valid") So(x.Provenance, ShouldEqual, "quad thing") }) Convey("It should parse crazy escaped quads", func() { x := Parse("\"\\\"this\" \"\\\"is\" \"\\\"valid\" \"\\\"quad thing\".") So(x, ShouldNotBeNil) So(x.Subject, ShouldEqual, "\"this") So(x.Predicate, ShouldEqual, "\"is") So(x.Object, ShouldEqual, "\"valid") So(x.Provenance, ShouldEqual, "\"quad thing") }) }) } func TestParsingNTriplesOfficial(t *testing.T) { Convey("When using some public test cases...", t, func() { Convey("It should handle some simple cases with comments", func() { var x *graph.Triple x = Parse("<http://example/s> <http://example/p> <http://example/o> . # comment") So(x, ShouldNotBeNil) So(x.Subject, ShouldEqual, "http://example/s") So(x.Predicate, ShouldEqual, "http://example/p") So(x.Object, ShouldEqual, "http://example/o") So(x.Provenance, ShouldEqual, "") x = Parse("<http://example/s> <http://example/p> _:o . # comment") So(x, ShouldNotBeNil) So(x.Subject, ShouldEqual, "http://example/s") So(x.Predicate, ShouldEqual, "http://example/p") So(x.Object, ShouldEqual, "_:o") So(x.Provenance, ShouldEqual, "") x = Parse("<http://example/s> <http://example/p> \"o\" . # comment") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "o") So(x.Provenance, ShouldEqual, "") x = Parse("<http://example/s> <http://example/p> \"o\"^^<http://example/dt> . # comment") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "o") So(x.Provenance, ShouldEqual, "") x = Parse("<http://example/s> <http://example/p> \"o\"@en . # comment") So(x, ShouldNotBeNil) So(x.Object, ShouldEqual, "o") So(x.Provenance, ShouldEqual, "") }) }) } func BenchmarkParser(b *testing.B) { for n := 0; n < b.N; n++ { x := Parse("<http://example/s> <http://example/p> \"object of some real\\tlength\"@en . # comment") if x.Object != "object of some real\tlength" { b.Fail() } } }
{ "content_hash": "21672c13e41bd6783a2a2fc3f2f3061a", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 101, "avg_line_length": 32.76923076923077, "alnum_prop": 0.6199791340636411, "repo_name": "aarongable/cayley", "id": "a8a83bc056f1a226d275bb236038764b28322864", "size": "4452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nquads/nquads_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10498" }, { "name": "Go", "bytes": "275360" }, { "name": "JavaScript", "bytes": "25379" }, { "name": "Python", "bytes": "3624" } ], "symlink_target": "" }
package top.cardone.func.v1.authority.rolePermission; import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.gson.Gson; import top.cardone.CardoneConsumerApplication; import lombok.extern.log4j.Log4j2; import lombok.val; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.CollectionUtils; import top.cardone.context.ApplicationContextHolder; import java.util.Map; @Log4j2 @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = CardoneConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class IndexFuncTest { @Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/authority/rolePermission/index.json") private String funcUrl; @Value("file:src/test/resources/top/cardone/func/v1/authority/rolePermission/IndexFuncTest.func.input.json") private Resource funcInputResource; @Value("file:src/test/resources/top/cardone/func/v1/authority/rolePermission/IndexFuncTest.func.output.json") private Resource funcOutputResource; @Test public void func() throws Exception { if (!funcInputResource.exists()) { FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8); } val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8); Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class); Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap)); Map<String, Object> output = Maps.newLinkedHashMap(); for (val parametersEntry : parametersMap.entrySet()) { val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue()); val headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE); headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]); headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0))); val httpEntity = new HttpEntity<>(body, headers); val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class); val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class); output.put(parametersEntry.getKey(), value); } FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8); } }
{ "content_hash": "fd515cdbb82cb6ee3945f4b18267c4a3", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 193, "avg_line_length": 44.83561643835616, "alnum_prop": 0.7540482737549649, "repo_name": "yht-fand/cardone-platform-authority", "id": "74790074b60fac4e4a1c7290e2a283109a73c635", "size": "3283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "consumer-bak/src/test/java/top/cardone/func/v1/authority/rolePermission/IndexFuncTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2133" }, { "name": "FreeMarker", "bytes": "732567" }, { "name": "Java", "bytes": "367105" }, { "name": "Shell", "bytes": "2043" } ], "symlink_target": "" }
package alice.tuprolog.interfaces; import java.util.HashMap; import alice.tuprolog.OperatorManager; import alice.tuprolog.Parser; import alice.tuprolog.Term; public class ParserFactory { /** * Creating a parser with default operator interpretation */ public static IParser createParser(String theory) { return new Parser(theory); } /** * creating a parser with default operator interpretation */ public static IParser createParser(String theory, HashMap<Term, Integer> mapping) { return new Parser(theory, mapping); } /** * creating a Parser specifing how to handle operators * and what text to parse */ public static IParser createParser(IOperatorManager op, String theory) { return new Parser((OperatorManager)op, theory); } /** * creating a Parser specifing how to handle operators * and what text to parse */ public static IParser createParser(IOperatorManager op, String theory, HashMap<Term, Integer> mapping) { return new Parser((OperatorManager)op, theory, mapping); } }
{ "content_hash": "55a71d951660186790b5ad3383000ed4", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 108, "avg_line_length": 27.78048780487805, "alnum_prop": 0.6733977172958736, "repo_name": "adlange/IN2SEC", "id": "e07bfdc2554aa4132f51a294c91858ddf3e56998", "size": "1139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/dependencies/alice/tuprolog/interfaces/ParserFactory.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1171443" }, { "name": "Prolog", "bytes": "17694" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- This comment will force IE7 to go into quirks mode. --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta> <link rel="stylesheet" type="text/css" href="../../CSS/Contents.css"></link> <script type="text/javascript" src="../../JS/Common.js"></script> <title>Types&lt;K&gt; Class</title> </head> <body> <div id="Header"> <div id="ProjectTitle">Documentation Project</div> <div id="PageTitle">Types&lt;K&gt; Class</div> <div id="HeaderShortcuts"> <a href="#SectionHeader0" onclick="javascript: SetSectionVisibility(0, true); SetExpandCollapseAllToCollapseAll();">Syntax</a>&nbsp; <a href="#SectionHeader1" onclick="javascript: SetSectionVisibility(1, true); SetExpandCollapseAllToCollapseAll();">Members</a>&nbsp; </div> <div class="DarkLine"></div> <div class="LightLine"></div> <div id="HeaderToolbar"> <img id="ExpandCollapseAllImg" src="../../GFX/SmallSquareExpanded.gif" alt="" style="vertical-align: top;" onclick="javascript: ToggleAllSectionsVisibility();" /> <span id="ExpandCollapseAllSpan" onclick="javascript: ToggleAllSectionsVisibility();">Collapse All</span> </div> </div> <div id="Contents"> <a id="ContentsAnchor">&nbsp;</a> A thread-safe, user-controlled cache of types. <div id="ItemLocation"> <b>Namespace:</b> <a href="../../Contents/2/362.html">Sasa.Dynamics</a><br /> <b>Assembly:</b> <a href="../../Contents/1/5.html">Sasa.Dynamics</a> </div> <div id="SectionHeader0" class="SectionHeader"> <img id="SectionExpanderImg0" src="../../GFX/BigSquareExpanded.gif" alt="Collapse/Expand" onclick="javascript: ToggleSectionVisibility(0);" /> <span class="SectionHeader"> <span class="ArrowCursor" onclick="javascript: ToggleSectionVisibility(0);"> Syntax </span> </span> </div> <div id="SectionContainerDiv0" class="SectionContainer"> <table class="CodeTable"><col width="100%" /><tr class="CodeTable"><th class="CodeTable">C#</th></tr><tr class="CodeTable"><td class="CodeTable"><table style="width: 100%;" class="InsideCodeBlock"> <col width="0%" /> <col width="100%" /> <tr> <td class="NoWrapTop">public static class Types&lt;K&gt; </td> <td>&nbsp;</td> </tr> </table> </td></tr></table> <div class="CommentHeader">Type Parameters</div> <div class="CommentParameterName">K</div> <div class="ParameterCommentContainer"> The key to map to types. </div> <div class="TopLink"><a href="#ContentsAnchor">Top</a></div></div> <div id="SectionHeader1" class="SectionHeader"> <img id="SectionExpanderImg1" src="../../GFX/BigSquareExpanded.gif" alt="Collapse/Expand" onclick="javascript: ToggleSectionVisibility(1);" /> <span class="SectionHeader"> <span class="ArrowCursor" onclick="javascript: ToggleSectionVisibility(1);"> Members </span> </span> </div> <div id="SectionContainerDiv1" class="SectionContainer"> <p>Click <a href="../../Contents/2/378.html">here</a> to see the list of members.</p> <div class="TopLink"><a href="#ContentsAnchor">Top</a></div></div> </div> <div id="Footer"> <span class="Footer">Generated by <a href="http://immdocnet.codeplex.com/" target="_blank">ImmDoc .NET</a></span>. </div> </body> </html>
{ "content_hash": "339d7e1ed0c7a3e3d46538e555a76ebd", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 197, "avg_line_length": 43.64935064935065, "alnum_prop": 0.6902707527521571, "repo_name": "fschwiet/ManyConsole", "id": "3eac8f093672b43f42a360a3ed5dbbf1ad7601af", "size": "3361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Sasa-v0.9.3-docs/Contents/2/366.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "75286" }, { "name": "CSS", "bytes": "13108" }, { "name": "HTML", "bytes": "4589763" }, { "name": "JavaScript", "bytes": "14766" }, { "name": "PowerShell", "bytes": "10774" } ], "symlink_target": "" }
'use strict'; module.exports = function(grunt) { var regex = /background[-image]*:.*?url\(([^\)]+)/g; /** * Parse a CSS file to find `background` and `background-image` URL's */ var getFileUrls = function(input) { var match, urls = []; while ((match = regex.exec(input)) !== null) { var str = match[1]; if(typeof str === 'string') { // Trim and remove quote marks before pushing it urls.push(str.trim().replace(/["']/g, "")); } } return urls; }; /** * Generate body:after containing url to preload */ var generateCssPreloader = function(urls) { var wrappedUrls = urls.map(function(url) { return 'url(' + url + ')'; }); return "body:after {\n\tdisplay: none;\n\tcontent: " + wrappedUrls.join(' ') + ";\n}"; }; /** * Grunt task */ grunt.registerMultiTask('img_preload', 'Preload images with CSS2 body:after', function() { var options = this.options({ append: false, urls: [] }); if(!(options.urls instanceof Object)) { grunt.fail.warn('`urls` option must be an Array'); } this.files.forEach(function(f) { // URL's to preload. var urls = options.urls; // Files processing. Searching images url's. f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).forEach(function(file) { var newUrls = getFileUrls(grunt.file.read(file)); urls = urls.concat(newUrls); }); // Dedup urls = grunt.util._.uniq(urls); if(urls.length > 0) { var content = ''; // With append mode (get file content). if(grunt.file.exists(f.dest) && options.append) { content += grunt.file.read(f.dest) + "\n\n"; } // Preloader block and write. content += generateCssPreloader(urls); grunt.file.write(f.dest, content); grunt.log.ok('File "' + f.dest + '" created with ' + urls.length + ' url\'s to preload.'); } else { grunt.log.warn('No URL\'s found.'); } }); }); };
{ "content_hash": "df0061ef84e756cb7652c09d39791998", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 98, "avg_line_length": 22.900990099009903, "alnum_prop": 0.5438824038045827, "repo_name": "juherpin/grunt-img-preload", "id": "bbd1f0005118367b981d403c9cef018c1279f434", "size": "2458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tasks/imgpreload.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6569" } ], "symlink_target": "" }
<?php defined('SYSPATH') or die ('no tiene acceso'); //descripcion del modelo productos class Model_Archivados extends ORM{ protected $_table_names_plural = false; //protected $_sorting = array('fecha_publicacion' => 'DESC'); //archivar una hoja de ruta public function archivar($id_nuri,$id_user,$id_carpeta,$fecha){ $archivo=ORM::factory('archivados'); $archivo->id_nuri=$id_nuri; $archivo->id_user=$id_user; $archivo->id_carpeta=$id_carpeta; $archivo->fecha=$fecha; return $archivo->save(); } public function carpeta($id_carpeta,$id_oficina) { $sql="SELECT s.id as id_seg,a.id_user, a.observaciones, s.id_archivo, c.carpeta, s.accion,s.oficial,s.de_oficina, s.proveido, a.fecha as fecha_archivo, d.id as id_doc, d.nur, d.codigo,d.referencia FROM seguimiento s INNER JOIN archivados a ON a.id=s.id_archivo INNER JOIN carpetas c ON a.id_carpeta=c.id INNER JOIN documentos d ON d.nur=s.nur WHERE s.estado='10' AND c.id='$id_carpeta' AND d.original='1' AND s.derivado_a='$id_oficina'"; return db::query(Database::SELECT, $sql)->execute(); } } ?>
{ "content_hash": "c70d04b5abb7d480326900649d2aaa96", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 204, "avg_line_length": 40.225806451612904, "alnum_prop": 0.6062550120288693, "repo_name": "fredd-for/codice", "id": "fcab5f9c303f93eddaf9868fd71ef355242e69a2", "size": "1247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/classes/model/archivados.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "46548" }, { "name": "JavaScript", "bytes": "3835759" }, { "name": "PHP", "bytes": "33896982" }, { "name": "Shell", "bytes": "248" } ], "symlink_target": "" }
package org.apache.camel.core.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import org.apache.camel.model.IdentifiedType; import org.apache.camel.util.CollectionStringBuffer; /** * The JAXB type class for the configuration of jmxAgent * * @version */ @XmlRootElement(name = "jmxAgent") @XmlAccessorType(XmlAccessType.FIELD) public class CamelJMXAgentDefinition extends IdentifiedType { /** * Disable JMI (default false) */ @XmlAttribute private String disabled; /** * Only register processor if a custom id was defined for it. */ @XmlAttribute private String onlyRegisterProcessorWithCustomId; /** * RMI connector registry port (default 1099) */ @XmlAttribute private String registryPort; /** * RMI connector server port (default -1 not used) */ @XmlAttribute private String connectorPort; /** * MBean server default domain name (default org.apache.camel) */ @XmlAttribute private String mbeanServerDefaultDomain; /** * MBean object domain name (default org.apache.camel) */ @XmlAttribute private String mbeanObjectDomainName; /** * JMX Service URL path (default /jmxrmi) */ @XmlAttribute private String serviceUrlPath; /** * A flag that indicates whether the agent should be created */ @XmlAttribute private String createConnector; /** * A flag that indicates whether the platform mbean server should be used */ @XmlAttribute private String usePlatformMBeanServer; /** * A flag that indicates whether to register mbeans always */ @XmlAttribute private String registerAlways; /** * A flag that indicates whether to register mbeans when starting new routes */ @XmlAttribute private String registerNewRoutes; /** * Level of granularity for performance statistics enabled */ @XmlAttribute private String statisticsLevel; /** * A flag that indicates whether Load statistics is enabled */ @XmlAttribute private String loadStatisticsEnabled; /** * A flag that indicates whether endpoint runtime statistics is enabled */ @XmlAttribute private String endpointRuntimeStatisticsEnabled; /** * A flag that indicates whether to include hostname in JMX MBean names. */ @XmlAttribute private String includeHostName; /** * A flag that indicates whether to remove detected sensitive information (such as passwords) from MBean names and attributes. */ @XmlAttribute private String mask; public String getDisabled() { return disabled; } public void setDisabled(String disabled) { this.disabled = disabled; } public String getOnlyRegisterProcessorWithCustomId() { return onlyRegisterProcessorWithCustomId; } public void setOnlyRegisterProcessorWithCustomId(String onlyRegisterProcessorWithCustomId) { this.onlyRegisterProcessorWithCustomId = onlyRegisterProcessorWithCustomId; } public String getRegistryPort() { return registryPort; } public void setRegistryPort(String registryPort) { this.registryPort = registryPort; } public String getConnectorPort() { return connectorPort; } public void setConnectorPort(String connectorPort) { this.connectorPort = connectorPort; } public String getMbeanServerDefaultDomain() { return mbeanServerDefaultDomain; } public void setMbeanServerDefaultDomain(String mbeanServerDefaultDomain) { this.mbeanServerDefaultDomain = mbeanServerDefaultDomain; } public String getMbeanObjectDomainName() { return mbeanObjectDomainName; } public void setMbeanObjectDomainName(String mbeanObjectDomainName) { this.mbeanObjectDomainName = mbeanObjectDomainName; } public String getServiceUrlPath() { return serviceUrlPath; } public void setServiceUrlPath(String serviceUrlPath) { this.serviceUrlPath = serviceUrlPath; } public String getCreateConnector() { return createConnector; } public void setCreateConnector(String createConnector) { this.createConnector = createConnector; } public String getUsePlatformMBeanServer() { return usePlatformMBeanServer; } public void setUsePlatformMBeanServer(String usePlatformMBeanServer) { this.usePlatformMBeanServer = usePlatformMBeanServer; } public String getStatisticsLevel() { return statisticsLevel; } public void setStatisticsLevel(String statisticsLevel) { this.statisticsLevel = statisticsLevel; } public String getRegisterAlways() { return registerAlways; } public void setRegisterAlways(String registerAlways) { this.registerAlways = registerAlways; } public String getRegisterNewRoutes() { return registerNewRoutes; } public void setRegisterNewRoutes(String registerNewRoutes) { this.registerNewRoutes = registerNewRoutes; } public String getLoadStatisticsEnabled() { return loadStatisticsEnabled; } public void setLoadStatisticsEnabled(String loadStatisticsEnabled) { this.loadStatisticsEnabled = loadStatisticsEnabled; } public String getEndpointRuntimeStatisticsEnabled() { return endpointRuntimeStatisticsEnabled; } public void setEndpointRuntimeStatisticsEnabled(String endpointRuntimeStatisticsEnabled) { this.endpointRuntimeStatisticsEnabled = endpointRuntimeStatisticsEnabled; } public String getIncludeHostName() { return includeHostName; } public void setIncludeHostName(String includeHostName) { this.includeHostName = includeHostName; } public String getMask() { return mask; } public void setMask(String mask) { this.mask = mask; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("CamelJMXAgent["); CollectionStringBuffer csb = new CollectionStringBuffer(); if (disabled != null) { csb.append("disabled=" + disabled); } if (usePlatformMBeanServer != null) { csb.append("usePlatformMBeanServer=" + usePlatformMBeanServer); } if (createConnector != null) { csb.append("createConnector=" + createConnector); } if (connectorPort != null) { csb.append("connectorPort=" + connectorPort); } if (registryPort != null) { csb.append("registryPort=" + registryPort); } if (serviceUrlPath != null) { csb.append("serviceUrlPath=" + serviceUrlPath); } if (mbeanServerDefaultDomain != null) { csb.append("mbeanServerDefaultDomain=" + mbeanServerDefaultDomain); } if (mbeanObjectDomainName != null) { csb.append("mbeanObjectDomainName=" + mbeanObjectDomainName); } if (statisticsLevel != null) { csb.append("statisticsLevel=" + statisticsLevel); } if (loadStatisticsEnabled != null) { csb.append("loadStatisticsEnabled=" + loadStatisticsEnabled); } if (endpointRuntimeStatisticsEnabled != null) { csb.append("endpointRuntimeStatisticsEnabled=" + endpointRuntimeStatisticsEnabled); } if (onlyRegisterProcessorWithCustomId != null) { csb.append("onlyRegisterProcessorWithCustomId=" + onlyRegisterProcessorWithCustomId); } if (registerAlways != null) { csb.append("registerAlways=" + registerAlways); } if (registerNewRoutes != null) { csb.append("registerNewRoutes=" + registerNewRoutes); } if (includeHostName != null) { csb.append("includeHostName=" + includeHostName); } if (mask != null) { csb.append("mask=" + mask); } sb.append(csb.toString()); sb.append("]"); return sb.toString(); } }
{ "content_hash": "0f885417bb887ce27c18c9b1351813ff", "timestamp": "", "source": "github", "line_count": 305, "max_line_length": 130, "avg_line_length": 27.439344262295084, "alnum_prop": 0.6638785995937388, "repo_name": "mnki/camel", "id": "b4ce31bfb016fd4191ad39dfdc056fe4bcd6a3d8", "size": "9172", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "components/camel-core-xml/src/main/java/org/apache/camel/core/xml/CamelJMXAgentDefinition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "106" }, { "name": "CSS", "bytes": "18641" }, { "name": "Eagle", "bytes": "2898" }, { "name": "Elm", "bytes": "5970" }, { "name": "Groovy", "bytes": "40961" }, { "name": "HTML", "bytes": "193182" }, { "name": "Java", "bytes": "47209328" }, { "name": "JavaScript", "bytes": "88124" }, { "name": "Protocol Buffer", "bytes": "578" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "321075" }, { "name": "Shell", "bytes": "12824" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "1483" }, { "name": "XSLT", "bytes": "284036" } ], "symlink_target": "" }
macro(linkCocoa targetName) find_library(COCOA_LIB Cocoa) target_link_libraries(${targetName} ${COCOA_LIB}) endmacro(linkCocoa)
{ "content_hash": "e8a892c50f28603330d3f82b9542b5f2", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 50, "avg_line_length": 32.5, "alnum_prop": 0.7846153846153846, "repo_name": "ClubOfDigitalEngineering/CMakeTemplate", "id": "de9f2cd8939fbe676a773344a284399ed4ace0ad", "size": "130", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CMakeMacros/Cocoa/Link.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "CMake", "bytes": "29726" } ], "symlink_target": "" }
/* * Ring initialization rules: * 1. Each segment is initialized to zero, except for link TRBs. * 2. Ring cycle state = 0. This represents Producer Cycle State (PCS) or * Consumer Cycle State (CCS), depending on ring function. * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment. * * Ring behavior rules: * 1. A ring is empty if enqueue == dequeue. This means there will always be at * least one free TRB in the ring. This is useful if you want to turn that * into a link TRB and expand the ring. * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a * link TRB, then load the pointer with the address in the link TRB. If the * link TRB had its toggle bit set, you may need to update the ring cycle * state (see cycle bit rules). You may have to do this multiple times * until you reach a non-link TRB. * 3. A ring is full if enqueue++ (for the definition of increment above) * equals the dequeue pointer. * * Cycle bit rules: * 1. When a consumer increments a dequeue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * 2. When a producer increments an enqueue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * * Producer rules: * 1. Check if ring is full before you enqueue. * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing. * Update enqueue pointer between each write (which may update the ring * cycle state). * 3. Notify consumer. If SW is producer, it rings the doorbell for command * and endpoint rings. If HC is the producer for the event ring, * and it generates an interrupt according to interrupt modulation rules. * * Consumer rules: * 1. Check if TRB belongs to you. If the cycle bit == your ring cycle state, * the TRB is owned by the consumer. * 2. Update dequeue pointer (which may update the ring cycle state) and * continue processing TRBs until you reach a TRB which is not owned by you. * 3. Notify the producer. SW is the consumer for the event ring, and it * updates event ring dequeue pointer. HC is the consumer for the command and * endpoint rings; it generates events on the event ring for these. */ #include <linux/scatterlist.h> #include <linux/slab.h> #include "xhci.h" static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA * address of the TRB. */ dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg, union xhci_trb *trb) { unsigned long segment_offset; if (!seg || !trb || trb < seg->trbs) return 0; /* offset in TRBs */ segment_offset = trb - seg->trbs; if (segment_offset > TRBS_PER_SEGMENT) return 0; return seg->dma + (segment_offset * sizeof(*trb)); } /* Does this link TRB point to the first segment in a ring, * or was the previous TRB the last TRB on the last segment in the ERST? */ static bool last_trb_on_last_seg(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return (trb == &seg->trbs[TRBS_PER_SEGMENT]) && (seg->next == xhci->event_ring->first_seg); else return le32_to_cpu(trb->link.control) & LINK_TOGGLE; } /* Is this TRB a link TRB or was the last TRB the last TRB in this event ring * segment? I.e. would the updated event TRB pointer step off the end of the * event seg? */ static int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return trb == &seg->trbs[TRBS_PER_SEGMENT]; else return TRB_TYPE_LINK_LE32(trb->link.control); } static int enqueue_is_link_trb(struct xhci_ring *ring) { struct xhci_link_trb *link = &ring->enqueue->link; return TRB_TYPE_LINK_LE32(link->control); } /* Updates trb to point to the next TRB in the ring, and updates seg if the next * TRB is in a new segment. This does not skip over link TRBs, and it does not * effect the ring dequeue or enqueue pointers. */ static void next_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment **seg, union xhci_trb **trb) { if (last_trb(xhci, ring, *seg, *trb)) { *seg = (*seg)->next; *trb = ((*seg)->trbs); } else { (*trb)++; } } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. */ static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring) { unsigned long long addr; ring->deq_updates++; /* * If this is not event ring, and the dequeue pointer * is not on a link TRB, there is one more usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->deq_seg, ring->dequeue)) ring->num_trbs_free++; do { /* * Update the dequeue pointer further if that was a link TRB or * we're at the end of an event ring segment (which doesn't have * link TRBS) */ if (last_trb(xhci, ring, ring->deq_seg, ring->dequeue)) { if (ring->type == TYPE_EVENT && last_trb_on_last_seg(xhci, ring, ring->deq_seg, ring->dequeue)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->deq_seg = ring->deq_seg->next; ring->dequeue = ring->deq_seg->trbs; } else { ring->dequeue++; } } while (last_trb(xhci, ring, ring->deq_seg, ring->dequeue)); addr = (unsigned long long) xhci_trb_virt_to_dma(ring->deq_seg, ring->dequeue); } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. * * If we've just enqueued a TRB that is in the middle of a TD (meaning the * chain bit is set), then set the chain bit in all the following link TRBs. * If we've enqueued the last TRB in a TD, make sure the following link TRBs * have their chain bit cleared (so that each Link TRB is a separate TD). * * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit * set, but other sections talk about dealing with the chain bit set. This was * fixed in the 0.96 specification errata, but we have to assume that all 0.95 * xHCI hardware can't handle the chain bit being cleared on a link TRB. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming) { u32 chain; union xhci_trb *next; unsigned long long addr; chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN; /* If this is not event ring, there is one less usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->enq_seg, ring->enqueue)) ring->num_trbs_free--; next = ++(ring->enqueue); ring->enq_updates++; /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->enq_seg, next)) { if (ring->type != TYPE_EVENT) { /* * If the caller doesn't plan on enqueueing more * TDs before ringing the doorbell, then we * don't want to give the link TRB to the * hardware just yet. We'll give the link TRB * back in prepare_ring() just before we enqueue * the TD at the top of the ring. */ if (!chain && !more_trbs_coming) break; /* If we're not dealing with 0.95 hardware or * isoc rings on AMD 0.96 host, * carry over the chain bit of the previous TRB * (which may mean the chain bit is cleared). */ if (!(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST)) && !xhci_link_trb_quirk(xhci)) { next->link.control &= cpu_to_le32(~TRB_CHAIN); next->link.control |= cpu_to_le32(chain); } /* Give this link TRB to the hardware */ wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } addr = (unsigned long long) xhci_trb_virt_to_dma(ring->enq_seg, ring->enqueue); } /* * Check to see if there's room to enqueue num_trbs on the ring and make sure * enqueue pointer will not advance into dequeue segment. See rules above. */ static inline int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring, unsigned int num_trbs) { int num_trbs_in_deq_seg; if (ring->num_trbs_free < num_trbs) return 0; if (ring->type != TYPE_COMMAND && ring->type != TYPE_EVENT) { num_trbs_in_deq_seg = ring->dequeue - ring->deq_seg->trbs; if (ring->num_trbs_free < num_trbs + num_trbs_in_deq_seg) return 0; } return 1; } /* Ring the host controller doorbell after placing a command on the ring */ void xhci_ring_cmd_db(struct xhci_hcd *xhci) { if (!(xhci->cmd_ring_state & CMD_RING_STATE_RUNNING)) return; xhci_dbg(xhci, "// Ding dong!\n"); xhci_writel(xhci, DB_VALUE_HOST, &xhci->dba->doorbell[0]); /* Flush PCI posted writes */ xhci_readl(xhci, &xhci->dba->doorbell[0]); } static int xhci_abort_cmd_ring(struct xhci_hcd *xhci) { u64 temp_64; int ret; xhci_dbg(xhci, "Abort command ring\n"); if (!(xhci->cmd_ring_state & CMD_RING_STATE_RUNNING)) { xhci_dbg(xhci, "The command ring isn't running, " "Have the command ring been stopped?\n"); return 0; } temp_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring); if (!(temp_64 & CMD_RING_RUNNING)) { xhci_dbg(xhci, "Command ring had been stopped\n"); return 0; } xhci->cmd_ring_state = CMD_RING_STATE_ABORTED; xhci_write_64(xhci, temp_64 | CMD_RING_ABORT, &xhci->op_regs->cmd_ring); /* Section 4.6.1.2 of xHCI 1.0 spec says software should * time the completion od all xHCI commands, including * the Command Abort operation. If software doesn't see * CRR negated in a timely manner (e.g. longer than 5 * seconds), then it should assume that the there are * larger problems with the xHC and assert HCRST. */ ret = handshake(xhci, &xhci->op_regs->cmd_ring, CMD_RING_RUNNING, 0, 5 * 1000 * 1000); if (ret < 0) { xhci_err(xhci, "Stopped the command ring failed, " "maybe the host is dead\n"); xhci->xhc_state |= XHCI_STATE_DYING; xhci_quiesce(xhci); xhci_halt(xhci); return -ESHUTDOWN; } return 0; } static int xhci_queue_cd(struct xhci_hcd *xhci, struct xhci_command *command, union xhci_trb *cmd_trb) { struct xhci_cd *cd; cd = kzalloc(sizeof(struct xhci_cd), GFP_ATOMIC); if (!cd) return -ENOMEM; INIT_LIST_HEAD(&cd->cancel_cmd_list); cd->command = command; cd->cmd_trb = cmd_trb; list_add_tail(&cd->cancel_cmd_list, &xhci->cancel_cmd_list); return 0; } /* * Cancel the command which has issue. * * Some commands may hang due to waiting for acknowledgement from * usb device. It is outside of the xHC's ability to control and * will cause the command ring is blocked. When it occurs software * should intervene to recover the command ring. * See Section 4.6.1.1 and 4.6.1.2 */ int xhci_cancel_cmd(struct xhci_hcd *xhci, struct xhci_command *command, union xhci_trb *cmd_trb) { int retval = 0; unsigned long flags; spin_lock_irqsave(&xhci->lock, flags); if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_warn(xhci, "Abort the command ring," " but the xHCI is dead.\n"); retval = -ESHUTDOWN; goto fail; } /* queue the cmd desriptor to cancel_cmd_list */ retval = xhci_queue_cd(xhci, command, cmd_trb); if (retval) { xhci_warn(xhci, "Queuing command descriptor failed.\n"); goto fail; } /* abort command ring */ retval = xhci_abort_cmd_ring(xhci); if (retval) { xhci_err(xhci, "Abort command ring failed\n"); if (unlikely(retval == -ESHUTDOWN)) { spin_unlock_irqrestore(&xhci->lock, flags); usb_hc_died(xhci_to_hcd(xhci)->primary_hcd); xhci_dbg(xhci, "xHCI host controller is dead.\n"); return retval; } } fail: spin_unlock_irqrestore(&xhci->lock, flags); return retval; } void xhci_ring_ep_doorbell(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id]; struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; unsigned int ep_state = ep->ep_state; /* Don't ring the doorbell for this endpoint if there are pending * cancellations because we don't want to interrupt processing. * We don't want to restart any stream rings if there's a set dequeue * pointer command pending because the device can choose to start any * stream once the endpoint is on the HW schedule. * FIXME - check all the stream rings for pending cancellations. */ if ((ep_state & EP_HALT_PENDING) || (ep_state & SET_DEQ_PENDING) || (ep_state & EP_HALTED)) return; xhci_writel(xhci, DB_VALUE(ep_index, stream_id), db_addr); /* The CPU has better things to do at this point than wait for a * write-posting flush. It'll get there soon enough. */ } /* Ring the doorbell for any rings with pending URBs */ static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index) { unsigned int stream_id; struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* A ring has pending URBs if its TD list is not empty */ if (!(ep->ep_state & EP_HAS_STREAMS)) { if (!(list_empty(&ep->ring->td_list))) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0); return; } for (stream_id = 1; stream_id < ep->stream_info->num_streams; stream_id++) { struct xhci_stream_info *stream_info = ep->stream_info; if (!list_empty(&stream_info->stream_rings[stream_id]->td_list)) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } } /* * Find the segment that trb is in. Start searching in start_seg. * If we must move past a segment that has a link TRB with a toggle cycle state * bit set, then we will toggle the value pointed at by cycle_state. */ static struct xhci_segment *find_trb_seg( struct xhci_segment *start_seg, union xhci_trb *trb, int *cycle_state) { struct xhci_segment *cur_seg = start_seg; struct xhci_generic_trb *generic_trb; while (cur_seg->trbs > trb || &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) { generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic; if (generic_trb->field[3] & cpu_to_le32(LINK_TOGGLE)) *cycle_state ^= 0x1; cur_seg = cur_seg->next; if (cur_seg == start_seg) /* Looped over the entire list. Oops! */ return NULL; } return cur_seg; } static struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* Common case: no streams */ if (!(ep->ep_state & EP_HAS_STREAMS)) return ep->ring; if (stream_id == 0) { xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has streams, " "but URB has no stream ID.\n", slot_id, ep_index); return NULL; } if (stream_id < ep->stream_info->num_streams) return ep->stream_info->stream_rings[stream_id]; xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has " "stream IDs 1 to %u allocated, " "but stream ID %u is requested.\n", slot_id, ep_index, ep->stream_info->num_streams - 1, stream_id); return NULL; } /* Get the right ring for the given URB. * If the endpoint supports streams, boundary check the URB's stream ID. * If the endpoint doesn't support streams, return the singular endpoint ring. */ static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci, struct urb *urb) { return xhci_triad_to_transfer_ring(xhci, urb->dev->slot_id, xhci_get_endpoint_index(&urb->ep->desc), urb->stream_id); } /* * Move the xHC's endpoint ring dequeue pointer past cur_td. * Record the new state of the xHC's endpoint ring dequeue segment, * dequeue pointer, and new consumer cycle state in state. * Update our internal representation of the ring's dequeue pointer. * * We do this in three jumps: * - First we update our new ring state to be the same as when the xHC stopped. * - Then we traverse the ring to find the segment that contains * the last TRB in the TD. We toggle the xHC's new cycle state when we pass * any link TRBs with the toggle cycle bit set. * - Finally we move the dequeue state one TRB further, toggling the cycle bit * if we've moved it past a link TRB with the toggle cycle bit set. * * Some of the uses of xhci_generic_trb are grotty, but if they're done * with correct __le32 accesses they should work fine. Only users of this are * in here. */ void xhci_find_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *cur_td, struct xhci_dequeue_state *state) { struct xhci_virt_device *dev = xhci->devs[slot_id]; struct xhci_ring *ep_ring; struct xhci_generic_trb *trb; struct xhci_ep_ctx *ep_ctx; dma_addr_t addr; ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN can't find new dequeue state " "for invalid stream ID %u.\n", stream_id); return; } state->new_cycle_state = 0; xhci_dbg(xhci, "Finding segment containing stopped TRB.\n"); state->new_deq_seg = find_trb_seg(cur_td->start_seg, dev->eps[ep_index].stopped_trb, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } /* Dig out the cycle state saved by the xHC during the stop ep cmd */ xhci_dbg(xhci, "Finding endpoint context\n"); ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); state->new_cycle_state = 0x1 & le64_to_cpu(ep_ctx->deq); state->new_deq_ptr = cur_td->last_trb; xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n"); state->new_deq_seg = find_trb_seg(state->new_deq_seg, state->new_deq_ptr, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } trb = &state->new_deq_ptr->generic; if (TRB_TYPE_LINK_LE32(trb->field[3]) && (trb->field[3] & cpu_to_le32(LINK_TOGGLE))) state->new_cycle_state ^= 0x1; next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr); /* * If there is only one segment in a ring, find_trb_seg()'s while loop * will not run, and it will return before it has a chance to see if it * needs to toggle the cycle bit. It can't tell if the stalled transfer * ended just before the link TRB on a one-segment ring, or if the TD * wrapped around the top of the ring, because it doesn't have the TD in * question. Look for the one-segment case where stalled TRB's address * is greater than the new dequeue pointer address. */ if (ep_ring->first_seg == ep_ring->first_seg->next && state->new_deq_ptr < dev->eps[ep_index].stopped_trb) state->new_cycle_state ^= 0x1; xhci_dbg(xhci, "Cycle state = 0x%x\n", state->new_cycle_state); /* Don't update the ring cycle state for the producer (us). */ xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n", state->new_deq_seg); addr = xhci_trb_virt_to_dma(state->new_deq_seg, state->new_deq_ptr); xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n", (unsigned long long) addr); } /* flip_cycle means flip the cycle bit of all but the first and last TRB. * (The last TRB actually points to the ring enqueue pointer, which is not part * of this TD.) This is used to remove partially enqueued isoc TDs from a ring. */ static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, struct xhci_td *cur_td, bool flip_cycle) { struct xhci_segment *cur_seg; union xhci_trb *cur_trb; for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb; true; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) { /* Unchain any chained Link TRBs, but * leave the pointers intact. */ cur_trb->generic.field[3] &= cpu_to_le32(~TRB_CHAIN); /* Flip the cycle bit (link TRBs can't be the first * or last TRB). */ if (flip_cycle) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); xhci_dbg(xhci, "Cancel (unchain) link TRB\n"); xhci_dbg(xhci, "Address = %p (0x%llx dma); " "in seg %p (0x%llx dma)\n", cur_trb, (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb), cur_seg, (unsigned long long)cur_seg->dma); } else { cur_trb->generic.field[0] = 0; cur_trb->generic.field[1] = 0; cur_trb->generic.field[2] = 0; /* Preserve only the cycle bit of this TRB */ cur_trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE); /* Flip the cycle bit except on the first or last TRB */ if (flip_cycle && cur_trb != cur_td->first_trb && cur_trb != cur_td->last_trb) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); cur_trb->generic.field[3] |= cpu_to_le32( TRB_TYPE(TRB_TR_NOOP)); xhci_dbg(xhci, "TRB to noop at offset 0x%llx\n", (unsigned long long) xhci_trb_virt_to_dma(cur_seg, cur_trb)); } if (cur_trb == cur_td->last_trb) break; } } static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state); void xhci_queue_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_dequeue_state *deq_state) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), " "new deq ptr = %p (0x%llx dma), new cycle = %u\n", deq_state->new_deq_seg, (unsigned long long)deq_state->new_deq_seg->dma, deq_state->new_deq_ptr, (unsigned long long)xhci_trb_virt_to_dma(deq_state->new_deq_seg, deq_state->new_deq_ptr), deq_state->new_cycle_state); queue_set_tr_deq(xhci, slot_id, ep_index, stream_id, deq_state->new_deq_seg, deq_state->new_deq_ptr, (u32) deq_state->new_cycle_state); /* Stop the TD queueing code from ringing the doorbell until * this command completes. The HC won't set the dequeue pointer * if the ring is running, and ringing the doorbell starts the * ring running. */ ep->ep_state |= SET_DEQ_PENDING; } static void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci, struct xhci_virt_ep *ep) { ep->ep_state &= ~EP_HALT_PENDING; /* Can't del_timer_sync in interrupt, so we attempt to cancel. If the * timer is running on another CPU, we don't decrement stop_cmds_pending * (since we didn't successfully stop the watchdog timer). */ if (del_timer(&ep->stop_cmd_timer)) ep->stop_cmds_pending--; } /* Must be called with xhci->lock held in interrupt context */ static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci, struct xhci_td *cur_td, int status, char *adjective) { struct usb_hcd *hcd; struct urb *urb; struct urb_priv *urb_priv; urb = cur_td->urb; urb_priv = urb->hcpriv; urb_priv->td_cnt++; hcd = bus_to_hcd(urb->dev->bus); /* Only giveback urb when this is the last td in urb */ if (urb_priv->td_cnt == urb_priv->length) { if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } usb_hcd_unlink_urb_from_ep(hcd, urb); spin_unlock(&xhci->lock); usb_hcd_giveback_urb(hcd, urb, status); xhci_urb_free_priv(xhci, urb_priv); spin_lock(&xhci->lock); } } /* * When we get a command completion for a Stop Endpoint Command, we need to * unlink any cancelled TDs from the ring. There are two ways to do that: * * 1. If the HW was in the middle of processing the TD that needs to be * cancelled, then we must move the ring's dequeue pointer past the last TRB * in the TD with a Set Dequeue Pointer Command. * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain * bit cleared) so that the HW will skip over them. */ static void handle_stopped_endpoint(struct xhci_hcd *xhci, union xhci_trb *trb, struct xhci_event_cmd *event) { unsigned int slot_id; unsigned int ep_index; struct xhci_virt_device *virt_dev; struct xhci_ring *ep_ring; struct xhci_virt_ep *ep; struct list_head *entry; struct xhci_td *cur_td = NULL; struct xhci_td *last_unlinked_td; struct xhci_dequeue_state deq_state; if (unlikely(TRB_TO_SUSPEND_PORT( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])))) { slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Stop endpoint command " "completion for disabled slot %u\n", slot_id); return; } memset(&deq_state, 0, sizeof(deq_state)); slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); ep = &xhci->devs[slot_id]->eps[ep_index]; if (list_empty(&ep->cancelled_td_list)) { xhci_stop_watchdog_timer_in_irq(xhci, ep); ep->stopped_td = NULL; ep->stopped_trb = NULL; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); return; } /* Fix up the ep ring first, so HW stops executing cancelled TDs. * We have the xHCI lock, so nothing can modify this list until we drop * it. We're also in the event handler, so we can't get re-interrupted * if another Stop Endpoint command completes */ list_for_each(entry, &ep->cancelled_td_list) { cur_td = list_entry(entry, struct xhci_td, cancelled_td_list); xhci_dbg(xhci, "Removing canceled TD starting at 0x%llx (dma).\n", (unsigned long long)xhci_trb_virt_to_dma( cur_td->start_seg, cur_td->first_trb)); ep_ring = xhci_urb_to_transfer_ring(xhci, cur_td->urb); if (!ep_ring) { /* This shouldn't happen unless a driver is mucking * with the stream ID after submission. This will * leave the TD on the hardware ring, and the hardware * will try to execute it, and may access a buffer * that has already been freed. In the best case, the * hardware will execute it, and the event handler will * ignore the completion event for that TD, since it was * removed from the td_list for that endpoint. In * short, don't muck with the stream ID after * submission. */ xhci_warn(xhci, "WARN Cancelled URB %p " "has invalid stream ID %u.\n", cur_td->urb, cur_td->urb->stream_id); goto remove_finished_td; } /* * If we stopped on the TD we need to cancel, then we have to * move the xHC endpoint ring dequeue pointer past this TD. */ if (cur_td == ep->stopped_td) xhci_find_new_dequeue_state(xhci, slot_id, ep_index, cur_td->urb->stream_id, cur_td, &deq_state); else td_to_noop(xhci, ep_ring, cur_td, false); remove_finished_td: /* * The event handler won't see a completion for this TD anymore, * so remove it from the endpoint ring's TD list. Keep it in * the cancelled TD list for URB completion later. */ list_del_init(&cur_td->td_list); } last_unlinked_td = cur_td; xhci_stop_watchdog_timer_in_irq(xhci, ep); /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */ if (deq_state.new_deq_ptr && deq_state.new_deq_seg) { xhci_queue_new_dequeue_state(xhci, slot_id, ep_index, ep->stopped_td->urb->stream_id, &deq_state); xhci_ring_cmd_db(xhci); } else { /* Otherwise ring the doorbell(s) to restart queued transfers */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } ep->stopped_td = NULL; ep->stopped_trb = NULL; /* * Drop the lock and complete the URBs in the cancelled TD list. * New TDs to be cancelled might be added to the end of the list before * we can complete all the URBs for the TDs we already unlinked. * So stop when we've completed the URB for the last TD we unlinked. */ do { cur_td = list_entry(ep->cancelled_td_list.next, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); /* Clean up the cancelled URB */ /* Doesn't matter what we pass for status, since the core will * just overwrite it (because the URB has been unlinked). */ xhci_giveback_urb_in_irq(xhci, cur_td, 0, "cancelled"); /* Stop processing the cancelled list if the watchdog timer is * running. */ if (xhci->xhc_state & XHCI_STATE_DYING) return; } while (cur_td != last_unlinked_td); /* Return to the event handler with xhci->lock re-acquired */ } /* Watchdog timer function for when a stop endpoint command fails to complete. * In this case, we assume the host controller is broken or dying or dead. The * host may still be completing some other events, so we have to be careful to * let the event ring handler and the URB dequeueing/enqueueing functions know * through xhci->state. * * The timer may also fire if the host takes a very long time to respond to the * command, and the stop endpoint command completion handler cannot delete the * timer before the timer function is called. Another endpoint cancellation may * sneak in before the timer function can grab the lock, and that may queue * another stop endpoint command and add the timer back. So we cannot use a * simple flag to say whether there is a pending stop endpoint command for a * particular endpoint. * * Instead we use a combination of that flag and a counter for the number of * pending stop endpoint commands. If the timer is the tail end of the last * stop endpoint command, and the endpoint's command is still pending, we assume * the host is dying. */ void xhci_stop_endpoint_command_watchdog(unsigned long arg) { struct xhci_hcd *xhci; struct xhci_virt_ep *ep; struct xhci_virt_ep *temp_ep; struct xhci_ring *ring; struct xhci_td *cur_td; int ret, i, j; unsigned long flags; ep = (struct xhci_virt_ep *) arg; xhci = ep->xhci; spin_lock_irqsave(&xhci->lock, flags); ep->stop_cmds_pending--; if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Stop EP timer ran, but another timer marked " "xHCI as DYING, exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) { xhci_dbg(xhci, "Stop EP timer ran, but no command pending, " "exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n"); xhci_warn(xhci, "Assuming host is dying, halting host.\n"); /* Oops, HC is dead or dying or at least not responding to the stop * endpoint command. */ xhci->xhc_state |= XHCI_STATE_DYING; /* Disable interrupts from the host controller and start halting it */ xhci_quiesce(xhci); spin_unlock_irqrestore(&xhci->lock, flags); ret = xhci_halt(xhci); spin_lock_irqsave(&xhci->lock, flags); if (ret < 0) { /* This is bad; the host is not responding to commands and it's * not allowing itself to be halted. At least interrupts are * disabled. If we call usb_hc_died(), it will attempt to * disconnect all device drivers under this host. Those * disconnect() methods will wait for all URBs to be unlinked, * so we must complete them. */ xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n"); xhci_warn(xhci, "Completing active URBs anyway.\n"); /* We could turn all TDs on the rings to no-ops. This won't * help if the host has cached part of the ring, and is slow if * we want to preserve the cycle bit. Skip it and hope the host * doesn't touch the memory. */ } for (i = 0; i < MAX_HC_SLOTS; i++) { if (!xhci->devs[i]) continue; for (j = 0; j < 31; j++) { temp_ep = &xhci->devs[i]->eps[j]; ring = temp_ep->ring; if (!ring) continue; xhci_dbg(xhci, "Killing URBs for slot ID %u, " "ep index %u\n", i, j); while (!list_empty(&ring->td_list)) { cur_td = list_first_entry(&ring->td_list, struct xhci_td, td_list); list_del_init(&cur_td->td_list); if (!list_empty(&cur_td->cancelled_td_list)) list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } while (!list_empty(&temp_ep->cancelled_td_list)) { cur_td = list_first_entry( &temp_ep->cancelled_td_list, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } } } spin_unlock_irqrestore(&xhci->lock, flags); xhci_dbg(xhci, "Calling usb_hc_died()\n"); usb_hc_died(xhci_to_hcd(xhci)->primary_hcd); xhci_dbg(xhci, "xHCI host controller is dead.\n"); } static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci, struct xhci_virt_device *dev, struct xhci_ring *ep_ring, unsigned int ep_index) { union xhci_trb *dequeue_temp; int num_trbs_free_temp; bool revert = false; num_trbs_free_temp = ep_ring->num_trbs_free; dequeue_temp = ep_ring->dequeue; /* If we get two back-to-back stalls, and the first stalled transfer * ends just before a link TRB, the dequeue pointer will be left on * the link TRB by the code in the while loop. So we have to update * the dequeue pointer one segment further, or we'll jump off * the segment into la-la-land. */ if (last_trb(xhci, ep_ring, ep_ring->deq_seg, ep_ring->dequeue)) { ep_ring->deq_seg = ep_ring->deq_seg->next; ep_ring->dequeue = ep_ring->deq_seg->trbs; } while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) { /* We have more usable TRBs */ ep_ring->num_trbs_free++; ep_ring->dequeue++; if (last_trb(xhci, ep_ring, ep_ring->deq_seg, ep_ring->dequeue)) { if (ep_ring->dequeue == dev->eps[ep_index].queued_deq_ptr) break; ep_ring->deq_seg = ep_ring->deq_seg->next; ep_ring->dequeue = ep_ring->deq_seg->trbs; } if (ep_ring->dequeue == dequeue_temp) { revert = true; break; } } if (revert) { xhci_dbg(xhci, "Unable to find new dequeue pointer\n"); ep_ring->num_trbs_free = num_trbs_free_temp; } } /* * When we get a completion for a Set Transfer Ring Dequeue Pointer command, * we need to clear the set deq pending flag in the endpoint ring state, so that * the TD queueing code can ring the doorbell again. We also need to ring the * endpoint doorbell to restart the ring, but only if there aren't more * cancellations pending. */ static void handle_set_deq_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { unsigned int slot_id; unsigned int ep_index; unsigned int stream_id; struct xhci_ring *ep_ring; struct xhci_virt_device *dev; struct xhci_ep_ctx *ep_ctx; struct xhci_slot_ctx *slot_ctx; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2])); dev = xhci->devs[slot_id]; ep_ring = xhci_stream_id_to_ring(dev, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN Set TR deq ptr command for " "freed stream ID %u\n", stream_id); /* XXX: Harmless??? */ dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; return; } ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx); if (GET_COMP_CODE(le32_to_cpu(event->status)) != COMP_SUCCESS) { unsigned int ep_state; unsigned int slot_state; switch (GET_COMP_CODE(le32_to_cpu(event->status))) { case COMP_TRB_ERR: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because " "of stream ID configuration\n"); break; case COMP_CTX_STATE: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due " "to incorrect slot or ep state.\n"); ep_state = le32_to_cpu(ep_ctx->ep_info); ep_state &= EP_STATE_MASK; slot_state = le32_to_cpu(slot_ctx->dev_state); slot_state = GET_SLOT_STATE(slot_state); xhci_dbg(xhci, "Slot state = %u, EP state = %u\n", slot_state, ep_state); break; case COMP_EBADSLT: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because " "slot %u was not enabled.\n", slot_id); break; default: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown " "completion code of %u.\n", GET_COMP_CODE(le32_to_cpu(event->status))); break; } /* OK what do we do now? The endpoint state is hosed, and we * should never get to this point if the synchronization between * queueing, and endpoint state are correct. This might happen * if the device gets disconnected after we've finished * cancelling URBs, which might not be an error... */ } else { xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n", le64_to_cpu(ep_ctx->deq)); if (xhci_trb_virt_to_dma(dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr) == (le64_to_cpu(ep_ctx->deq) & ~(EP_CTX_CYCLE_MASK))) { /* Update the ring's dequeue segment and dequeue pointer * to reflect the new position. */ update_ring_for_set_deq_completion(xhci, dev, ep_ring, ep_index); } else { xhci_warn(xhci, "Mismatch between completed Set TR Deq " "Ptr command & xHCI internal state.\n"); xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n", dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr); } } dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; dev->eps[ep_index].queued_deq_seg = NULL; dev->eps[ep_index].queued_deq_ptr = NULL; /* Restart any rings with pending URBs */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } static void handle_reset_ep_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { int slot_id; unsigned int ep_index; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); /* This command will only fail if the endpoint wasn't halted, * but we don't care. */ xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n", GET_COMP_CODE(le32_to_cpu(event->status))); /* HW with the reset endpoint quirk needs to have a configure endpoint * command complete before the endpoint can be used. Queue that here * because the HW can't handle two commands being queued in a row. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK) { xhci_dbg(xhci, "Queueing configure endpoint command\n"); xhci_queue_configure_endpoint(xhci, xhci->devs[slot_id]->in_ctx->dma, slot_id, false); xhci_ring_cmd_db(xhci); } else { /* Clear our internal halted state and restart the ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } } /* Complete the command and detele it from the devcie's command queue. */ static void xhci_complete_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_command *command, u32 status) { command->status = status; list_del(&command->cmd_list); if (command->completion) complete(command->completion); else xhci_free_command(xhci, command); } /* Check to see if a command in the device's command queue matches this one. * Signal the completion or free the command, and return 1. Return 0 if the * completed command isn't at the head of the command list. */ static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event) { struct xhci_command *command; if (list_empty(&virt_dev->cmd_list)) return 0; command = list_entry(virt_dev->cmd_list.next, struct xhci_command, cmd_list); if (xhci->cmd_ring->dequeue != command->command_trb) return 0; xhci_complete_cmd_in_cmd_wait_list(xhci, command, GET_COMP_CODE(le32_to_cpu(event->status))); return 1; } /* * Finding the command trb need to be cancelled and modifying it to * NO OP command. And if the command is in device's command wait * list, finishing and freeing it. * * If we can't find the command trb, we think it had already been * executed. */ static void xhci_cmd_to_noop(struct xhci_hcd *xhci, struct xhci_cd *cur_cd) { struct xhci_segment *cur_seg; union xhci_trb *cmd_trb; u32 cycle_state; if (xhci->cmd_ring->dequeue == xhci->cmd_ring->enqueue) return; /* find the current segment of command ring */ cur_seg = find_trb_seg(xhci->cmd_ring->first_seg, xhci->cmd_ring->dequeue, &cycle_state); if (!cur_seg) { xhci_warn(xhci, "Command ring mismatch, dequeue = %p %llx (dma)\n", xhci->cmd_ring->dequeue, (unsigned long long) xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue)); xhci_debug_ring(xhci, xhci->cmd_ring); xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring); return; } /* find the command trb matched by cd from command ring */ for (cmd_trb = xhci->cmd_ring->dequeue; cmd_trb != xhci->cmd_ring->enqueue; next_trb(xhci, xhci->cmd_ring, &cur_seg, &cmd_trb)) { /* If the trb is link trb, continue */ if (TRB_TYPE_LINK_LE32(cmd_trb->generic.field[3])) continue; if (cur_cd->cmd_trb == cmd_trb) { /* If the command in device's command list, we should * finish it and free the command structure. */ if (cur_cd->command) xhci_complete_cmd_in_cmd_wait_list(xhci, cur_cd->command, COMP_CMD_STOP); /* get cycle state from the origin command trb */ cycle_state = le32_to_cpu(cmd_trb->generic.field[3]) & TRB_CYCLE; /* modify the command trb to NO OP command */ cmd_trb->generic.field[0] = 0; cmd_trb->generic.field[1] = 0; cmd_trb->generic.field[2] = 0; cmd_trb->generic.field[3] = cpu_to_le32( TRB_TYPE(TRB_CMD_NOOP) | cycle_state); break; } } } static void xhci_cancel_cmd_in_cd_list(struct xhci_hcd *xhci) { struct xhci_cd *cur_cd, *next_cd; if (list_empty(&xhci->cancel_cmd_list)) return; list_for_each_entry_safe(cur_cd, next_cd, &xhci->cancel_cmd_list, cancel_cmd_list) { xhci_cmd_to_noop(xhci, cur_cd); list_del(&cur_cd->cancel_cmd_list); kfree(cur_cd); } } /* * traversing the cancel_cmd_list. If the command descriptor according * to cmd_trb is found, the function free it and return 1, otherwise * return 0. */ static int xhci_search_cmd_trb_in_cd_list(struct xhci_hcd *xhci, union xhci_trb *cmd_trb) { struct xhci_cd *cur_cd, *next_cd; if (list_empty(&xhci->cancel_cmd_list)) return 0; list_for_each_entry_safe(cur_cd, next_cd, &xhci->cancel_cmd_list, cancel_cmd_list) { if (cur_cd->cmd_trb == cmd_trb) { if (cur_cd->command) xhci_complete_cmd_in_cmd_wait_list(xhci, cur_cd->command, COMP_CMD_STOP); list_del(&cur_cd->cancel_cmd_list); kfree(cur_cd); return 1; } } return 0; } /* * If the cmd_trb_comp_code is COMP_CMD_ABORT, we just check whether the * trb pointed by the command ring dequeue pointer is the trb we want to * cancel or not. And if the cmd_trb_comp_code is COMP_CMD_STOP, we will * traverse the cancel_cmd_list to trun the all of the commands according * to command descriptor to NO-OP trb. */ static int handle_stopped_cmd_ring(struct xhci_hcd *xhci, int cmd_trb_comp_code) { int cur_trb_is_good = 0; /* Searching the cmd trb pointed by the command ring dequeue * pointer in command descriptor list. If it is found, free it. */ cur_trb_is_good = xhci_search_cmd_trb_in_cd_list(xhci, xhci->cmd_ring->dequeue); if (cmd_trb_comp_code == COMP_CMD_ABORT) xhci->cmd_ring_state = CMD_RING_STATE_STOPPED; else if (cmd_trb_comp_code == COMP_CMD_STOP) { /* traversing the cancel_cmd_list and canceling * the command according to command descriptor */ xhci_cancel_cmd_in_cd_list(xhci); xhci->cmd_ring_state = CMD_RING_STATE_RUNNING; /* * ring command ring doorbell again to restart the * command ring */ if (xhci->cmd_ring->dequeue != xhci->cmd_ring->enqueue) xhci_ring_cmd_db(xhci); } return cur_trb_is_good; } static void handle_cmd_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event) { int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); u64 cmd_dma; dma_addr_t cmd_dequeue_dma; struct xhci_input_control_ctx *ctrl_ctx; struct xhci_virt_device *virt_dev; unsigned int ep_index; struct xhci_ring *ep_ring; unsigned int ep_state; cmd_dma = le64_to_cpu(event->cmd_trb); cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue); /* Is the command ring deq ptr out of sync with the deq seg ptr? */ if (cmd_dequeue_dma == 0) { xhci->error_bitmask |= 1 << 4; return; } /* Does the DMA address match our internal dequeue pointer address? */ if (cmd_dma != (u64) cmd_dequeue_dma) { xhci->error_bitmask |= 1 << 5; return; } if ((GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_CMD_ABORT) || (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_CMD_STOP)) { /* If the return value is 0, we think the trb pointed by * command ring dequeue pointer is a good trb. The good * trb means we don't want to cancel the trb, but it have * been stopped by host. So we should handle it normally. * Otherwise, driver should invoke inc_deq() and return. */ if (handle_stopped_cmd_ring(xhci, GET_COMP_CODE(le32_to_cpu(event->status)))) { inc_deq(xhci, xhci->cmd_ring); return; } } switch (le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]) & TRB_TYPE_BITMASK) { case TRB_TYPE(TRB_ENABLE_SLOT): if (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_SUCCESS) xhci->slot_id = slot_id; else xhci->slot_id = 0; complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_DISABLE_SLOT): if (xhci->devs[slot_id]) { if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) /* Delete default control endpoint resources */ xhci_free_device_endpoint_resources(xhci, xhci->devs[slot_id], true); xhci_free_virt_device(xhci, slot_id); } break; case TRB_TYPE(TRB_CONFIG_EP): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; /* * Configure endpoint commands can come from the USB core * configuration or alt setting changes, or because the HW * needed an extra configure endpoint command after a reset * endpoint command or streams were being configured. * If the command was for a halted endpoint, the xHCI driver * is not waiting on the configure endpoint command. */ ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx); /* Input ctx add_flags are the endpoint index plus one */ ep_index = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags)) - 1; /* A usb_set_interface() call directly after clearing a halted * condition may race on this quirky hardware. Not worth * worrying about, since this is prototype hardware. Not sure * if this will work for streams, but streams support was * untested on this prototype. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK && ep_index != (unsigned int) -1 && le32_to_cpu(ctrl_ctx->add_flags) - SLOT_FLAG == le32_to_cpu(ctrl_ctx->drop_flags)) { ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state; if (!(ep_state & EP_HALTED)) goto bandwidth_change; xhci_dbg(xhci, "Completed config ep cmd - " "last ep index = %d, state = %d\n", ep_index, ep_state); /* Clear internal halted state and restart ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); break; } bandwidth_change: xhci_dbg(xhci, "Completed config ep cmd\n"); xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_EVAL_CONTEXT): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_ADDR_DEV): xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_STOP_RING): handle_stopped_endpoint(xhci, xhci->cmd_ring->dequeue, event); break; case TRB_TYPE(TRB_SET_DEQ): handle_set_deq_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_CMD_NOOP): break; case TRB_TYPE(TRB_RESET_EP): handle_reset_ep_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_RESET_DEV): xhci_dbg(xhci, "Completed reset device command.\n"); slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Reset device command completion " "for disabled slot %u\n", slot_id); break; case TRB_TYPE(TRB_NEC_GET_FW): if (!(xhci->quirks & XHCI_NEC_HOST)) { xhci->error_bitmask |= 1 << 6; break; } xhci_dbg(xhci, "NEC firmware version %2x.%02x\n", NEC_FW_MAJOR(le32_to_cpu(event->status)), NEC_FW_MINOR(le32_to_cpu(event->status))); break; default: /* Skip over unknown commands on the event ring */ xhci->error_bitmask |= 1 << 6; break; } inc_deq(xhci, xhci->cmd_ring); } static void handle_vendor_event(struct xhci_hcd *xhci, union xhci_trb *event) { u32 trb_type; trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->generic.field[3])); xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type); if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST)) handle_cmd_completion(xhci, &event->event_cmd); } /* @port_id: the one-based port ID from the hardware (indexed from array of all * port registers -- USB 3.0 and USB 2.0). * * Returns a zero-based port number, which is suitable for indexing into each of * the split roothubs' port arrays and bus state arrays. * Add one to it in order to call xhci_find_slot_id_by_port. */ static unsigned int find_faked_portnum_from_hw_portnum(struct usb_hcd *hcd, struct xhci_hcd *xhci, u32 port_id) { unsigned int i; unsigned int num_similar_speed_ports = 0; /* port_id from the hardware is 1-based, but port_array[], usb3_ports[], * and usb2_ports are 0-based indexes. Count the number of similar * speed ports, up to 1 port before this port. */ for (i = 0; i < (port_id - 1); i++) { u8 port_speed = xhci->port_array[i]; /* * Skip ports that don't have known speeds, or have duplicate * Extended Capabilities port speed entries. */ if (port_speed == 0 || port_speed == DUPLICATE_ENTRY) continue; /* * USB 3.0 ports are always under a USB 3.0 hub. USB 2.0 and * 1.1 ports are under the USB 2.0 hub. If the port speed * matches the device speed, it's a similar speed port. */ if ((port_speed == 0x03) == (hcd->speed == HCD_USB3)) num_similar_speed_ports++; } return num_similar_speed_ports; } static void handle_device_notification(struct xhci_hcd *xhci, union xhci_trb *event) { u32 slot_id; struct usb_device *udev; slot_id = TRB_TO_SLOT_ID(event->generic.field[3]); if (!xhci->devs[slot_id]) { xhci_warn(xhci, "Device Notification event for " "unused slot %u\n", slot_id); return; } xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n", slot_id); udev = xhci->devs[slot_id]->udev; if (udev && udev->parent) usb_wakeup_notification(udev->parent, udev->portnum); } static void handle_port_status(struct xhci_hcd *xhci, union xhci_trb *event) { struct usb_hcd *hcd; u32 port_id; u32 temp, temp1; int max_ports; int slot_id; unsigned int faked_port_index; u8 major_revision; struct xhci_bus_state *bus_state; __le32 __iomem **port_array; bool bogus_port_status = false; /* Port status change events always have a successful completion code */ if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS) { xhci_warn(xhci, "WARN: xHC returned failed port status event\n"); xhci->error_bitmask |= 1 << 8; } port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0])); xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id); max_ports = HCS_MAX_PORTS(xhci->hcs_params1); if ((port_id <= 0) || (port_id > max_ports)) { xhci_warn(xhci, "Invalid port id %d\n", port_id); bogus_port_status = true; goto cleanup; } /* Figure out which usb_hcd this port is attached to: * is it a USB 3.0 port or a USB 2.0/1.1 port? */ major_revision = xhci->port_array[port_id - 1]; if (major_revision == 0) { xhci_warn(xhci, "Event for port %u not in " "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } if (major_revision == DUPLICATE_ENTRY) { xhci_warn(xhci, "Event for port %u duplicated in" "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } /* * Hardware port IDs reported by a Port Status Change Event include USB * 3.0 and USB 2.0 ports. We want to check if the port has reported a * resume event, but we first need to translate the hardware port ID * into the index into the ports on the correct split roothub, and the * correct bus_state structure. */ /* Find the right roothub. */ hcd = xhci_to_hcd(xhci); if ((major_revision == 0x03) != (hcd->speed == HCD_USB3)) hcd = xhci->shared_hcd; bus_state = &xhci->bus_state[hcd_index(hcd)]; if (hcd->speed == HCD_USB3) port_array = xhci->usb3_ports; else port_array = xhci->usb2_ports; /* Find the faked port hub number */ faked_port_index = find_faked_portnum_from_hw_portnum(hcd, xhci, port_id); temp = xhci_readl(xhci, port_array[faked_port_index]); if (hcd->state == HC_STATE_SUSPENDED) { xhci_dbg(xhci, "resume root hub\n"); usb_hcd_resume_root_hub(hcd); } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME) { xhci_dbg(xhci, "port resume event for port %d\n", port_id); temp1 = xhci_readl(xhci, &xhci->op_regs->command); if (!(temp1 & CMD_RUN)) { xhci_warn(xhci, "xHC is not running.\n"); goto cleanup; } if (DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "remote wake SS port %d\n", port_id); /* Set a flag to say the port signaled remote wakeup, * so we can tell the difference between the end of * device and host initiated resume. */ bus_state->port_remote_wakeup |= 1 << faked_port_index; xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); xhci_set_link_state(xhci, port_array, faked_port_index, XDEV_U0); /* Need to wait until the next link state change * indicates the device is actually in U0. */ bogus_port_status = true; goto cleanup; } else { xhci_dbg(xhci, "resume HS port %d\n", port_id); bus_state->resume_done[faked_port_index] = jiffies + msecs_to_jiffies(20); set_bit(faked_port_index, &bus_state->resuming_ports); mod_timer(&hcd->rh_timer, bus_state->resume_done[faked_port_index]); /* Do the rest in GetPortStatus */ } } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_U0 && DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "resume SS port %d finished\n", port_id); /* We've just brought the device into U0 through either the * Resume state after a device remote wakeup, or through the * U3Exit state after a host-initiated resume. If it's a device * initiated remote wake, don't pass up the link state change, * so the roothub behavior is consistent with external * USB 3.0 hub behavior. */ slot_id = xhci_find_slot_id_by_port(hcd, xhci, faked_port_index + 1); if (slot_id && xhci->devs[slot_id]) xhci_ring_device(xhci, slot_id); if (bus_state->port_remote_wakeup & (1 << faked_port_index)) { bus_state->port_remote_wakeup &= ~(1 << faked_port_index); xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); usb_wakeup_notification(hcd->self.root_hub, faked_port_index + 1); bogus_port_status = true; goto cleanup; } } if (hcd->speed != HCD_USB3) xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); cleanup: /* Update event ring dequeue pointer before dropping the lock */ inc_deq(xhci, xhci->event_ring); /* Don't make the USB core poll the roothub if we got a bad port status * change event. Besides, at that point we can't tell which roothub * (USB 2.0 or USB 3.0) to kick. */ if (bogus_port_status) return; /* * xHCI port-status-change events occur when the "or" of all the * status-change bits in the portsc register changes from 0 to 1. * New status changes won't cause an event if any other change * bits are still set. When an event occurs, switch over to * polling to avoid losing status changes. */ xhci_dbg(xhci, "%s: starting port polling.\n", __func__); set_bit(HCD_FLAG_POLL_RH, &hcd->flags); spin_unlock(&xhci->lock); /* Pass this up to the core */ usb_hcd_poll_rh_status(hcd); spin_lock(&xhci->lock); } /* * This TD is defined by the TRBs starting at start_trb in start_seg and ending * at end_trb, which may be in another segment. If the suspect DMA address is a * TRB in this TD, this function returns that TRB's segment. Otherwise it * returns 0. */ struct xhci_segment *trb_in_td(struct xhci_segment *start_seg, union xhci_trb *start_trb, union xhci_trb *end_trb, dma_addr_t suspect_dma) { dma_addr_t start_dma; dma_addr_t end_seg_dma; dma_addr_t end_trb_dma; struct xhci_segment *cur_seg; start_dma = xhci_trb_virt_to_dma(start_seg, start_trb); cur_seg = start_seg; do { if (start_dma == 0) return NULL; /* We may get an event for a Link TRB in the middle of a TD */ end_seg_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[TRBS_PER_SEGMENT - 1]); /* If the end TRB isn't in this segment, this is set to 0 */ end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb); if (end_trb_dma > 0) { /* The end TRB is in this segment, so suspect should be here */ if (start_dma <= end_trb_dma) { if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma) return cur_seg; } else { /* Case for one segment with * a TD wrapped around to the top */ if ((suspect_dma >= start_dma && suspect_dma <= end_seg_dma) || (suspect_dma >= cur_seg->dma && suspect_dma <= end_trb_dma)) return cur_seg; } return NULL; } else { /* Might still be somewhere in this segment */ if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma) return cur_seg; } cur_seg = cur_seg->next; start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]); } while (cur_seg != start_seg); return NULL; } static void xhci_cleanup_halted_endpoint(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *td, union xhci_trb *event_trb) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; ep->ep_state |= EP_HALTED; ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = stream_id; xhci_queue_reset_ep(xhci, slot_id, ep_index); xhci_cleanup_stalled_ring(xhci, td->urb->dev, ep_index); ep->stopped_td = NULL; ep->stopped_trb = NULL; ep->stopped_stream = 0; xhci_ring_cmd_db(xhci); } /* Check if an error has halted the endpoint ring. The class driver will * cleanup the halt for a non-default control endpoint if we indicate a stall. * However, a babble and other errors also halt the endpoint ring, and the class * driver won't clear the halt in that case, so we need to issue a Set Transfer * Ring Dequeue Pointer command manually. */ static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci, struct xhci_ep_ctx *ep_ctx, unsigned int trb_comp_code) { /* TRB completion codes that may require a manual halt cleanup */ if (trb_comp_code == COMP_TX_ERR || trb_comp_code == COMP_BABBLE || trb_comp_code == COMP_SPLIT_ERR) /* The 0.96 spec says a babbling control endpoint * is not halted. The 0.96 spec says it is. Some HW * claims to be 0.95 compliant, but it halts the control * endpoint anyway. Check if a babble halted the * endpoint. */ if ((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) == cpu_to_le32(EP_STATE_HALTED)) return 1; return 0; } int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code) { if (trb_comp_code >= 224 && trb_comp_code <= 255) { /* Vendor defined "informational" completion code, * treat as not-an-error. */ xhci_dbg(xhci, "Vendor defined info completion code %u\n", trb_comp_code); xhci_dbg(xhci, "Treating code as success.\n"); return 1; } return 0; } /* * Finish the td processing, remove the td from td list; * Return 1 if the urb can be given back. */ static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status, bool skip) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct urb *urb = NULL; struct xhci_ep_ctx *ep_ctx; int ret = 0; struct urb_priv *urb_priv; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); if (skip) goto td_cleanup; if (trb_comp_code == COMP_STOP_INVAL || trb_comp_code == COMP_STOP) { /* The Endpoint Stop Command completion will take care of any * stopped TDs. A stopped TD may be restarted, so don't update * the ring dequeue pointer or take this TD off any lists yet. */ ep->stopped_td = td; ep->stopped_trb = event_trb; return 0; } else { if (trb_comp_code == COMP_STALL) { /* The transfer is completed from the driver's * perspective, but we need to issue a set dequeue * command for this stalled endpoint to move the dequeue * pointer past the TD. We can't do that here because * the halt condition must be cleared first. Let the * USB class driver clear the stall later. */ ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = ep_ring->stream_id; } else if (xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) { /* Other types of errors halt the endpoint, but the * class driver doesn't call usb_reset_endpoint() unless * the error is -EPIPE. Clear the halted status in the * xHCI hardware manually. */ xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, ep_ring->stream_id, td, event_trb); } else { /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); } td_cleanup: /* Clean up the endpoint's TD list */ urb = td->urb; urb_priv = urb->hcpriv; /* Do one last check of the actual transfer length. * If the host controller said we transferred more data than * the buffer length, urb->actual_length will be a very big * number (since it's unsigned). Play it safe and say we didn't * transfer anything. */ if (urb->actual_length > urb->transfer_buffer_length) { xhci_warn(xhci, "URB transfer length is wrong, " "xHC issue? req. len = %u, " "act. len = %u\n", urb->transfer_buffer_length, urb->actual_length); urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } list_del_init(&td->td_list); /* Was this TD slated to be cancelled but completed anyway? */ if (!list_empty(&td->cancelled_td_list)) list_del_init(&td->cancelled_td_list); urb_priv->td_cnt++; /* Giveback the urb when all the tds are completed */ if (urb_priv->td_cnt == urb_priv->length) { ret = 1; if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } } } return ret; } /* * Process control tds, update urb status and actual_length. */ static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_ep_ctx *ep_ctx; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: if (event_trb == ep_ring->dequeue) { xhci_warn(xhci, "WARN: Success on ctrl setup TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN: Success on ctrl data TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; case COMP_STOP_INVAL: case COMP_STOP: return finish_td(xhci, td, event_trb, event, ep, status, false); default: if (!xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) break; xhci_dbg(xhci, "TRB error code %u, " "halted endpoint index = %u\n", trb_comp_code, ep_index); /* else fall through */ case COMP_STALL: /* Did we transfer part of the data (middle) phase? */ if (event_trb != ep_ring->dequeue && event_trb != td->last_trb) td->urb->actual_length = td->urb->transfer_buffer_length - EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)); else td->urb->actual_length = 0; xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, 0, td, event_trb); return finish_td(xhci, td, event_trb, event, ep, status, true); } /* * Did we transfer any data, despite the errors that might have * happened? I.e. did we get past the setup stage? */ if (event_trb != ep_ring->dequeue) { /* The event was for the status stage */ if (event_trb == td->last_trb) { if (td->urb->actual_length != 0) { /* Don't overwrite a previously set error code */ if ((*status == -EINPROGRESS || *status == 0) && (td->urb->transfer_flags & URB_SHORT_NOT_OK)) /* Did we already see a short data * stage? */ *status = -EREMOTEIO; } else { td->urb->actual_length = td->urb->transfer_buffer_length; } } else { /* Maybe the event was for the data stage? */ td->urb->actual_length = td->urb->transfer_buffer_length - EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)); xhci_dbg(xhci, "Waiting for status " "stage event\n"); return 0; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * Process isochronous tds, update urb packet status and actual_length. */ static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; int idx; int len = 0; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; struct usb_iso_packet_descriptor *frame; u32 trb_comp_code; bool skip_td = false; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* handle completion code */ switch (trb_comp_code) { case COMP_SUCCESS: if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) == 0) { frame->status = 0; break; } if ((xhci->quirks & XHCI_TRUST_TX_LENGTH)) trb_comp_code = COMP_SHORT_TX; case COMP_SHORT_TX: frame->status = td->urb->transfer_flags & URB_SHORT_NOT_OK ? -EREMOTEIO : 0; break; case COMP_BW_OVER: frame->status = -ECOMM; skip_td = true; break; case COMP_BUFF_OVER: case COMP_BABBLE: frame->status = -EOVERFLOW; skip_td = true; break; case COMP_DEV_ERR: case COMP_STALL: case COMP_TX_ERR: frame->status = -EPROTO; skip_td = true; break; case COMP_STOP: case COMP_STOP_INVAL: break; default: frame->status = -1; break; } if (trb_comp_code == COMP_SUCCESS || skip_td) { frame->actual_length = frame->length; td->urb->actual_length += frame->length; } else { for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)); if (trb_comp_code != COMP_STOP_INVAL) { frame->actual_length = len; td->urb->actual_length += len; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct usb_iso_packet_descriptor *frame; int idx; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* The transfer is partly done. */ frame->status = -EXDEV; /* calc actual length */ frame->actual_length = 0; /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); return finish_td(xhci, td, NULL, event, ep, status, true); } /* * Process bulk and interrupt tds, update urb status and actual_length. */ static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; u32 trb_comp_code; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: /* Double check that the HW transferred everything. */ if (event_trb != td->last_trb || EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) { xhci_warn(xhci, "WARN Successful completion " "on short TX\n"); if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; if ((xhci->quirks & XHCI_TRUST_TX_LENGTH)) trb_comp_code = COMP_SHORT_TX; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; default: /* Others already handled above */ break; } if (trb_comp_code == COMP_SHORT_TX) xhci_dbg(xhci, "ep %#x - asked for %d bytes, " "%d bytes untransferred\n", td->urb->ep->desc.bEndpointAddress, td->urb->transfer_buffer_length, EVENT_TRB_LEN(le32_to_cpu(event->transfer_len))); /* Fast path - was this the last TRB in the TD for this URB? */ if (event_trb == td->last_trb) { if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) { td->urb->actual_length = td->urb->transfer_buffer_length - EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)); if (td->urb->transfer_buffer_length < td->urb->actual_length) { xhci_warn(xhci, "HC gave bad length " "of %d bytes left\n", EVENT_TRB_LEN(le32_to_cpu(event->transfer_len))); td->urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } /* Don't overwrite a previously set error code */ if (*status == -EINPROGRESS) { if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } } else { td->urb->actual_length = td->urb->transfer_buffer_length; /* Ignore a short packet completion if the * untransferred length was zero. */ if (*status == -EREMOTEIO) *status = 0; } } else { /* Slow path - walk the list, starting from the dequeue * pointer, to get the actual length transferred. */ td->urb->actual_length = 0; for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } /* If the ring didn't stop on a Link or No-op TRB, add * in the actual bytes transferred from the Normal TRB */ if (trb_comp_code != COMP_STOP_INVAL) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)); } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * If this function returns an error condition, it means it got a Transfer * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address. * At this point, the host controller is probably hosed and should be reset. */ static int handle_tx_event(struct xhci_hcd *xhci, struct xhci_transfer_event *event) { struct xhci_virt_device *xdev; struct xhci_virt_ep *ep; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_td *td = NULL; dma_addr_t event_dma; struct xhci_segment *event_seg; union xhci_trb *event_trb; struct urb *urb = NULL; int status = -EINPROGRESS; struct urb_priv *urb_priv; struct xhci_ep_ctx *ep_ctx; struct list_head *tmp; u32 trb_comp_code; int ret = 0; int td_num = 0; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; if (!xdev) { xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Endpoint ID is 1 based, our index is zero based */ ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep = &xdev->eps[ep_index]; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); if (!ep_ring || (le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) == EP_STATE_DISABLED) { xhci_err(xhci, "ERROR Transfer event for disabled endpoint " "or incorrect stream ring\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Count current td numbers if ep->skip is set */ if (ep->skip) { list_for_each(tmp, &ep_ring->td_list) td_num++; } event_dma = le64_to_cpu(event->buffer); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); /* Look for common error cases */ switch (trb_comp_code) { /* Skip codes that require special handling depending on * transfer type */ case COMP_SUCCESS: if (EVENT_TRB_LEN(le32_to_cpu(event->transfer_len)) == 0) break; if (xhci->quirks & XHCI_TRUST_TX_LENGTH) trb_comp_code = COMP_SHORT_TX; else xhci_warn(xhci, "WARN Successful completion on short TX: " "needs XHCI_TRUST_TX_LENGTH quirk?\n"); case COMP_SHORT_TX: break; case COMP_STOP: xhci_dbg(xhci, "Stopped on Transfer TRB\n"); break; case COMP_STOP_INVAL: xhci_dbg(xhci, "Stopped on No-op or Link TRB\n"); break; case COMP_STALL: xhci_dbg(xhci, "Stalled endpoint\n"); ep->ep_state |= EP_HALTED; status = -EPIPE; break; case COMP_TRB_ERR: xhci_warn(xhci, "WARN: TRB error on endpoint\n"); status = -EILSEQ; break; case COMP_SPLIT_ERR: case COMP_TX_ERR: xhci_dbg(xhci, "Transfer error on endpoint\n"); status = -EPROTO; break; case COMP_BABBLE: xhci_dbg(xhci, "Babble error on endpoint\n"); status = -EOVERFLOW; break; case COMP_DB_ERR: xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n"); status = -ENOSR; break; case COMP_BW_OVER: xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n"); break; case COMP_BUFF_OVER: xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n"); break; case COMP_UNDERRUN: /* * When the Isoch ring is empty, the xHC will generate * a Ring Overrun Event for IN Isoch endpoint or Ring * Underrun Event for OUT Isoch endpoint. */ xhci_dbg(xhci, "underrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Underrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_OVERRUN: xhci_dbg(xhci, "overrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Overrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_DEV_ERR: xhci_warn(xhci, "WARN: detect an incompatible device"); status = -EPROTO; break; case COMP_MISSED_INT: /* * When encounter missed service error, one or more isoc tds * may be missed by xHC. * Set skip flag of the ep_ring; Complete the missed tds as * short transfer when process the ep_ring next time. */ ep->skip = true; xhci_dbg(xhci, "Miss service interval error, set skip flag\n"); goto cleanup; default: if (xhci_is_vendor_info_code(xhci, trb_comp_code)) { status = 0; break; } xhci_warn(xhci, "ERROR Unknown event condition, HC probably " "busted\n"); goto cleanup; } do { /* This TRB should be in the TD at the head of this ring's * TD list. */ if (list_empty(&ep_ring->td_list)) { xhci_warn(xhci, "WARN Event TRB for slot %d ep %d " "with no TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); xhci_dbg(xhci, "Event TRB with TRB type ID %u\n", (le32_to_cpu(event->flags) & TRB_TYPE_BITMASK)>>10); xhci_print_trb_offsets(xhci, (union xhci_trb *) event); if (ep->skip) { ep->skip = false; xhci_dbg(xhci, "td_list is empty while skip " "flag set. Clear skip flag.\n"); } ret = 0; goto cleanup; } /* We've skipped all the TDs on the ep ring when ep->skip set */ if (ep->skip && td_num == 0) { ep->skip = false; xhci_dbg(xhci, "All tds on the ep_ring skipped. " "Clear skip flag.\n"); ret = 0; goto cleanup; } td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list); if (ep->skip) td_num--; /* Is this a TRB in the currently executing TD? */ event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue, td->last_trb, event_dma); /* * Skip the Force Stopped Event. The event_trb(event_dma) of FSE * is not in the current TD pointed by ep_ring->dequeue because * that the hardware dequeue pointer still at the previous TRB * of the current TD. The previous TRB maybe a Link TD or the * last TRB of the previous TD. The command completion handle * will take care the rest. */ if (!event_seg && trb_comp_code == COMP_STOP_INVAL) { ret = 0; goto cleanup; } if (!event_seg) { if (!ep->skip || !usb_endpoint_xfer_isoc(&td->urb->ep->desc)) { /* Some host controllers give a spurious * successful event after a short transfer. * Ignore it. */ if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) && ep_ring->last_td_was_short) { ep_ring->last_td_was_short = false; ret = 0; goto cleanup; } /* HC is busted, give up! */ xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not " "part of current TD\n"); return -ESHUTDOWN; } ret = skip_isoc_td(xhci, td, event, ep, &status); goto cleanup; } if (trb_comp_code == COMP_SHORT_TX) ep_ring->last_td_was_short = true; else ep_ring->last_td_was_short = false; if (ep->skip) { xhci_dbg(xhci, "Found td. Clear skip flag.\n"); ep->skip = false; } event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)]; /* * No-op TRB should not trigger interrupts. * If event_trb is a no-op TRB, it means the * corresponding TD has been cancelled. Just ignore * the TD. */ if (TRB_TYPE_NOOP_LE32(event_trb->generic.field[3])) { xhci_dbg(xhci, "event_trb is a no-op TRB. Skip it\n"); goto cleanup; } /* Now update the urb's actual_length and give back to * the core */ if (usb_endpoint_xfer_control(&td->urb->ep->desc)) ret = process_ctrl_td(xhci, td, event_trb, event, ep, &status); else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc)) ret = process_isoc_td(xhci, td, event_trb, event, ep, &status); else ret = process_bulk_intr_td(xhci, td, event_trb, event, ep, &status); cleanup: /* * Do not update event ring dequeue pointer if ep->skip is set. * Will roll back to continue process missed tds. */ if (trb_comp_code == COMP_MISSED_INT || !ep->skip) { inc_deq(xhci, xhci->event_ring); } if (ret) { urb = td->urb; urb_priv = urb->hcpriv; /* Leave the TD around for the reset endpoint function * to use(but only if it's not a control endpoint, * since we already queued the Set TR dequeue pointer * command for stalled control endpoints). */ if (usb_endpoint_xfer_control(&urb->ep->desc) || (trb_comp_code != COMP_STALL && trb_comp_code != COMP_BABBLE)) xhci_urb_free_priv(xhci, urb_priv); else kfree(urb_priv); usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); if ((urb->actual_length != urb->transfer_buffer_length && (urb->transfer_flags & URB_SHORT_NOT_OK)) || (status != 0 && !usb_endpoint_xfer_isoc(&urb->ep->desc))) xhci_dbg(xhci, "Giveback URB %p, len = %d, " "expected = %x, status = %d\n", urb, urb->actual_length, urb->transfer_buffer_length, status); spin_unlock(&xhci->lock); /* EHCI, UHCI, and OHCI always unconditionally set the * urb->status of an isochronous endpoint to 0. */ if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) status = 0; usb_hcd_giveback_urb(bus_to_hcd(urb->dev->bus), urb, status); spin_lock(&xhci->lock); } /* * If ep->skip is set, it means there are missed tds on the * endpoint ring need to take care of. * Process them as short transfer until reach the td pointed by * the event. */ } while (ep->skip && trb_comp_code != COMP_MISSED_INT); return 0; } /* * This function handles all OS-owned events on the event ring. It may drop * xhci->lock between event processing (e.g. to pass up port status changes). * Returns >0 for "possibly more events to process" (caller should call again), * otherwise 0 if done. In future, <0 returns should indicate error code. */ static int xhci_handle_event(struct xhci_hcd *xhci) { union xhci_trb *event; int update_ptrs = 1; int ret; if (!xhci->event_ring || !xhci->event_ring->dequeue) { xhci->error_bitmask |= 1 << 1; return 0; } event = xhci->event_ring->dequeue; /* Does the HC or OS own the TRB? */ if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) != xhci->event_ring->cycle_state) { xhci->error_bitmask |= 1 << 2; return 0; } /* * Barrier between reading the TRB_CYCLE (valid) flag above and any * speculative reads of the event's flags/data below. */ rmb(); /* FIXME: Handle more event types. */ switch ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK)) { case TRB_TYPE(TRB_COMPLETION): handle_cmd_completion(xhci, &event->event_cmd); break; case TRB_TYPE(TRB_PORT_STATUS): handle_port_status(xhci, event); update_ptrs = 0; break; case TRB_TYPE(TRB_TRANSFER): ret = handle_tx_event(xhci, &event->trans_event); if (ret < 0) xhci->error_bitmask |= 1 << 9; else update_ptrs = 0; break; case TRB_TYPE(TRB_DEV_NOTE): handle_device_notification(xhci, event); break; default: if ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK) >= TRB_TYPE(48)) handle_vendor_event(xhci, event); else xhci->error_bitmask |= 1 << 3; } /* Any of the above functions may drop and re-acquire the lock, so check * to make sure a watchdog timer didn't mark the host as non-responsive. */ if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI host dying, returning from " "event handler.\n"); return 0; } if (update_ptrs) /* Update SW event ring dequeue pointer */ inc_deq(xhci, xhci->event_ring); /* Are there more items on the event ring? Caller will call us again to * check. */ return 1; } /* * xHCI spec says we can get an interrupt, and if the HC has an error condition, * we might get bad data out of the event ring. Section 4.10.2.7 has a list of * indicators of an event TRB error, but we check the status *first* to be safe. */ irqreturn_t xhci_irq(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); u32 status; union xhci_trb *trb; u64 temp_64; union xhci_trb *event_ring_deq; dma_addr_t deq; spin_lock(&xhci->lock); trb = xhci->event_ring->dequeue; /* Check if the xHC generated the interrupt, or the irq is shared */ status = xhci_readl(xhci, &xhci->op_regs->status); if (status == 0xffffffff) goto hw_died; if (!(status & STS_EINT)) { spin_unlock(&xhci->lock); return IRQ_NONE; } if (status & STS_FATAL) { xhci_warn(xhci, "WARNING: Host System Error\n"); xhci_halt(xhci); hw_died: spin_unlock(&xhci->lock); return -ESHUTDOWN; } /* * Clear the op reg interrupt status first, * so we can receive interrupts from other MSI-X interrupters. * Write 1 to clear the interrupt status. */ status |= STS_EINT; xhci_writel(xhci, status, &xhci->op_regs->status); /* FIXME when MSI-X is supported and there are multiple vectors */ /* Clear the MSI-X event interrupt status */ if (hcd->irq) { u32 irq_pending; /* Acknowledge the PCI interrupt */ irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending); irq_pending |= IMAN_IP; xhci_writel(xhci, irq_pending, &xhci->ir_set->irq_pending); } if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI dying, ignoring interrupt. " "Shouldn't IRQs be disabled?\n"); /* Clear the event handler busy flag (RW1C); * the event ring should be empty. */ temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); xhci_write_64(xhci, temp_64 | ERST_EHB, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } event_ring_deq = xhci->event_ring->dequeue; /* FIXME this should be a delayed service routine * that clears the EHB. */ while (xhci_handle_event(xhci) > 0) {} temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); /* If necessary, update the HW's version of the event ring deq ptr. */ if (event_ring_deq != xhci->event_ring->dequeue) { deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg, xhci->event_ring->dequeue); if (deq == 0) xhci_warn(xhci, "WARN something wrong with SW event " "ring dequeue ptr.\n"); /* Update HC event ring dequeue pointer */ temp_64 &= ERST_PTR_MASK; temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK); } /* Clear the event handler busy flag (RW1C); event ring is empty. */ temp_64 |= ERST_EHB; xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd) { return xhci_irq(hcd); } /**** Endpoint Ring Operations ****/ /* * Generic function for queueing a TRB on a ring. * The caller must have checked to make sure there's room on the ring. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming, u32 field1, u32 field2, u32 field3, u32 field4) { struct xhci_generic_trb *trb; trb = &ring->enqueue->generic; trb->field[0] = cpu_to_le32(field1); trb->field[1] = cpu_to_le32(field2); trb->field[2] = cpu_to_le32(field3); trb->field[3] = cpu_to_le32(field4); inc_enq(xhci, ring, more_trbs_coming); } /* * Does various checks on the endpoint ring, and makes it ready to queue num_trbs. * FIXME allocate segments if the ring is full. */ static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, u32 ep_state, unsigned int num_trbs, gfp_t mem_flags) { unsigned int num_trbs_needed; /* Make sure the endpoint has been added to xHC schedule */ switch (ep_state) { case EP_STATE_DISABLED: /* * USB core changed config/interfaces without notifying us, * or hardware is reporting the wrong state. */ xhci_warn(xhci, "WARN urb submitted to disabled ep\n"); return -ENOENT; case EP_STATE_ERROR: xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n"); /* FIXME event handling code for error needs to clear it */ /* XXX not sure if this should be -ENOENT or not */ return -EINVAL; case EP_STATE_HALTED: xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n"); case EP_STATE_STOPPED: case EP_STATE_RUNNING: break; default: xhci_err(xhci, "ERROR unknown endpoint state for ep\n"); /* * FIXME issue Configure Endpoint command to try to get the HC * back into a known state. */ return -EINVAL; } while (1) { if (room_on_ring(xhci, ep_ring, num_trbs)) break; if (ep_ring == xhci->cmd_ring) { xhci_err(xhci, "Do not support expand command ring\n"); return -ENOMEM; } xhci_dbg(xhci, "ERROR no room on ep ring, " "try ring expansion\n"); num_trbs_needed = num_trbs - ep_ring->num_trbs_free; if (xhci_ring_expansion(xhci, ep_ring, num_trbs_needed, mem_flags)) { xhci_err(xhci, "Ring expansion failed\n"); return -ENOMEM; } }; if (enqueue_is_link_trb(ep_ring)) { struct xhci_ring *ring = ep_ring; union xhci_trb *next; next = ring->enqueue; while (last_trb(xhci, ring, ring->enq_seg, next)) { /* If we're not dealing with 0.95 hardware or isoc rings * on AMD 0.96 host, clear the chain bit. */ if (!xhci_link_trb_quirk(xhci) && !(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST))) next->link.control &= cpu_to_le32(~TRB_CHAIN); else next->link.control |= cpu_to_le32(TRB_CHAIN); wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } } return 0; } static int prepare_transfer(struct xhci_hcd *xhci, struct xhci_virt_device *xdev, unsigned int ep_index, unsigned int stream_id, unsigned int num_trbs, struct urb *urb, unsigned int td_index, gfp_t mem_flags) { int ret; struct urb_priv *urb_priv; struct xhci_td *td; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id); if (!ep_ring) { xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n", stream_id); return -EINVAL; } ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[td_index]; INIT_LIST_HEAD(&td->td_list); INIT_LIST_HEAD(&td->cancelled_td_list); if (td_index == 0) { ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb); if (unlikely(ret)) return ret; } td->urb = urb; /* Add this TD to the tail of the endpoint ring's TD list */ list_add_tail(&td->td_list, &ep_ring->td_list); td->start_seg = ep_ring->enq_seg; td->first_trb = ep_ring->enqueue; urb_priv->td[td_index] = td; return 0; } static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb) { int num_sgs, num_trbs, running_total, temp, i; struct scatterlist *sg; sg = NULL; num_sgs = urb->num_mapped_sgs; temp = urb->transfer_buffer_length; num_trbs = 0; for_each_sg(urb->sg, sg, num_sgs, i) { unsigned int len = sg_dma_len(sg); /* Scatter gather list entries may cross 64KB boundaries */ running_total = TRB_MAX_BUFF_SIZE - (sg_dma_address(sg) & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; if (running_total != 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < sg_dma_len(sg) && running_total < temp) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } len = min_t(int, len, temp); temp -= len; if (temp == 0) break; } return num_trbs; } static void check_trb_math(struct urb *urb, int num_trbs, int running_total) { if (num_trbs != 0) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated number of " "TRBs, %d left\n", __func__, urb->ep->desc.bEndpointAddress, num_trbs); if (running_total != urb->transfer_buffer_length) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, " "queued %#x (%d), asked for %#x (%d)\n", __func__, urb->ep->desc.bEndpointAddress, running_total, running_total, urb->transfer_buffer_length, urb->transfer_buffer_length); } static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, int start_cycle, struct xhci_generic_trb *start_trb) { /* * Pass all the TRBs to the hardware at once and make sure this write * isn't reordered. */ wmb(); if (start_cycle) start_trb->field[3] |= cpu_to_le32(start_cycle); else start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE); xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } /* * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD * (comprised of sg list entries) can take several service intervals to * transmit. */ int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index); int xhci_interval; int ep_interval; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index); } /* * The TD size is the number of bytes remaining in the TD (including this TRB), * right shifted by 10. * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_td_remainder(unsigned int remainder) { u32 max = (1 << (21 - 17 + 1)) - 1; if ((remainder >> 10) >= max) return max << 17; else return (remainder >> 10) << 17; } /* * For xHCI 1.0 host controllers, TD size is the number of max packet sized * packets remaining in the TD (*not* including this TRB). * * Total TD packet count = total_packet_count = * DIV_ROUND_UP(TD size in bytes / wMaxPacketSize) * * Packets transferred up to and including this TRB = packets_transferred = * rounddown(total bytes transferred including this TRB / wMaxPacketSize) * * TD size = total_packet_count - packets_transferred * * It must fit in bits 21:17, so it can't be bigger than 31. * The last TRB in a TD must have the TD size set to zero. */ static u32 xhci_v1_0_td_remainder(int running_total, int trb_buff_len, unsigned int total_packet_count, struct urb *urb, unsigned int num_trbs_left) { int packets_transferred; /* One TRB with a zero-length data packet. */ if (num_trbs_left == 0 || (running_total == 0 && trb_buff_len == 0)) return 0; /* All the TRB queueing functions don't count the current TRB in * running_total. */ packets_transferred = (running_total + trb_buff_len) / GET_MAX_PACKET(usb_endpoint_maxp(&urb->ep->desc)); if ((total_packet_count - packets_transferred) > 31) return 31 << 17; return (total_packet_count - packets_transferred) << 17; } static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; unsigned int num_trbs; struct urb_priv *urb_priv; struct xhci_td *td; struct scatterlist *sg; int num_sgs; int trb_buff_len, this_sg_len, running_total; unsigned int total_packet_count; bool first_trb; u64 addr; bool more_trbs_coming; struct xhci_generic_trb *start_trb; int start_cycle; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = count_sg_trbs_needed(xhci, urb); num_sgs = urb->num_mapped_sgs; total_packet_count = DIV_ROUND_UP(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (trb_buff_len < 0) return trb_buff_len; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; /* * How much data is in the first TRB? * * There are three forces at work for TRB buffer pointers and lengths: * 1. We don't want to walk off the end of this sg-list entry buffer. * 2. The transfer length that the driver requested may be smaller than * the amount of memory allocated for this scatter-gather list. * 3. TRBs buffers can't cross 64KB boundaries. */ sg = urb->sg; addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 field = 0; u32 length_field = 0; u32 remainder = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; if (TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)) < trb_buff_len) { xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n"); xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n", (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1), (unsigned int) addr + trb_buff_len); } /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb, num_trbs - 1); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer -- * Are we done queueing all the TRBs for this sg entry? */ this_sg_len -= trb_buff_len; if (this_sg_len == 0) { --num_sgs; if (num_sgs == 0) break; sg = sg_next(sg); addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); } else { addr += trb_buff_len; } trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (running_total + trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length - running_total; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* This is very similar to what ehci-q.c qtd_fill() does */ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_trbs; struct xhci_generic_trb *start_trb; bool first_trb; bool more_trbs_coming; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, ret; unsigned int total_packet_count; u64 addr; if (urb->num_sgs) return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index); ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = 0; /* How much data is (potentially) left before the 64KB boundary? */ running_total = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; /* If there's some data on this 64KB chunk, or we have to send a * zero-length transfer, we need at least one TRB */ if (running_total != 0 || urb->transfer_buffer_length == 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < urb->transfer_buffer_length) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */ ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; total_packet_count = DIV_ROUND_UP(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); /* How much data is in the first TRB? */ addr = (u64) urb->transfer_dma; trb_buff_len = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 remainder = 0; field = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb, num_trbs - 1); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer */ addr += trb_buff_len; trb_buff_len = urb->transfer_buffer_length - running_total; if (trb_buff_len > TRB_MAX_BUFF_SIZE) trb_buff_len = TRB_MAX_BUFF_SIZE; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* Caller must have locked xhci->lock */ int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; int num_trbs; int ret; struct usb_ctrlrequest *setup; struct xhci_generic_trb *start_trb; int start_cycle; u32 field, length_field; struct urb_priv *urb_priv; struct xhci_td *td; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; /* * Need to copy setup packet into setup TRB, so we can't use the setup * DMA address. */ if (!urb->setup_packet) return -EINVAL; /* 1 TRB for setup, 1 for status */ num_trbs = 2; /* * Don't need to check if we need additional event data and normal TRBs, * since data in control transfers will never get bigger than 16MB * XXX: can we get a buffer that crosses 64KB boundaries? */ if (urb->transfer_buffer_length > 0) num_trbs++; ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; /* Queue setup TRB - see section 6.4.1.2.1 */ /* FIXME better way to translate setup_packet into two u32 fields? */ setup = (struct usb_ctrlrequest *) urb->setup_packet; field = 0; field |= TRB_IDT | TRB_TYPE(TRB_SETUP); if (start_cycle == 0) field |= 0x1; /* xHCI 1.0 6.4.1.2.1: Transfer Type field */ if (xhci->hci_version == 0x100) { if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_TX_TYPE(TRB_DATA_IN); else field |= TRB_TX_TYPE(TRB_DATA_OUT); } } queue_trb(xhci, ep_ring, true, setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16, le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16, TRB_LEN(8) | TRB_INTR_TARGET(0), /* Immediate data in pointer */ field); /* If there's data, queue data TRBs */ /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field = TRB_ISP | TRB_TYPE(TRB_DATA); else field = TRB_TYPE(TRB_DATA); length_field = TRB_LEN(urb->transfer_buffer_length) | xhci_td_remainder(urb->transfer_buffer_length) | TRB_INTR_TARGET(0); if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_DIR_IN; queue_trb(xhci, ep_ring, true, lower_32_bits(urb->transfer_dma), upper_32_bits(urb->transfer_dma), length_field, field | ep_ring->cycle_state); } /* Save the DMA address of the last TRB in the TD */ td->last_trb = ep_ring->enqueue; /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */ /* If the device sent data, the status stage is an OUT transfer */ if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN) field = 0; else field = TRB_DIR_IN; queue_trb(xhci, ep_ring, false, 0, 0, TRB_INTR_TARGET(0), /* Event on completion */ field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state); giveback_first_trb(xhci, slot_id, ep_index, 0, start_cycle, start_trb); return 0; } static int count_isoc_trbs_needed(struct xhci_hcd *xhci, struct urb *urb, int i) { int num_trbs = 0; u64 addr, td_len; addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset); td_len = urb->iso_frame_desc[i].length; num_trbs = DIV_ROUND_UP(td_len + (addr & (TRB_MAX_BUFF_SIZE - 1)), TRB_MAX_BUFF_SIZE); if (num_trbs == 0) num_trbs++; return num_trbs; } /* * The transfer burst count field of the isochronous TRB defines the number of * bursts that are required to move all packets in this TD. Only SuperSpeed * devices can burst up to bMaxBurst number of packets per service interval. * This field is zero based, meaning a value of zero in the field means one * burst. Basically, for everything but SuperSpeed devices, this field will be * zero. Only xHCI 1.0 host controllers support this field. */ static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; if (xhci->hci_version < 0x100 || udev->speed != USB_SPEED_SUPER) return 0; max_burst = urb->ep->ss_ep_comp.bMaxBurst; return roundup(total_packet_count, max_burst + 1) - 1; } /* * Returns the number of packets in the last "burst" of packets. This field is * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so * the last burst packet count is equal to the total number of packets in the * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst * must contain (bMaxBurst + 1) number of packets, but the last burst can * contain 1 to (bMaxBurst + 1) packets. */ static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; unsigned int residue; if (xhci->hci_version < 0x100) return 0; switch (udev->speed) { case USB_SPEED_SUPER: /* bMaxBurst is zero based: 0 means 1 packet per burst */ max_burst = urb->ep->ss_ep_comp.bMaxBurst; residue = total_packet_count % (max_burst + 1); /* If residue is zero, the last burst contains (max_burst + 1) * number of packets, but the TLBPC field is zero-based. */ if (residue == 0) return max_burst; return residue - 1; default: if (total_packet_count == 0) return 0; return total_packet_count - 1; } } /* This is for isoc transfer */ static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_tds, trbs_per_td; struct xhci_generic_trb *start_trb; bool first_trb; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, td_len, td_remain_len, ret; u64 start_addr, addr; int i, j; bool more_trbs_coming; ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; num_tds = urb->number_of_packets; if (num_tds < 1) { xhci_dbg(xhci, "Isoc URB with zero packets?\n"); return -EINVAL; } start_addr = (u64) urb->transfer_dma; start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; urb_priv = urb->hcpriv; /* Queue the first TRB, even if it's zero-length */ for (i = 0; i < num_tds; i++) { unsigned int total_packet_count; unsigned int burst_count; unsigned int residue; first_trb = true; running_total = 0; addr = start_addr + urb->iso_frame_desc[i].offset; td_len = urb->iso_frame_desc[i].length; td_remain_len = td_len; total_packet_count = DIV_ROUND_UP(td_len, GET_MAX_PACKET( usb_endpoint_maxp(&urb->ep->desc))); /* A zero-length transfer still involves at least one packet. */ if (total_packet_count == 0) total_packet_count++; burst_count = xhci_get_burst_count(xhci, urb->dev, urb, total_packet_count); residue = xhci_get_last_burst_packet_count(xhci, urb->dev, urb, total_packet_count); trbs_per_td = count_isoc_trbs_needed(xhci, urb, i); ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, trbs_per_td, urb, i, mem_flags); if (ret < 0) { if (i == 0) return ret; goto cleanup; } td = urb_priv->td[i]; for (j = 0; j < trbs_per_td; j++) { u32 remainder = 0; field = 0; if (first_trb) { field = TRB_TBC(burst_count) | TRB_TLBPC(residue); /* Queue the isoc TRB */ field |= TRB_TYPE(TRB_ISOC); /* Assume URB_ISO_ASAP is set */ field |= TRB_SIA; if (i == 0) { if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; first_trb = false; } else { /* Queue other normal TRBs */ field |= TRB_TYPE(TRB_NORMAL); field |= ep_ring->cycle_state; } /* Only set interrupt on short packet for IN EPs */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Chain all the TRBs together; clear the chain bit in * the last TRB to indicate it's the last TRB in the * chain. */ if (j < trbs_per_td - 1) { field |= TRB_CHAIN; more_trbs_coming = true; } else { td->last_trb = ep_ring->enqueue; field |= TRB_IOC; if (xhci->hci_version == 0x100 && !(xhci->quirks & XHCI_AVOID_BEI)) { /* Set BEI bit except for the last td */ if (i < num_tds - 1) field |= TRB_BEI; } more_trbs_coming = false; } /* Calculate TRB length */ trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)); if (trb_buff_len > td_remain_len) trb_buff_len = td_remain_len; /* Set the TRB length, TD size, & interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( td_len - running_total); } else { remainder = xhci_v1_0_td_remainder( running_total, trb_buff_len, total_packet_count, urb, (trbs_per_td - j - 1)); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field); running_total += trb_buff_len; addr += trb_buff_len; td_remain_len -= trb_buff_len; } /* Check TD length */ if (running_total != td_len) { xhci_err(xhci, "ISOC TD length unmatch\n"); ret = -EINVAL; goto cleanup; } } if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_disable(); } xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++; giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; cleanup: /* Clean up a partially enqueued isoc transfer. */ for (i--; i >= 0; i--) list_del_init(&urb_priv->td[i]->td_list); /* Use the first TD as a temporary variable to turn the TDs we've queued * into No-ops with a software-owned cycle bit. That way the hardware * won't accidentally start executing bogus TDs when we partially * overwrite them. td->first_trb and td->start_seg are already set. */ urb_priv->td[0]->last_trb = ep_ring->enqueue; /* Every TRB except the first & last will have its cycle bit flipped. */ td_to_noop(xhci, ep_ring, urb_priv->td[0], true); /* Reset the ring enqueue back to the first TRB and its cycle bit. */ ep_ring->enqueue = urb_priv->td[0]->first_trb; ep_ring->enq_seg = urb_priv->td[0]->start_seg; ep_ring->cycle_state = start_cycle; ep_ring->num_trbs_free = ep_ring->num_trbs_free_temp; usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); return ret; } /* * Check transfer ring to guarantee there is enough room for the urb. * Update ISO URB start_frame and interval. * Update interval as xhci_queue_intr_tx does. Just use xhci frame_index to * update the urb->start_frame by now. * Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input. */ int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx; int start_frame; int xhci_interval; int ep_interval; int num_tds, num_trbs, i; int ret; xdev = xhci->devs[slot_id]; ep_ring = xdev->eps[ep_index].ring; ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); num_trbs = 0; num_tds = urb->number_of_packets; for (i = 0; i < num_tds; i++) num_trbs += count_isoc_trbs_needed(xhci, urb, i); /* Check the ring to guarantee there is enough room for the whole urb. * Do not insert any td of the urb to the ring if the check failed. */ ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index); start_frame &= 0x3fff; urb->start_frame = start_frame; if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->start_frame >>= 3; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } ep_ring->num_trbs_free_temp = ep_ring->num_trbs_free; return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index); } /**** Command Ring Operations ****/ /* Generic function for queueing a command TRB on the command ring. * Check to make sure there's room on the command ring for one command TRB. * Also check that there's room reserved for commands that must not fail. * If this is a command that must not fail, meaning command_must_succeed = TRUE, * then only check for the number of reserved spots. * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB * because the command event handler may want to resubmit a failed command. */ static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4, bool command_must_succeed) { int reserved_trbs = xhci->cmd_ring_reserved_trbs; int ret; if (!command_must_succeed) reserved_trbs++; ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING, reserved_trbs, GFP_ATOMIC); if (ret < 0) { xhci_err(xhci, "ERR: No room for command on command ring\n"); if (command_must_succeed) xhci_err(xhci, "ERR: Reserved TRB counting for " "unfailable commands failed.\n"); return ret; } queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3, field4 | xhci->cmd_ring->cycle_state); return 0; } /* Queue a slot enable or disable request on the command ring */ int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue an address device command TRB */ int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } int xhci_queue_vendor_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4) { return queue_command(xhci, field1, field2, field3, field4, false); } /* Queue a reset device command TRB */ int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue a configure endpoint command TRB */ int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id), command_must_succeed); } /* Queue an evaluate context command TRB */ int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id), false); } /* * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop * activity on an endpoint that is about to be suspended. */ int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, int suspend) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_STOP_RING); u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type | trb_suspend, false); } /* Set Transfer Ring Dequeue Pointer command. * This should not be used for endpoints that have streams enabled. */ static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state) { dma_addr_t addr; u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id); u32 type = TRB_TYPE(TRB_SET_DEQ); struct xhci_virt_ep *ep; addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr); if (addr == 0) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n", deq_seg, deq_ptr); return 0; } ep = &xhci->devs[slot_id]->eps[ep_index]; if ((ep->ep_state & SET_DEQ_PENDING)) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n"); return 0; } ep->queued_deq_seg = deq_seg; ep->queued_deq_ptr = deq_ptr; return queue_command(xhci, lower_32_bits(addr) | cycle_state, upper_32_bits(addr), trb_stream_id, trb_slot_id | trb_ep_index | type, false); } int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_RESET_EP); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type, false); }
{ "content_hash": "7924ef24dc3ba76de4e09e89bd5edf56", "timestamp": "", "source": "github", "line_count": 3982, "max_line_length": 92, "avg_line_length": 31.2579105976896, "alnum_prop": 0.6595778868633957, "repo_name": "indashnet/InDashNet.Open.UN2000", "id": "a3c93745401c8fe9b35effdf60982799b0739fd5", "size": "125254", "binary": false, "copies": "69", "ref": "refs/heads/master", "path": "lichee/linux-3.4/drivers/usb/host/xhci-ring.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.google.rubidium; import java.util.Arrays; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.junit.Rule; import org.junit.Test; public class DataProcessorTest { @Rule public final transient TestPipeline p = TestPipeline.create(); @Test public void BuildUserToSourceMapTest() { String[] cmdArgs = new String[] { "--sourceStartDate=2022-01-15", "--sourceEndDate=2022-01-15", "--attributionSourceFileName=attribution_source.json", "--inputDirectory=testdata" }; SimulationConfig options = PipelineOptionsFactory.fromArgs(cmdArgs).withValidation().as(SimulationConfig.class); String sourceData1 = "{\"user_id\": \"U1\", \"source_event_id\": 1, \"source_type\": \"EVENT\", \"publisher\":" + " \"https://www.example1.com/s1\", \"web_destination\":" + " \"https://www.example2.com/d1\", \"enrollment_id\":" + " \"https://www.example3.com/r1\", \"event_time\": 1642218050000, \"expiry\":" + " 1647645724, \"priority\": 100, \"registrant\": \"https://www.example3.com/e1\"," + " \"dedup_keys\": [], \"install_attribution_window\": 100," + " \"post_install_exclusivity_window\": 101, \"filter_data\": {\"type\": [\"1\"," + " \"2\", \"3\", \"4\"], \"ctid\": [\"id\"]}, \"aggregation_keys\": [{\"id\":" + " \"myId\", \"key_piece\": \"0xFFFFFFFFFFFFFF\" }]}"; String sourceData2 = "{\"user_id\": \"U1\", \"source_event_id\": 2, \"source_type\": \"EVENT\", \"publisher\":" + " \"https://www.example1.com/s2\", \"web_destination\":" + " \"https://www.example2.com/d2\", \"enrollment_id\":" + " \"https://www.example3.com/r1\", \"event_time\": 1642235602000, \"expiry\":" + " 1647645724, \"priority\": 100, \"registrant\": \"https://www.example3.com/e1\"," + " \"dedup_keys\": [], \"install_attribution_window\": 100," + " \"post_install_exclusivity_window\": 101, \"filter_data\": {\"type\": [\"7\"," + " \"8\", \"9\", \"10\"], \"ctid\": [\"id\"]}, \"aggregation_keys\": [{\"id\":" + " \"campaignCounts\", \"key_piece\": \"0x159\"}, {\"id\": \"geoValue\"," + " \"key_piece\": \"0x5\"}]}"; String sourceData3 = "{\"user_id\": \"U2\", \"source_event_id\": 3, \"source_type\": \"NAVIGATION\"," + " \"publisher\": \"https://www.example1.com/s3\", \"web_destination\":" + " \"https://www.example2.com/d3\", \"enrollment_id\":" + " \"https://www.example3.com/r1\", \"event_time\": 1642249235000, \"expiry\":" + " 1647645724, \"priority\": 100, \"registrant\": \"https://www.example3.com/e1\"," + " \"dedup_keys\": [], \"install_attribution_window\": 100," + " \"post_install_exclusivity_window\": 101, \"filter_data\": {\"type\": [\"1\"," + " \"2\", \"3\", \"4\"], \"ctid\": [\"id\"]}, \"aggregation_keys\": [{\"id\":" + " \"myId3\", \"key_piece\": \"0xFFFFFFFFFFFFFFFFFFFFFF\"}]}"; JSONParser parser = new JSONParser(); try { Source source1 = SourceProcessor.buildSourceFromJson((JSONObject) parser.parse(sourceData1)); Source source2 = SourceProcessor.buildSourceFromJson((JSONObject) parser.parse(sourceData2)); Source source3 = SourceProcessor.buildSourceFromJson((JSONObject) parser.parse(sourceData3)); PCollection<KV<String, Source>> userToAdtechSourceData = DataProcessor.buildUserToSourceMap(p, options); PAssert.that(userToAdtechSourceData) .containsInAnyOrder( Arrays.asList(KV.of("U1", source1), KV.of("U1", source2), KV.of("U2", source3))); } catch (Exception e) { e.printStackTrace(); } p.run().waitUntilFinish(); } @Test public void BuildUserToTriggerMapTest() { String[] cmdArgs = new String[] { "--triggerStartDate=2022-01-15", "--triggerEndDate=2022-01-15", "--triggerFileName=trigger.json", "--inputDirectory=testdata" }; SimulationConfig options = PipelineOptionsFactory.fromArgs(cmdArgs).withValidation().as(SimulationConfig.class); String triggerData1 = "{\"user_id\": \"U1\", \"attribution_destination\": \"https://www.example2.com/d1\"," + " \"destination_type\": \"WEB\", \"enrollment_id\": \"https://www.example3.com/r1\"," + " \"trigger_time\": 1642271444000, \"event_trigger_data\": [{\"trigger_data\": 1000," + " \"priority\": 100, \"deduplication_key\": 1}], \"registrant\":" + " \"http://example1.com/4\", \"aggregatable_trigger_data\": [{\"key_piece\":" + " \"0x400\", \"source_keys\": [\"campaignCounts\"], \"filters\": {\"key_1\":" + " [\"value_1\", \"value_2\"], \"key_2\": [\"value_1\", \"value_2\"]} }]," + " \"aggregatable_values\": {\"campaignCounts\": 32768,\"geoValue\": 1664}," + " \"filters\": \"{\\\"key_1\\\": [\\\"value_1\\\", \\\"value_2\\\"], \\\"key_2\\\":" + " [\\\"value_1\\\", \\\"value_2\\\"]}\"}"; String triggerData2 = "{\"user_id\": \"U1\", \"attribution_destination\": \"https://www.example2.com/d3\"," + " \"destination_type\": \"WEB\", \"enrollment_id\": \"https://www.example3.com/r1\"," + " \"trigger_time\": 1642273950000, \"event_trigger_data\": [{\"trigger_data\": 1000," + " \"priority\": 100, \"deduplication_key\": 1}], \"registrant\":" + " \"http://example1.com/4\", \"aggregatable_trigger_data\": [{\"key_piece\":" + " \"0x400\", \"source_keys\": [\"campaignCounts\"], \"not_filters\": {\"key_1x\":" + " [\"value_1\", \"value_2\"], \"key_2x\": [\"value_1\", \"value_2\"]} }]," + " \"aggregatable_values\": {\"campaignCounts\": 32768,\"geoValue\": 1664}," + " \"filters\": \"{\\\"key_1\\\": [\\\"value_1\\\", \\\"value_2\\\"], \\\"key_2\\\":" + " [\\\"value_1\\\", \\\"value_2\\\"]}\"}"; String triggerData3 = "{\"user_id\": \"U2\", \"attribution_destination\": \"https://www.example2.com/d3\"," + " \"destination_type\": \"WEB\", \"enrollment_id\": \"https://www.example3.com/r1\"," + " \"trigger_time\": 1642288930000, \"event_trigger_data\": [{\"trigger_data\": 1000," + " \"priority\": 100, \"deduplication_key\": 1}], \"registrant\":" + " \"http://example1.com/4\", \"aggregatable_trigger_data\": [{\"key_piece\":" + " \"0x400\", \"source_keys\": [\"campaignCounts\"], \"filters\": {\"key_1\":" + " [\"value_1\", \"value_2\"], \"key_2\": [\"value_1\", \"value_2\"]} }]," + " \"aggregatable_values\": {\"campaignCounts\": 32768,\"geoValue\": 1664}," + " \"filters\": \"{\\\"key_1\\\": [\\\"value_1\\\", \\\"value_2\\\"], \\\"key_2\\\":" + " [\\\"value_1\\\", \\\"value_2\\\"]}\"}"; PCollection<KV<String, Trigger>> userToAdtechTriggerData = DataProcessor.buildUserToTriggerMap(p, options); JSONParser parser = new JSONParser(); try { Trigger trigger1 = TriggerProcessor.buildTriggerFromJson((JSONObject) parser.parse(triggerData1)); Trigger trigger2 = TriggerProcessor.buildTriggerFromJson((JSONObject) parser.parse(triggerData2)); Trigger trigger3 = TriggerProcessor.buildTriggerFromJson((JSONObject) parser.parse(triggerData3)); PAssert.that(userToAdtechTriggerData) .containsInAnyOrder( Arrays.asList(KV.of("U1", trigger1), KV.of("U1", trigger2), KV.of("U2", trigger3))); } catch (Exception e) { e.printStackTrace(); } p.run().waitUntilFinish(); } }
{ "content_hash": "0e9895b35cdaa39c9fa805b0a33506ac", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 99, "avg_line_length": 54.87074829931973, "alnum_prop": 0.5426481527398959, "repo_name": "privacysandbox/measurement-simulation", "id": "0b77de276183fd7e7fa1eed8cffa71b4f0afb9d9", "size": "8660", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "javatests/com/google/rubidium/DataProcessorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "463599" }, { "name": "Python", "bytes": "28221" }, { "name": "Starlark", "bytes": "19851" } ], "symlink_target": "" }
<?php namespace Barman\Annotation; use Doctrine\Common\Annotations\Annotation\Target; use Barman\Annotation; use Barman\AutoArguments; use Barman\Exception\MutatorException; use Barman\Step; use Barman\Variable\ArgumentVariable; /** * @Annotation * @Target({"CLASS", "METHOD", "ANNOTATION"}) */ class Context extends Step implements ArgumentVariable, AutoArguments { /** * @var string */ public $name; /** * @var string */ public $class; /** * @throws MutatorException */ public function onCreate(): void { if ($this->isClassAnnotation()) { if (!is_string($this->name)) { throw new MutatorException('Define name of context.'); } if ($this->name === 'default') { throw new MutatorException('"Default" name of context is reserved.'); } if ($this->getClassKeeper()->hasContext($this->name)) { throw new MutatorException(sprintf('"%s" context is already defined.', $this->name )); } if (!class_exists($this->class)) { throw new MutatorException(sprintf('"%s" context class not found.', $this->name )); } $this->getClassKeeper()->addContext($this->name, $this->class); } // Rest of code is executed when Context is used as Step if (!$this->isMethodAnnotation()) { return; } if ($this->name === null) { $this->name = 'default'; $reflection = $this->getReflectionClass(); $context_class = '\\' . $reflection->getNamespaceName() . '\\' . $reflection->getShortName() . 'Context'; if (!isset($this->getClassKeeper()->getContexts()[$this->name]) && class_exists($context_class, false)) { $this->getClassKeeper()->addContext($this->name, $context_class); } } if (!isset($this->getClassKeeper()->getContexts()[$this->name])) { throw new MutatorException(sprintf('"%s" context is not registered', $this->name )); } } public function onMutate(): void { if ($this->isMethodAnnotation()) { parent::onMutate(); $name = str_replace('_', '', ucwords($this->name, '_.')); $this->getStepKeeper()->setCallExpression("\$this->get{$name}Context()->"); } } /** * @return string */ public function getArgumentVariableName(): string { return $this->name; } /** * @return string */ public function getArgumentVariableExpression(): string { return '$this->get' . str_replace('_', '', ucwords($this->name, '_')) . 'Context()'; } /** * @return string */ public function getAutoArgumentsClass(): string { return $this->getClassKeeper()->getContexts()[$this->name]; } /** * @return string */ public function getAutoArgumentsMethod(): string { return $this->method; } }
{ "content_hash": "f27c35d7902da504a156990e586cce84", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 117, "avg_line_length": 25.739837398373982, "alnum_prop": 0.5290587492103601, "repo_name": "perfumer/contracts", "id": "e5e840249855a9fb801c631df218bd0588b3d088", "size": "3166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Annotation/Context.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "115496" }, { "name": "Shell", "bytes": "65" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "83383e96f810bbd1eaed93b809a31b4a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "95a0859acf74c5ee17593123bf747f982ba7dfa1", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Chlorophyta/Ulvophyceae/Codiolales/Acrosiphoniaceae/Urospora/Urospora wormskioldii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); // ------------------------------------------------------------------------ /** * Postgre Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_driver extends CI_DB { var $dbdriver = 'postgre'; var $_escape_char = '"'; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' RANDOM()'; // database specific random keyword /** * Connection String * * @access private * @return string */ function _connect_string() { $components = array( 'hostname' => 'host', 'port' => 'port', 'database' => 'dbname', 'username' => 'user', 'password' => 'password' ); $connect_string = ""; foreach ($components as $key => $val) { if (isset($this->$key) && $this->$key != '') { $connect_string .= " $val=".$this->$key; } } return trim($connect_string); } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { return @pg_connect($this->_connect_string()); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { return @pg_pconnect($this->_connect_string()); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (pg_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { // Not needed for Postgre so we'll return TRUE return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @pg_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; return @pg_exec($this->conn_id, "begin"); } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return @pg_exec($this->conn_id, "commit"); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } return @pg_exec($this->conn_id, "rollback"); } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } $str = pg_escape_string($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @pg_affected_rows($this->result_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { $v = $this->_version(); $v = $v['server']; $table = func_num_args() > 0 ? func_get_arg(0) : NULL; $column = func_num_args() > 1 ? func_get_arg(1) : NULL; if ($table == NULL && $v >= '8.1') { $sql='SELECT LASTVAL() as ins_id'; } elseif ($table != NULL && $column != NULL && $v >= '8.0') { $sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column); $query = $this->query($sql); $row = $query->row(); $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq); } elseif ($table != NULL) { // seq_name passed in table parameter $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table); } else { return pg_last_oid($this->result_id); } $query = $this->query($sql); $row = $query->row(); return $row->ins_id; } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'"; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT * FROM ".$table." LIMIT 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return pg_last_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return ''; } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return implode(', ', $tables); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $sql .= "LIMIT ".$limit; if ($offset > 0) { $sql .= " OFFSET ".$offset; } return $sql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @pg_close($conn_id); } } /* End of file postgre_driver.php */ /* Location: ./system/database/drivers/postgre/postgre_driver.php */
{ "content_hash": "adff0c30d98fd849c6ed9e853feb4f13", "timestamp": "", "source": "github", "line_count": 691, "max_line_length": 155, "avg_line_length": 21.926193921852388, "alnum_prop": 0.514157481354366, "repo_name": "alvescaio/SisGO", "id": "9c93ab6085aac0f89e0d2aeb28080479bd2c4385", "size": "15598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "system/database/drivers/postgre/postgre_driver.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "151" }, { "name": "CSS", "bytes": "189237" }, { "name": "HTML", "bytes": "1329991" }, { "name": "JavaScript", "bytes": "261629" }, { "name": "PHP", "bytes": "1250193" } ], "symlink_target": "" }
.class final Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable; .super Ljava/lang/Object; .source "ViewRootImpl.java" # interfaces .implements Ljava/lang/Runnable; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/view/ViewRootImpl; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x10 name = "InvalidateOnAnimationRunnable" .end annotation # instance fields .field private mPosted:Z .field private mTempViewRects:[Landroid/view/View$AttachInfo$InvalidateInfo; .field private mTempViews:[Landroid/view/View; .field private final mViewRects:Ljava/util/ArrayList; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/ArrayList", "<", "Landroid/view/View$AttachInfo$InvalidateInfo;", ">;" } .end annotation .end field .field private final mViews:Ljava/util/ArrayList; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/ArrayList", "<", "Landroid/view/View;", ">;" } .end annotation .end field .field final synthetic this$0:Landroid/view/ViewRootImpl; # direct methods .method constructor <init>(Landroid/view/ViewRootImpl;)V .locals 1 .prologue .line 7082 iput-object p1, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->this$0:Landroid/view/ViewRootImpl; invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 7084 new-instance v0, Ljava/util/ArrayList; invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V iput-object v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; .line 7085 new-instance v0, Ljava/util/ArrayList; invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V iput-object v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; return-void .end method .method private postIfNeededLocked()V .locals 3 .prologue const/4 v2, 0x1 .line 7158 iget-boolean v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mPosted:Z if-nez v0, :cond_0 .line 7159 iget-object v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->this$0:Landroid/view/ViewRootImpl; iget-object v0, v0, Landroid/view/ViewRootImpl;->mChoreographer:Landroid/view/Choreographer; const/4 v1, 0x0 invoke-virtual {v0, v2, p0, v1}, Landroid/view/Choreographer;->postCallback(ILjava/lang/Runnable;Ljava/lang/Object;)V .line 7160 iput-boolean v2, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mPosted:Z .line 7162 :cond_0 return-void .end method # virtual methods .method public addView(Landroid/view/View;)V .locals 1 .param p1, "view" # Landroid/view/View; .prologue .line 7091 monitor-enter p0 .line 7092 :try_start_0 iget-object v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z .line 7093 invoke-direct {p0}, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->postIfNeededLocked()V .line 7094 monitor-exit p0 .line 7095 return-void .line 7094 :catchall_0 move-exception v0 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .end method .method public addViewRect(Landroid/view/View$AttachInfo$InvalidateInfo;)V .locals 1 .param p1, "info" # Landroid/view/View$AttachInfo$InvalidateInfo; .prologue .line 7098 monitor-enter p0 .line 7099 :try_start_0 iget-object v0, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z .line 7100 invoke-direct {p0}, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->postIfNeededLocked()V .line 7101 monitor-exit p0 .line 7102 return-void .line 7101 :catchall_0 move-exception v0 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .end method .method public removeView(Landroid/view/View;)V .locals 6 .param p1, "view" # Landroid/view/View; .prologue .line 7105 monitor-enter p0 .line 7106 :try_start_0 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; invoke-virtual {v3, p1}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z .line 7108 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v3}, Ljava/util/ArrayList;->size()I move-result v0 .local v0, "i":I move v1, v0 .end local v0 # "i":I .local v1, "i":I :goto_0 add-int/lit8 v0, v1, -0x1 .end local v1 # "i":I .restart local v0 # "i":I if-lez v1, :cond_1 .line 7109 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v3, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object; move-result-object v2 check-cast v2, Landroid/view/View$AttachInfo$InvalidateInfo; .line 7110 .local v2, "info":Landroid/view/View$AttachInfo$InvalidateInfo; iget-object v3, v2, Landroid/view/View$AttachInfo$InvalidateInfo;->target:Landroid/view/View; if-ne v3, p1, :cond_0 .line 7111 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v3, v0}, Ljava/util/ArrayList;->remove(I)Ljava/lang/Object; .line 7112 invoke-virtual {v2}, Landroid/view/View$AttachInfo$InvalidateInfo;->recycle()V :cond_0 move v1, v0 .line 7114 .end local v0 # "i":I .restart local v1 # "i":I goto :goto_0 .line 7116 .end local v1 # "i":I .end local v2 # "info":Landroid/view/View$AttachInfo$InvalidateInfo; .restart local v0 # "i":I :cond_1 iget-boolean v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mPosted:Z if-eqz v3, :cond_2 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; invoke-virtual {v3}, Ljava/util/ArrayList;->isEmpty()Z move-result v3 if-eqz v3, :cond_2 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v3}, Ljava/util/ArrayList;->isEmpty()Z move-result v3 if-eqz v3, :cond_2 .line 7117 iget-object v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->this$0:Landroid/view/ViewRootImpl; iget-object v3, v3, Landroid/view/ViewRootImpl;->mChoreographer:Landroid/view/Choreographer; const/4 v4, 0x1 const/4 v5, 0x0 invoke-virtual {v3, v4, p0, v5}, Landroid/view/Choreographer;->removeCallbacks(ILjava/lang/Runnable;Ljava/lang/Object;)V .line 7118 const/4 v3, 0x0 iput-boolean v3, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mPosted:Z .line 7120 :cond_2 monitor-exit p0 .line 7121 return-void .line 7120 .end local v0 # "i":I :catchall_0 move-exception v3 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v3 .end method .method public run()V .locals 9 .prologue .line 7127 monitor-enter p0 .line 7128 const/4 v4, 0x0 :try_start_0 iput-boolean v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mPosted:Z .line 7130 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; invoke-virtual {v4}, Ljava/util/ArrayList;->size()I move-result v2 .line 7131 .local v2, "viewCount":I if-eqz v2, :cond_0 .line 7132 iget-object v5, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViews:[Landroid/view/View; if-eqz v4, :cond_2 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViews:[Landroid/view/View; :goto_0 invoke-virtual {v5, v4}, Ljava/util/ArrayList;->toArray([Ljava/lang/Object;)[Ljava/lang/Object; move-result-object v4 check-cast v4, [Landroid/view/View; iput-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViews:[Landroid/view/View; .line 7134 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViews:Ljava/util/ArrayList; invoke-virtual {v4}, Ljava/util/ArrayList;->clear()V .line 7137 :cond_0 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v4}, Ljava/util/ArrayList;->size()I move-result v3 .line 7138 .local v3, "viewRectCount":I if-eqz v3, :cond_1 .line 7139 iget-object v5, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViewRects:[Landroid/view/View$AttachInfo$InvalidateInfo; if-eqz v4, :cond_3 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViewRects:[Landroid/view/View$AttachInfo$InvalidateInfo; :goto_1 invoke-virtual {v5, v4}, Ljava/util/ArrayList;->toArray([Ljava/lang/Object;)[Ljava/lang/Object; move-result-object v4 check-cast v4, [Landroid/view/View$AttachInfo$InvalidateInfo; iput-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViewRects:[Landroid/view/View$AttachInfo$InvalidateInfo; .line 7141 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mViewRects:Ljava/util/ArrayList; invoke-virtual {v4}, Ljava/util/ArrayList;->clear()V .line 7143 :cond_1 monitor-exit p0 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .line 7145 const/4 v0, 0x0 .local v0, "i":I :goto_2 if-ge v0, v2, :cond_4 .line 7146 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViews:[Landroid/view/View; aget-object v4, v4, v0 invoke-virtual {v4}, Landroid/view/View;->invalidate()V .line 7147 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViews:[Landroid/view/View; const/4 v5, 0x0 aput-object v5, v4, v0 .line 7145 add-int/lit8 v0, v0, 0x1 goto :goto_2 .line 7132 .end local v0 # "i":I .end local v3 # "viewRectCount":I :cond_2 :try_start_1 new-array v4, v2, [Landroid/view/View; goto :goto_0 .line 7139 .restart local v3 # "viewRectCount":I :cond_3 new-array v4, v3, [Landroid/view/View$AttachInfo$InvalidateInfo; goto :goto_1 .line 7143 .end local v2 # "viewCount":I .end local v3 # "viewRectCount":I :catchall_0 move-exception v4 monitor-exit p0 :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 throw v4 .line 7150 .restart local v0 # "i":I .restart local v2 # "viewCount":I .restart local v3 # "viewRectCount":I :cond_4 const/4 v0, 0x0 :goto_3 if-ge v0, v3, :cond_5 .line 7151 iget-object v4, p0, Landroid/view/ViewRootImpl$InvalidateOnAnimationRunnable;->mTempViewRects:[Landroid/view/View$AttachInfo$InvalidateInfo; aget-object v1, v4, v0 .line 7152 .local v1, "info":Landroid/view/View$AttachInfo$InvalidateInfo; iget-object v4, v1, Landroid/view/View$AttachInfo$InvalidateInfo;->target:Landroid/view/View; iget v5, v1, Landroid/view/View$AttachInfo$InvalidateInfo;->left:I iget v6, v1, Landroid/view/View$AttachInfo$InvalidateInfo;->top:I iget v7, v1, Landroid/view/View$AttachInfo$InvalidateInfo;->right:I iget v8, v1, Landroid/view/View$AttachInfo$InvalidateInfo;->bottom:I invoke-virtual {v4, v5, v6, v7, v8}, Landroid/view/View;->invalidate(IIII)V .line 7153 invoke-virtual {v1}, Landroid/view/View$AttachInfo$InvalidateInfo;->recycle()V .line 7150 add-int/lit8 v0, v0, 0x1 goto :goto_3 .line 7155 .end local v1 # "info":Landroid/view/View$AttachInfo$InvalidateInfo; :cond_5 return-void .end method
{ "content_hash": "1aa765a7ae6d19b0c0b6e437c3470977", "timestamp": "", "source": "github", "line_count": 484, "max_line_length": 144, "avg_line_length": 26.41322314049587, "alnum_prop": 0.6912546933667084, "repo_name": "GaHoKwan/tos_device_meizu_mx4", "id": "934cedb423a30565e870d24a6a11e80d57e851d2", "size": "12784", "binary": false, "copies": "2", "ref": "refs/heads/TPS-YUNOS", "path": "patch/smali/pack/framework.jar/smali/android/view/ViewRootImpl$InvalidateOnAnimationRunnable.smali", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2407" }, { "name": "Groff", "bytes": "8687" }, { "name": "Makefile", "bytes": "31774" }, { "name": "Shell", "bytes": "6226" }, { "name": "Smali", "bytes": "350951922" } ], "symlink_target": "" }
using Esri.ArcGISRuntime.Layers; using System.Diagnostics; using System.Windows; using System.Windows.Controls; namespace ArcGISRuntimeSDKDotNet_DesktopSamples.Samples { /// <summary> /// Demonstrates adding a Web tiled layer to a Map in XAML, and changing layer properties in code behind. /// Also demonstrates including Attribution as per Terms of Use for the various layers. /// </summary> /// <title>Web Tiled Layer</title> /// <category>Layers</category> /// <subcategory>Tiled Layers</subcategory> public partial class WebTiledLayerSample : UserControl { public WebTiledLayerSample() { InitializeComponent(); MyMapView.SpatialReferenceChanged += MyMapView_SpatialReferenceChanged; } void MyMapView_SpatialReferenceChanged(object sender, System.EventArgs e) { cboLayers.SelectedIndex = 0; } private void cboLayers_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (MyMapView.SpatialReference == null) return; MyMapView.Map.Layers.Remove("MyWebTiledLayer"); WebTiledLayer webTiledLayer = new WebTiledLayer() { ID = "MyWebTiledLayer" }; switch (cboLayers.SelectedIndex) { //Esri National Geographic case 0: webTiledLayer.TemplateUri = "http://{subDomain}.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{level}/{row}/{col}"; webTiledLayer.SubDomains = new string[] { "server", "services" }; Attribution.Content = Attribution.Resources["NatGeoAttribution"]; Attribution.Visibility = Visibility.Visible; break; //MapQuest case 1: webTiledLayer.TemplateUri = "http://otile1.mqcdn.com/tiles/1.0.0/vx/map/{level}/{col}/{row}.jpg"; Attribution.Content = Attribution.Resources["MapQuestAttribution"]; Attribution.Visibility = Visibility.Visible; break; //OpenCycleMap case 2: webTiledLayer.TemplateUri = "http://{subDomain}.tile.opencyclemap.org/cycle/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c" }; Attribution.Content = Attribution.Resources["OpenCycleMapAttribution"]; Attribution.Visibility = Visibility.Visible; break; //Cloudmade Midnight Commander case 3: webTiledLayer.TemplateUri = "http://{subDomain}.tile.cloudmade.com/1a1b06b230af4efdbb989ea99e9841af/999/256/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c" }; Attribution.Visibility = Visibility.Collapsed; // No attribution info here, so keep dialog collapsed. break; //Cloudmade Pale Dawn case 4: webTiledLayer.TemplateUri = "http://{subDomain}.tile.cloudmade.com/1a1b06b230af4efdbb989ea99e9841af/998/256/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c" }; Attribution.Visibility = Visibility.Collapsed; // No attribution info here, so keep dialog collapsed. break; //MapBox Dark case 5: webTiledLayer.TemplateUri = "http://{subDomain}.tiles.mapbox.com/v3/examples.map-cnkhv76j/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c", "d" }; Attribution.Content = Attribution.Resources["MapboxAttribution"]; Attribution.Visibility = Visibility.Visible; break; //Mapbox Terrain case 6: webTiledLayer.TemplateUri = "http://{subDomain}.tiles.mapbox.com/v3/mapbox.mapbox-warden/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c", "d" }; Attribution.Content = Attribution.Resources["MapboxAttribution"]; Attribution.Visibility = Visibility.Visible; break; //Stamen Terrain case 7: webTiledLayer.TemplateUri = "http://{subDomain}.tile.stamen.com/terrain/{level}/{col}/{row}.jpg"; webTiledLayer.SubDomains = new string[] { "a", "b", "c", "d" }; Attribution.Content = Attribution.Resources["StamenOtherAttribution"]; Attribution.Visibility = Visibility.Visible; break; //Stamen Watercolor case 8: webTiledLayer.TemplateUri = "http://{subDomain}.tile.stamen.com/watercolor/{level}/{col}/{row}.jpg"; webTiledLayer.SubDomains = new string[] { "a", "b", "c", "d" }; Attribution.Content = Attribution.Resources["StamenOtherAttribution"]; Attribution.Visibility = Visibility.Visible; break; //Stamen Toner case 9: webTiledLayer.TemplateUri = "http://{subDomain}.tile.stamen.com/toner/{level}/{col}/{row}.png"; webTiledLayer.SubDomains = new string[] { "a", "b", "c", "d" }; Attribution.Content = Attribution.Resources["StamenTonerAttribution"]; Attribution.Visibility = Visibility.Visible; break; } MyMapView.Map.Layers.Add(webTiledLayer); } private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) { Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); e.Handled = true; } } }
{ "content_hash": "61ce71a674f875198d27e22fadebfd3f", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 159, "avg_line_length": 49.97520661157025, "alnum_prop": 0.5645774764345957, "repo_name": "Tyshark9/arcgis-runtime-samples-dotnet", "id": "f9773df60358c5d6658565e9dc5810ff3059c29e", "size": "6049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Desktop/ArcGISRuntimeSDKDotNet_DesktopSamples/Samples/TiledLayers/WebTiledLayerSample.xaml.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1781429" } ], "symlink_target": "" }
package org.deeplearning4j.eval; import org.nd4j.common.base.Preconditions; import org.nd4j.evaluation.IEvaluation; @Deprecated public class EvaluationUtils extends org.nd4j.evaluation.EvaluationUtils { public static <T> T copyToLegacy(IEvaluation<?> from, Class<T> to){ if(from == null) return null; Preconditions.checkState(to.isAssignableFrom(from.getClass()), "Invalid classes: %s vs %s", from.getClass(), to); throw new UnsupportedOperationException("Not implemented"); } }
{ "content_hash": "0df684df7f0502961844736d23a13e56", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 121, "avg_line_length": 26.55, "alnum_prop": 0.711864406779661, "repo_name": "deeplearning4j/deeplearning4j", "id": "a45dc7844ad1d04db4d7caa9b674a129b02e5b23", "size": "1422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/eval/EvaluationUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1458" }, { "name": "C", "bytes": "165340" }, { "name": "C++", "bytes": "17817311" }, { "name": "CMake", "bytes": "112697" }, { "name": "CSS", "bytes": "12974" }, { "name": "Cuda", "bytes": "2413085" }, { "name": "Cython", "bytes": "12094" }, { "name": "FreeMarker", "bytes": "77257" }, { "name": "HTML", "bytes": "18609" }, { "name": "Java", "bytes": "47657420" }, { "name": "JavaScript", "bytes": "296767" }, { "name": "Kotlin", "bytes": "2041047" }, { "name": "PureBasic", "bytes": "12254" }, { "name": "Python", "bytes": "77566" }, { "name": "Ruby", "bytes": "4558" }, { "name": "Scala", "bytes": "1026" }, { "name": "Shell", "bytes": "92012" }, { "name": "Smarty", "bytes": "975" }, { "name": "Starlark", "bytes": "931" }, { "name": "TypeScript", "bytes": "81217" } ], "symlink_target": "" }
BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("ERY"); case mBTC: return QString("mERY"); case uBTC: return QString::fromUtf8("μERY"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString(QObject::tr("Erylliums")); case mBTC: return QString(QObject::tr("Milli-Erylliums (1 / 1,000)")); case uBTC: return QString(QObject::tr("Micro-Erylliums (1 / 1,000,000)")); default: return QString("???"); } } qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 9; // 210,000,000 (# digits, without commas) case mBTC: return 12; // 210,000,000,000 case uBTC: return 15; // 210,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus, uint8_t nNumberOfZeros) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess zeros after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=nNumberOfZeros && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign, uint8_t nNumberOfZeros) { return format(unit, amount, plussign, nNumberOfZeros) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } QString BitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (BitcoinUnits::valid(unit)) { amountTitle += " ("+BitcoinUnits::name(unit) + ")"; } return amountTitle; }
{ "content_hash": "388e4fa6ccc4ff218c85f7cf23f7d4f8", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 100, "avg_line_length": 24.53475935828877, "alnum_prop": 0.6137750653879687, "repo_name": "Eryllium/project", "id": "e967a5509a2ae9426750e459efceff468f900a85", "size": "4640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/bitcoinunits.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "139611" }, { "name": "Batchfile", "bytes": "5376" }, { "name": "C", "bytes": "722189" }, { "name": "C++", "bytes": "2687486" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "12684" }, { "name": "HTML", "bytes": "50621" }, { "name": "Makefile", "bytes": "14645" }, { "name": "NSIS", "bytes": "6088" }, { "name": "Objective-C", "bytes": "1108" }, { "name": "Objective-C++", "bytes": "7225" }, { "name": "Perl", "bytes": "1049" }, { "name": "Python", "bytes": "44877" }, { "name": "QMake", "bytes": "17981" }, { "name": "Shell", "bytes": "16820" } ], "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 net.groboclown.p4.server.api.cache.messagebus; import net.groboclown.p4.server.api.ClientServerRef; import net.groboclown.p4.server.api.P4ServerName; import net.groboclown.p4.server.api.messagebus.AbstractMessageEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Date; public class AbstractCacheUpdateEvent<E extends AbstractCacheUpdateEvent<E>> extends AbstractMessageEvent { private final ClientServerRef ref; private final P4ServerName serverName; private final Date created = new Date(); /** * Used by messages to receive events posted to the message bus. * * @param <E> event type */ public interface Visitor<E extends AbstractCacheUpdateEvent<E>> { void visit(@NotNull E event); } protected AbstractCacheUpdateEvent(@NotNull ClientServerRef ref) { this.ref = ref; this.serverName = ref.getServerName(); } protected AbstractCacheUpdateEvent(@NotNull P4ServerName name) { this.ref = null; this.serverName = name; } @SuppressWarnings("unchecked") void visit(@NotNull String cacheId, @NotNull Visitor<E> visitor) { boolean run = shouldVisitName(cacheId); if (run) { visitor.visit((E) this); } } @NotNull public Date getCreated() { return created; } @Nullable public ClientServerRef getClientRef() { return ref; } @NotNull public P4ServerName getServerName() { return serverName; } }
{ "content_hash": "a54386c44ff1195b627a731043117797", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 107, "avg_line_length": 29.971830985915492, "alnum_prop": 0.6992481203007519, "repo_name": "groboclown/p4ic4idea", "id": "a78fd158717fe13b04100d606c0fe100760d8465", "size": "2128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "idea-p4server/api/src/main/java/net/groboclown/p4/server/api/cache/messagebus/AbstractCacheUpdateEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "4156" }, { "name": "Groovy", "bytes": "76175" }, { "name": "HTML", "bytes": "122275" }, { "name": "Java", "bytes": "10150871" }, { "name": "PHP", "bytes": "426" }, { "name": "Python", "bytes": "15206" }, { "name": "Ruby", "bytes": "615" }, { "name": "Shell", "bytes": "25651" } ], "symlink_target": "" }
layout: default name: Add, get, remove title: Example to showcase the add, get and remove methods. url: http://codepen.io/javve/pen/cLdfw slug: cLdfw --- {% include codepen.html %}
{ "content_hash": "ef3dff9a4d31e9e9790066a67470881e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 59, "avg_line_length": 22.75, "alnum_prop": 0.7252747252747253, "repo_name": "mizukagetobi/ect", "id": "25ca93a5d2b64b7d44c55e3f7bef757b94b4aabd", "size": "186", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "assets/plugins/list/docs/_examples/add-get-remove.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "15982" }, { "name": "ApacheConf", "bytes": "1656" }, { "name": "CSS", "bytes": "390613" }, { "name": "HTML", "bytes": "8585640" }, { "name": "JavaScript", "bytes": "1148479" }, { "name": "PHP", "bytes": "2514657" }, { "name": "Ruby", "bytes": "3909" }, { "name": "Shell", "bytes": "331" } ], "symlink_target": "" }
package ceylon.language.meta; import ceylon.language.meta.declaration.ClassDeclaration; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Method; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel; @Ceylon(major=8, minor=0) @Method public class classDeclaration_ { @Ignore private classDeclaration_(){} @TypeInfo("ceylon.language.meta.declaration::ClassDeclaration") public static ClassDeclaration classDeclaration( @TypeInfo("ceylon.language::Anything") @Name("instance") java.lang.Object instance) { return (ClassDeclaration)Metamodel.getOrCreateMetamodel(instance.getClass()); } }
{ "content_hash": "ba5961dfb8f312ba3d5c345afe995ac0", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 85, "avg_line_length": 34.57692307692308, "alnum_prop": 0.7530589543937709, "repo_name": "unratito/ceylon.language", "id": "fbe1863fa195549cb8cae1f64d9193aa59a3308d", "size": "899", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "runtime/ceylon/language/meta/classDeclaration_.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ceylon", "bytes": "1315602" }, { "name": "Java", "bytes": "1640616" }, { "name": "JavaScript", "bytes": "392707" } ], "symlink_target": "" }
To contribute code to Seastar, send your changes as [patches](https://github.com/scylladb/scylla/wiki/Formatting-and-sending-patches) to the [mailing list](https://groups.google.com/forum/#!forum/seastar-dev). We don't accept pull requests on GitHub. # Asking questions or requesting help Use the [Seastar mailing list](https://groups.google.com/forum/#!forum/seastar-dev) for general questions and help. # Reporting an issue Please use the [Issue Tracker](https://github.com/scylladb/seastar/issues/) to report issues. Supply as much information about your environment as possible, especially for performance problems.
{ "content_hash": "89d0ba8fd010193c93eddf5deb7f57ea", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 250, "avg_line_length": 62.5, "alnum_prop": 0.7856, "repo_name": "cloudius-systems/seastar", "id": "76dfc3947cb459e5b378945de0ab5b5235c1395e", "size": "657", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1576528" }, { "name": "Python", "bytes": "97374" }, { "name": "Ragel in Ruby Host", "bytes": "10719" }, { "name": "Shell", "bytes": "9626" } ], "symlink_target": "" }
title: "FINDSTATS" layout: function isPage: "true" desc: "Computes statistics on matching GTS." categoryTree: ["reference","functions"] category: reference signature: "[ 'token' 'class_selector' { labels_selectors } ] FINDSTATS { statistics }" --- The `FINDSTATS` function computes statistics on matching GTS. It expects a list of parameters on the stack. This list must contain a read token as string, then another string (that can contains a REGEXP) which corresponds to a class selector of a matching GTS on a Warp10 cluster and finally a labels map selector. This function return a map full of statistics on those series. It contains for example stats such as error rate or whether estimates on classes, gts, or labels. *`FINDSTATS` is **NOT** available in standalone mode* ``` [ 'token' 'class_selector' { labels_selectors } ] FINDSTATS { statistics } ``` ## Example ## WarpScript commands: [ 'TOKEN' 'myclass' { 'myLabel' '~foo.*' } ] FINDSTATS
{ "content_hash": "2c792f7d669c1f3f22e7a986d6a8b6a9", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 378, "avg_line_length": 38.76, "alnum_prop": 0.7327141382868937, "repo_name": "cityzendata/www.warp10.io", "id": "feab974d1da7c31f3084e02db21f02dbef0a8bfd", "size": "973", "binary": false, "copies": "2", "ref": "refs/heads/gh-pages", "path": "reference/functions/function_FINDSTATS.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23451" }, { "name": "HTML", "bytes": "19328" }, { "name": "JavaScript", "bytes": "63013" } ], "symlink_target": "" }
import { Route } from '@angular/router'; import { DashboardComponent } from './index'; import { LiveDashboardRoutes } from './live-bids/index'; import { WatchDashboardRoutes } from './watch-bids/index'; export const DashboardRoutes: Route[] = [ { path: 'dashboard', component: DashboardComponent, children: [ { path: '', redirectTo: LiveDashboardRoutes.path, pathMatch: 'full' }, LiveDashboardRoutes, WatchDashboardRoutes ] } ];
{ "content_hash": "e98a6d89b8a83da6a4cb5ac731a381b6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 82, "avg_line_length": 31.625, "alnum_prop": 0.6225296442687747, "repo_name": "OElabed/angular2-bid-dashboard", "id": "40f0ead4844f6003bc774ba66b3ad6c10565b86d", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/app/content/dashboard/dashboard.routes.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "102" }, { "name": "CSS", "bytes": "245790" }, { "name": "HTML", "bytes": "101535" }, { "name": "JavaScript", "bytes": "8414" }, { "name": "Nginx", "bytes": "1052" }, { "name": "TypeScript", "bytes": "120213" } ], "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 com.facebook.presto.hive.authentication; import com.facebook.presto.hive.ForHiveMetastore; import com.facebook.presto.hive.HiveClientConfig; import com.google.common.collect.ImmutableMap; import org.apache.hadoop.hive.metastore.security.DelegationTokenIdentifier; import org.apache.hadoop.hive.thrift.client.TUGIAssumingTransport; import org.apache.hadoop.security.SaslRpcServer; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.thrift.transport.TSaslClientTransport; import org.apache.thrift.transport.TTransport; import javax.inject.Inject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.RealmCallback; import javax.security.sasl.RealmChoiceCallback; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Base64; import java.util.Map; import java.util.Optional; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import static javax.security.sasl.Sasl.QOP; import static javax.security.sasl.Sasl.SERVER_AUTH; import static org.apache.hadoop.security.SaslRpcServer.AuthMethod.KERBEROS; import static org.apache.hadoop.security.SaslRpcServer.AuthMethod.TOKEN; import static org.apache.hadoop.security.SaslRpcServer.SASL_DEFAULT_REALM; import static org.apache.hadoop.security.SecurityUtil.getServerPrincipal; public class KerberosHiveMetastoreAuthentication implements HiveMetastoreAuthentication { private static final Map<String, String> SASL_PROPERTIES = ImmutableMap.of(QOP, "auth", SERVER_AUTH, "true"); private final String hiveMetastoreServicePrincipal; private final HadoopAuthentication authentication; private final boolean hdfsWireEncryptionEnabled; @Inject public KerberosHiveMetastoreAuthentication( MetastoreKerberosConfig config, @ForHiveMetastore HadoopAuthentication authentication, HiveClientConfig hiveClientConfig) { this(config.getHiveMetastoreServicePrincipal(), authentication, hiveClientConfig.isHdfsWireEncryptionEnabled()); } public KerberosHiveMetastoreAuthentication(String hiveMetastoreServicePrincipal, HadoopAuthentication authentication, boolean hdfsWireEncryptionEnabled) { this.hiveMetastoreServicePrincipal = requireNonNull(hiveMetastoreServicePrincipal, "hiveMetastoreServicePrincipal is null"); this.authentication = requireNonNull(authentication, "authentication is null"); this.hdfsWireEncryptionEnabled = hdfsWireEncryptionEnabled; } @Override public TTransport authenticate(TTransport rawTransport, String hiveMetastoreHost, Optional<String> tokenString) { return tokenString.map(s -> authenticateWithToken(rawTransport, s)).orElseGet(() -> authenticateWithHost(rawTransport, hiveMetastoreHost)); } private TTransport authenticateWithToken(TTransport rawTransport, String tokenString) { try { Token<DelegationTokenIdentifier> token = new Token<>(); token.decodeFromUrlString(tokenString); TTransport saslTransport = new TSaslClientTransport( TOKEN.getMechanismName(), null, null, SASL_DEFAULT_REALM, SASL_PROPERTIES, new SaslClientCallbackHandler(token), rawTransport); return new TUGIAssumingTransport(saslTransport, UserGroupInformation.getCurrentUser()); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static class SaslClientCallbackHandler implements CallbackHandler { private final String userName; private final char[] userPassword; public SaslClientCallbackHandler(Token<? extends TokenIdentifier> token) { this.userName = encodeIdentifier(token.getIdentifier()); this.userPassword = encodePassword(token.getPassword()); } @Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof RealmChoiceCallback) { continue; } else if (callback instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callback; nameCallback.setName(userName); } else if (callback instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callback; passwordCallback.setPassword(userPassword); } else if (callback instanceof RealmCallback) { RealmCallback realmCallback = (RealmCallback) callback; realmCallback.setText(realmCallback.getDefaultText()); } else { throw new UnsupportedCallbackException(callback, "Unrecognized SASL client callback"); } } } private static String encodeIdentifier(byte[] identifier) { return Base64.getEncoder().encodeToString(identifier); } private static char[] encodePassword(byte[] password) { return Base64.getEncoder().encodeToString(password).toCharArray(); } } private TTransport authenticateWithHost(TTransport rawTransport, String hiveMetastoreHost) { try { String serverPrincipal = getServerPrincipal(hiveMetastoreServicePrincipal, hiveMetastoreHost); String[] names = SaslRpcServer.splitKerberosName(serverPrincipal); checkState(names.length == 3, "Kerberos principal name does NOT have the expected hostname part: %s", serverPrincipal); Map<String, String> saslProps = ImmutableMap.of( QOP, hdfsWireEncryptionEnabled ? "auth-conf" : "auth", SERVER_AUTH, "true"); TTransport saslTransport = new TSaslClientTransport( KERBEROS.getMechanismName(), null, names[0], names[1], saslProps, null, rawTransport); return new TUGIAssumingTransport(saslTransport, authentication.getUserGroupInformation()); } catch (IOException e) { throw new UncheckedIOException(e); } } }
{ "content_hash": "d0056d6828be2f38619fa720f984cdd5", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 156, "avg_line_length": 41.944134078212294, "alnum_prop": 0.6875332978156633, "repo_name": "prestodb/presto", "id": "55ecd274da896d177cbed305865c9924eda8cd83", "size": "7508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-hive/src/main/java/com/facebook/presto/hive/authentication/KerberosHiveMetastoreAuthentication.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "33331" }, { "name": "Batchfile", "bytes": "795" }, { "name": "C++", "bytes": "640275" }, { "name": "CMake", "bytes": "31361" }, { "name": "CSS", "bytes": "28319" }, { "name": "Dockerfile", "bytes": "1266" }, { "name": "HTML", "bytes": "29601" }, { "name": "Java", "bytes": "52940440" }, { "name": "JavaScript", "bytes": "286864" }, { "name": "Makefile", "bytes": "16617" }, { "name": "Mustache", "bytes": "17803" }, { "name": "NASL", "bytes": "11965" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "39357" }, { "name": "Roff", "bytes": "52281" }, { "name": "Shell", "bytes": "38937" }, { "name": "Thrift", "bytes": "14675" } ], "symlink_target": "" }
A simple React app to showcase React, Flux, Firebase & material-ui Work in progress
{ "content_hash": "f4ca8cf0458d103a5f8dde3827c02ece", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 66, "avg_line_length": 42, "alnum_prop": 0.7857142857142857, "repo_name": "qmmr/react-stack", "id": "a52a3d06589222b1be63337fa4d3f761a93cea86", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "76" }, { "name": "HTML", "bytes": "290" }, { "name": "JavaScript", "bytes": "6133" } ], "symlink_target": "" }
.PHONY=up clean bash test browser DOCKER_HOST?=localhost up: docker-compose up -d clean: docker-compose down --remove-orphans bash: docker-compose exec node bash test: docker-compose run --rm codeceptjs codeceptjs run selenium-firefox: xdg-open vnc://$(DOCKER_HOST):9059 selenium-chrome: xdg-open vnc://$(DOCKER_HOST):9060 browser: xdg-open http://$(DOCKER_HOST):9100
{ "content_hash": "294e3764d4e6030a2952a5a6aa92a95d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 50, "avg_line_length": 15.958333333333334, "alnum_prop": 0.7362924281984334, "repo_name": "cunneen/json-editor", "id": "437f11a8ecc8408b51dd8ae795b3492cdd7920b7", "size": "383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "46044" }, { "name": "JavaScript", "bytes": "551726" } ], "symlink_target": "" }
layout: model title: Multilingual XLMRobertaForTokenClassification Base Cased model (from flood) author: John Snow Labs name: xlmroberta_ner_flood_base_finetuned_panx date: 2022-08-14 tags: [de, fr, open_source, xlm_roberta, ner, xx] task: Named Entity Recognition language: xx edition: Spark NLP 4.1.0 spark_version: 3.0 supported: true annotator: XlmRoBertaForTokenClassification article_header: type: cover use_language_switcher: "Python-Scala-Java" --- ## Description Pretrained XLMRobertaForTokenClassification model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `xlm-roberta-base-finetuned-panx-de-fr` is a Multilingual model originally trained by `flood`. ## Predicted Entities `PER`, `LOC`, `ORG` {:.btn-box} <button class="button button-orange" disabled>Live Demo</button> <button class="button button-orange" disabled>Open in Colab</button> [Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/xlmroberta_ner_flood_base_finetuned_panx_xx_4.1.0_3.0_1660439016684.zip){:.button.button-orange.button-orange-trans.arr.button-icon} ## How to use <div class="tabs-box" markdown="1"> {% include programmingLanguageSelectScalaPythonNLU.html %} ```python documentAssembler = DocumentAssembler() \ .setInputCols(["text"]) \ .setOutputCols("document") tokenizer = Tokenizer() \ .setInputCols("document") \ .setOutputCol("token") token_classifier = XlmRoBertaForTokenClassification.pretrained("xlmroberta_ner_flood_base_finetuned_panx","xx") \ .setInputCols(["document", "token"]) \ .setOutputCol("ner") ner_converter = NerConverter()\ .setInputCols(["document", "token", "ner"])\ .setOutputCol("ner_chunk") pipeline = Pipeline(stages=[documentAssembler, tokenizer, token_classifier, ner_converter]) data = spark.createDataFrame([["PUT YOUR STRING HERE"]]).toDF("text") result = pipeline.fit(data).transform(data) ``` ```scala val documentAssembler = new DocumentAssembler() .setInputCols(Array("text")) .setOutputCols(Array("document")) val tokenizer = new Tokenizer() .setInputCols("document") .setOutputCol("token") val token_classifier = XlmRoBertaForTokenClassification.pretrained("xlmroberta_ner_flood_base_finetuned_panx","xx") .setInputCols(Array("document", "token")) .setOutputCol("ner") val ner_converter = new NerConverter() .setInputCols(Array("document", "token', "ner")) .setOutputCol("ner_chunk") val pipeline = new Pipeline().setStages(Array(documentAssembler, tokenizer, token_classifier, ner_converter)) val data = Seq("PUT YOUR STRING HERE").toDS.toDF("text") val result = pipeline.fit(data).transform(data) ``` </div> {:.model-param} ## Model Information {:.table-model} |---|---| |Model Name:|xlmroberta_ner_flood_base_finetuned_panx| |Compatibility:|Spark NLP 4.1.0+| |License:|Open Source| |Edition:|Official| |Input Labels:|[document, token]| |Output Labels:|[ner]| |Language:|xx| |Size:|858.8 MB| |Case sensitive:|true| |Max sentence length:|256| ## References - https://huggingface.co/flood/xlm-roberta-base-finetuned-panx-de-fr
{ "content_hash": "f5139296c63c90ada3f755dc5e49e98a", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 248, "avg_line_length": 30.601941747572816, "alnum_prop": 0.7319162436548223, "repo_name": "JohnSnowLabs/spark-nlp", "id": "b4c87e5c30c86024920f5523956900e3e270c1fa", "size": "3156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/_posts/murat-gunay/2022-08-14-xlmroberta_ner_flood_base_finetuned_panx_xx_3_0.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "14452" }, { "name": "Java", "bytes": "223289" }, { "name": "Makefile", "bytes": "819" }, { "name": "Python", "bytes": "1694517" }, { "name": "Scala", "bytes": "4116435" }, { "name": "Shell", "bytes": "5286" } ], "symlink_target": "" }
<?php // show all the errors error_reporting(E_ALL); // the only file that needs including into your project require_once 'Cassandra.php'; // list of seed servers to randomly connect to // all the parameters are optional and default to given values $servers = array( array( 'host' => '127.0.0.1', 'port' => 9160, 'use-framed-transport' => true, 'send-timeout-ms' => 1000, 'receive-timeout-ms' => 1000 ) ); // create a named singleton, the second parameter name defaults to "main" // you can have several named singletons with different server pools $cassandra = Cassandra::createInstance($servers); // at any point in code, you can get the named singleton instance, the name // again defaults to "main" so no need to define it if using single instance $cassandra2 = Cassandra::getInstance(); // drop the example keyspace and ignore errors should it not exist try { $cassandra->dropKeyspace('CassandraExample'); } catch (Exception $e) {} // create a new keyspace, accepts extra parameters for replication options // normally you don't do it every time $cassandra->createKeyspace('CassandraExample'); // start using the created keyspace $cassandra->useKeyspace('CassandraExample'); // if a request fails, it will be retried for this many times, each time backing // down for a bit longer period to prevent floods; defaults to 5 $cassandra->setMaxCallRetries(5); // create a standard column family with given column metadata $cassandra->createStandardColumnFamily( 'CassandraExample', // keyspace name 'user', // the column-family name array( // list of columns with metadata array( 'name' => 'name', 'type' => Cassandra::TYPE_UTF8, 'index-type' => Cassandra::INDEX_KEYS, // create secondary index 'index-name' => 'NameIdx' ), array( 'name' => 'email', 'type' => Cassandra::TYPE_UTF8 ), array( 'name' => 'age', 'type' => Cassandra::TYPE_INTEGER, 'index-type' => Cassandra::INDEX_KEYS, 'index-name' => 'AgeIdx' ) ) // actually accepts more parameters with reasonable defaults ); // create a standard column family with given column metadata $cassandra->createStandardColumnFamily( 'CassandraExample', 'counter', array(), Cassandra::TYPE_UTF8, Cassandra::TYPE_COUNTER ); // create a super column family $cassandra->createSuperColumnFamily( 'CassandraExample', 'cities', array( array( 'name' => 'population', 'type' => Cassandra::TYPE_INTEGER ), array( 'name' => 'comment', 'type' => Cassandra::TYPE_UTF8 ) ), // see the definition for these additional optional parameters Cassandra::TYPE_UTF8, Cassandra::TYPE_UTF8, Cassandra::TYPE_UTF8, 'Capitals supercolumn test', 1000, 1000, 0.5 ); // lets fetch and display the schema of created keyspace $schema = $cassandra->getKeyspaceSchema('CassandraExample'); echo 'Schema: <pre>'.print_r($schema, true).'</pre><hr/>'; /* // should we need to, we can access the low-level client directly $version = $cassandra->getConnection()->getClient()->describe_version(); echo 'Version directly: <pre>'.print_r($version, true).'</pre><hr/>'; */ // if implemented, use the wrapped methods as these are smarter - can retry etc $version = $cassandra->getVersion(); echo 'Version through wrapper: <pre>'.print_r($version, true).'</pre><hr/>'; // cluster is a pool of connections $cluster = $cassandra->getCluster(); echo 'Cluster: <pre>'.print_r($cluster, true).'</pre><hr/>'; // you can ask the cluster for a connection to a random seed server from pool $connection = $cluster->getConnection(); echo 'Connection: <pre>'.print_r($connection, true).'</pre><hr/>'; // access column family, using the singleton syntax // there is shorter "cf" methid that is an alias to "columnFamily" $userColumnFamily = Cassandra::getInstance()->columnFamily('user'); echo 'Column family "user": <pre>'.print_r($userColumnFamily, true).'</pre><hr/>'; // lets insert some test data using the convinience method "set" of Cassandra // the syntax is COLUMN_FAMILY_NAME.KEY_NAME $cassandra->set( 'user.john', array( 'email' => 'john@smith.com', 'name' => 'John Smith', 'age' => 34 ) ); // when inserting data, it's ok if key name contains ".", no need to escape them $cassandra->set( 'user.jane.doe', array( 'email' => 'jane@doe.com', 'name' => 'Jane Doe', 'age' => 24 ) ); // longer way of inserting data, first getting the column family $cassandra->cf('user')->set( 'chuck', // key name array( // column names and values 'email' => 'chuck@norris.com', 'name' => 'Chuck Norris', 'age' => 24 ), Cassandra::CONSISTENCY_QUORUM // optional consistency to use // also accepts optional custom timestamp and time to live ); // lets fetch all the information about user john $john = $cassandra->get('user.john'); echo 'User "john": <pre>'.print_r($john, true).'</pre><hr/>'; // since the jane key "jane.doe" includes a ".", we have to escape it $jane = $cassandra->get('user.'.Cassandra::escape('jane.doe')); echo 'User "jane.doe": <pre>'.print_r($jane, true).'</pre><hr/>'; // there is some syntatic sugar on the query of Cassandra::get() allowing you // to fetch specific columns, ranges of them, limit amount etc. for example, // lets only fetch columns name and age $chuck = $cassandra->get('user.chuck:name,age'); echo 'User "chuck", name and age: <pre>'.print_r($chuck, true).'</pre><hr/>'; // fetch all solumns from age to name (gets all columns in-between too) $chuck2 = $cassandra->get('user.chuck:age-name'); echo 'User "chuck", columns ago to name: <pre>'.print_r($chuck2, true).'</pre><hr/>'; // the range columns do not need to exist, we can get character ranges $chuck3 = $cassandra->get('user.chuck:a-z'); echo 'User "chuck", columns a-z: <pre>'.print_r($chuck3, true).'</pre><hr/>'; // when performing range queries, we can also limit the number of columns // returned (2); also the method accepts consistency level as second parameter $chuck4 = $cassandra->get('user.chuck:a-z|2', Cassandra::CONSISTENCY_ALL); echo 'User "chuck", columns a-z, limited to 2 columns: <pre>'.print_r($chuck4, true).'</pre><hr/>'; // the Cassandra::get() is a convinience method proxying to lower level // CassandraColumnFamily::get(), no need to worry about escaping with this. // column family has additional methods getAll(), getColumns(), getColumnRange() // that all map to lower level get() calls with more appopriate parameters $jane2 = $cassandra->cf('user')->get('jane.doe'); echo 'User "jane.doe", lower level api: <pre>'.print_r($jane2, true).'</pre><hr/>'; // we defined a secondary index on "age" column of "user" column family so we // can use CassandraColumnFamily::getWhere() to fetch users of specific age. // this returns an iterator that you can go over with foreach or use the // getAll() method that fetches all the data and returns an array $aged24 = $cassandra->cf('user')->getWhere(array('age' => 24)); echo 'Users at age 24: <pre>'.print_r($aged24->getAll(), true).'</pre><hr/>'; // if we know we are going to need to values of several keys, we can request // them in a single query for better performance $chuckAndJohn = $cassandra->cf('user')->getMultiple(array('chuck', 'john')); echo 'Users "chuck" and "john": <pre>'.print_r($chuckAndJohn, true).'</pre><hr/>'; /* Uncomment this when using order preserving partitioner // we can fetch a range of keys but this is predictable only if using an // order preserving partitioner, Cassandra defaults to random one // again as there may be more results than it's reasonable to fetch in a single // query, an iterator is returned that can make several smaller range queries // as the data is iterated $usersAZ = $cassandra->cf('user')->getKeyRange('a', 'z'); echo 'Users with keys in range a-z: <pre>'.print_r($usersAZ->getAll(), true).'</pre><hr/>'; */ // counters example /*$cassandra->set( 'counter.test', array( 'first' => 1, 'second' => 10 ) );*/ $cassandra->cf('counter')->increment('test', 'first'); $testCounter = $cassandra->get('counter.test'); echo 'Test counter after increment: <pre>'.print_r($testCounter, true).'</pre><hr/>'; $cassandra->cf('counter')->updateCounter('test', 'first', 10); $testCounter = $cassandra->get('counter.test'); echo 'Test counter after second increment by 10: <pre>'.print_r($testCounter, true).'</pre><hr/>'; // find the number of columns a key has, we could also request for ranges $chuckColumnCount = $cassandra->cf('user')->getColumnCount('chuck'); echo 'User "chuck" column count: <pre>'.print_r($chuckColumnCount, true).'</pre><hr/>'; // we can find column counts for several keys at once $chuckJaneColumnCounts = $cassandra->cf('user')->getColumnCounts(array('chuck', 'jane.doe')); echo 'User "chuck" and "jane.doe" column counts: <pre>'.print_r($chuckJaneColumnCounts, true).'</pre><hr/>'; // setting supercolumn values is similar to normal column families $cassandra->set( 'cities.Estonia', array( 'Tallinn' => array( 'population' => '411980', 'comment' => 'Capital of Estonia', 'size' => 'big' ), 'Tartu' => array( 'population' => '98589', 'comment' => 'City of good thoughts', 'size' => 'medium' ) ) ); // fetch all columns of Tartu in Estonia of cities $tartu = $cassandra->cf('cities')->getAll('Estonia', 'Tartu'); echo 'Super-column cities.Estonia.Tartu: <pre>'.print_r($tartu, true).'</pre><hr/>'; // we could also use the higher level Cassandra::get() to fetch supercolumn info // we can still use the additional filters of columns $tallinn = $cassandra->get('cities.Estonia.Tallinn:population,size'); echo 'Super-column cities.Estonia.Tallinn: <pre>'.print_r($tallinn, true).'</pre><hr/>'; // we can also insert multiple rows and columns $cassandra->cf('user')->setMultiple(array( 'sam' => array( 'email' => 'sam@email.com', 'name' => 'Sam J', 'age' => 26 ), 'rick' => array( 'email' => 'rick@email.com', 'name' => 'Rick P', 'age' => 48 ) )); $samAndRick = $cassandra->cf('user')->getMultiple(array('sam', 'rick')); echo 'Users "sam" and "rick": <pre>'.print_r($samAndRick, true).'</pre><hr/>'; // we can also insert multiple entries into super column families $cassandra->cf('cities')->setMultiple(array( 'SomeCountryX' => array( 'CityA' => array( 'population' => '23432', 'comment' => 'Weird city name', 'size' => 'medium' ), 'CityB' => array( 'population' => '2332', 'comment' => 'City of bees?', 'size' => 'small' ) ), 'SomeCountryY' => array( 'CityC' => array( 'population' => '2352343', 'comment' => 'Capital of Y', 'size' => 'massive' ) ) )); $countryX = $cassandra->cf('cities')->getAll('SomeCountryX'); echo 'Super-column cities.SomeCountryX: <pre>'.print_r($countryX, true).'</pre><hr/>'; $countryY = $cassandra->cf('cities')->getAll('SomeCountryY'); echo 'Super-column cities.SomeCountryY: <pre>'.print_r($countryY, true).'</pre><hr/>'; /* // you can delete all the data in a column family using "truncate" $cassandra->truncate('user'); // you may choose to drop an entire keyspace $cassandra->dropKeyspace('CassandraExample'); */
{ "content_hash": "6748b248c22c69bc9a6898d089f1cb95", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 108, "avg_line_length": 33.941717791411044, "alnum_prop": 0.6776321735201084, "repo_name": "lekster/md_new", "id": "fcc6f8dc1b3103b103f03c74edcbb27a05fb80e8", "size": "11065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/common/Cassandra/Cassandra-PHP-Client-Library/example.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "20439" }, { "name": "Awk", "bytes": "5471" }, { "name": "Batchfile", "bytes": "176" }, { "name": "C", "bytes": "5632" }, { "name": "C++", "bytes": "65663" }, { "name": "CSS", "bytes": "1567317" }, { "name": "Cucumber", "bytes": "118867" }, { "name": "HTML", "bytes": "4120360" }, { "name": "JavaScript", "bytes": "7316517" }, { "name": "Makefile", "bytes": "190597" }, { "name": "PHP", "bytes": "18464769" }, { "name": "Perl", "bytes": "5146" }, { "name": "PostScript", "bytes": "23931" }, { "name": "Shell", "bytes": "1038311" }, { "name": "TeX", "bytes": "470410" } ], "symlink_target": "" }
#include <config.h> #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <pcsclite.h> #include <ifdhandler.h> #include "debug.h" #include "ccid.h" #include "defs.h" #include "ccid_ifdhandler.h" #include "commands.h" #include "utils.h" #ifdef __APPLE__ #include <CoreFoundation/CoreFoundation.h> #endif /***************************************************************************** * * ccid_open_hack_pre * ****************************************************************************/ int ccid_open_hack_pre(unsigned int reader_index) { _ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index); switch (ccid_descriptor->readerID) { case MYSMARTPAD: ccid_descriptor->dwMaxIFSD = 254; break; case CL1356D: /* the firmware needs some time to initialize */ (void)sleep(1); ccid_descriptor->readTimeout = 60*1000; /* 60 seconds */ break; #ifdef ENABLE_ZLP case GEMPCTWIN: case GEMPCKEY: case DELLSCRK: /* Only the chipset with firmware version 2.00 is "bogus" * The reader may send packets of 0 bytes when the reader is * connected to a USB 3 port */ if (0x0200 == ccid_descriptor->IFD_bcdDevice) { ccid_descriptor->zlp = TRUE; DEBUG_INFO1("ZLP fixup"); } break; #endif case OZ776: case OZ776_7772: ccid_descriptor->dwMaxDataRate = 9600; break; case ElatecTWN4_CCID_CDC: case ElatecTWN4_CCID: /* Use a timeout of 1000 ms instead of 100 ms in * CmdGetSlotStatus() used by CreateChannelByNameOrChannel() * The reader answers after up to 1 s if no tag is present */ ccid_descriptor->readTimeout = DEFAULT_COM_READ_TIMEOUT * 10; break; case SCM_SCL011: case IDENTIV_uTrust3700F: case IDENTIV_uTrust3701F: case IDENTIV_uTrust4701F: /* The SCM SCL011 reader needs 350 ms to answer */ ccid_descriptor->readTimeout = DEFAULT_COM_READ_TIMEOUT * 4; break; } /* CCID */ if ((PROTOCOL_CCID == ccid_descriptor->bInterfaceProtocol) && (3 == ccid_descriptor -> bNumEndpoints)) { #ifndef TWIN_SERIAL /* just wait for 100ms in case a notification is in the pipe */ (void)InterruptRead(reader_index, 100); #endif } /* ICCD type A */ if (PROTOCOL_ICCD_A == ccid_descriptor->bInterfaceProtocol) { unsigned char tmp[MAX_ATR_SIZE]; unsigned int n = sizeof(tmp); DEBUG_COMM("ICCD type A"); (void)CmdPowerOff(reader_index); (void)CmdPowerOn(reader_index, &n, tmp, VOLTAGE_AUTO); (void)CmdPowerOff(reader_index); } /* ICCD type B */ if (PROTOCOL_ICCD_B == ccid_descriptor->bInterfaceProtocol) { unsigned char tmp[MAX_ATR_SIZE]; unsigned int n = sizeof(tmp); DEBUG_COMM("ICCD type B"); if (CCID_CLASS_SHORT_APDU == (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK)) { /* use the extended APDU comm alogorithm */ ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_EXTENDED_APDU; } (void)CmdPowerOff(reader_index); (void)CmdPowerOn(reader_index, &n, tmp, VOLTAGE_AUTO); (void)CmdPowerOff(reader_index); } return 0; } /* ccid_open_hack_pre */ #ifndef NO_LOG /***************************************************************************** * * dump_gemalto_firmware_features * ****************************************************************************/ static void dump_gemalto_firmware_features(struct GEMALTO_FIRMWARE_FEATURES *gff) { DEBUG_INFO2("Dumping Gemalto firmware features (%zd bytes):", sizeof(struct GEMALTO_FIRMWARE_FEATURES)); #define YESNO(x) (x) ? "yes" : "no" DEBUG_INFO2(" bLogicalLCDLineNumber: %d", gff->bLogicalLCDLineNumber); DEBUG_INFO2(" bLogicalLCDRowNumber: %d", gff->bLogicalLCDRowNumber); DEBUG_INFO2(" bLcdInfo: 0x%02X", gff->bLcdInfo); DEBUG_INFO2(" bEntryValidationCondition: 0x%02X", gff->bEntryValidationCondition); DEBUG_INFO1(" Reader supports PC/SCv2 features:"); DEBUG_INFO2(" VerifyPinStart: %s", YESNO(gff->VerifyPinStart)); DEBUG_INFO2(" VerifyPinFinish: %s", YESNO(gff->VerifyPinFinish)); DEBUG_INFO2(" ModifyPinStart: %s", YESNO(gff->ModifyPinStart)); DEBUG_INFO2(" ModifyPinFinish: %s", YESNO(gff->ModifyPinFinish)); DEBUG_INFO2(" GetKeyPressed: %s", YESNO(gff->GetKeyPressed)); DEBUG_INFO2(" VerifyPinDirect: %s", YESNO(gff->VerifyPinDirect)); DEBUG_INFO2(" ModifyPinDirect: %s", YESNO(gff->ModifyPinDirect)); DEBUG_INFO2(" Abort: %s", YESNO(gff->Abort)); DEBUG_INFO2(" GetKey: %s", YESNO(gff->GetKey)); DEBUG_INFO2(" WriteDisplay: %s", YESNO(gff->WriteDisplay)); DEBUG_INFO2(" SetSpeMessage: %s", YESNO(gff->SetSpeMessage)); DEBUG_INFO2(" bTimeOut2: %s", YESNO(gff->bTimeOut2)); DEBUG_INFO2(" bPPDUSupportOverXferBlock: %s", YESNO(gff->bPPDUSupportOverXferBlock)); DEBUG_INFO2(" bPPDUSupportOverEscape: %s", YESNO(gff->bPPDUSupportOverEscape)); DEBUG_INFO2(" bListSupportedLanguages: %s", YESNO(gff->bListSupportedLanguages)); DEBUG_INFO2(" bNumberMessageFix: %s", YESNO(gff->bNumberMessageFix)); DEBUG_INFO2(" VersionNumber: 0x%02X", gff->VersionNumber); DEBUG_INFO2(" MinimumPINSize: %d", gff->MinimumPINSize); DEBUG_INFO2(" MaximumPINSize: %d", gff->MaximumPINSize); DEBUG_INFO2(" Firewall: %s", YESNO(gff->Firewall)); if (gff->Firewall && gff->FirewalledCommand_SW1 && gff->FirewalledCommand_SW2) { DEBUG_INFO2(" FirewalledCommand_SW1: 0x%02X", gff->FirewalledCommand_SW1); DEBUG_INFO2(" FirewalledCommand_SW2: 0x%02X", gff->FirewalledCommand_SW2); } } /* dump_gemalto_firmware_features */ #endif /***************************************************************************** * * set_gemalto_firmware_features * ****************************************************************************/ static void set_gemalto_firmware_features(unsigned int reader_index) { _ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index); struct GEMALTO_FIRMWARE_FEATURES *gf_features; gf_features = malloc(sizeof(struct GEMALTO_FIRMWARE_FEATURES)); if (gf_features) { unsigned char cmd[] = { 0x6A }; /* GET_FIRMWARE_FEATURES command id */ unsigned int len_features = sizeof *gf_features; RESPONSECODE ret; ret = CmdEscapeCheck(reader_index, cmd, sizeof cmd, (unsigned char*)gf_features, &len_features, 0, TRUE); if ((IFD_SUCCESS == ret) && (len_features == sizeof *gf_features)) { /* Command is supported if it succeeds at CCID level */ /* and returned size matches our expectation */ ccid_descriptor->gemalto_firmware_features = gf_features; #ifndef NO_LOG dump_gemalto_firmware_features(gf_features); #endif } else { /* Command is not supported, let's free allocated memory */ free(gf_features); DEBUG_INFO3("GET_FIRMWARE_FEATURES failed: " DWORD_D ", len=%d", ret, len_features); } } } /* set_gemalto_firmware_features */ /***************************************************************************** * * ccid_open_hack_post * ****************************************************************************/ int ccid_open_hack_post(unsigned int reader_index) { _ccid_descriptor *ccid_descriptor = get_ccid_descriptor(reader_index); RESPONSECODE return_value = IFD_SUCCESS; switch (ccid_descriptor->readerID) { case GEMPCKEY: case GEMPCTWIN: /* Reader announces TPDU but can do APDU (EMV in fact) */ if (DriverOptions & DRIVER_OPTION_GEMPC_TWIN_KEY_APDU) { unsigned char cmd[] = { 0x1F, 0x02 }; unsigned char res[10]; unsigned int length_res = sizeof(res); if (CmdEscape(reader_index, cmd, sizeof(cmd), res, &length_res, 0) == IFD_SUCCESS) { ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_SHORT_APDU; } } break; case VEGAALPHA: case GEMPCPINPAD: /* load the l10n strings in the pinpad memory */ { #define L10N_HEADER_SIZE 5 #define L10N_STRING_MAX_SIZE 16 #define L10N_NB_STRING 10 unsigned char cmd[L10N_HEADER_SIZE + L10N_NB_STRING * L10N_STRING_MAX_SIZE]; unsigned char res[20]; unsigned int length_res = sizeof(res); int offset, i, j; const char *fr[] = { "Entrer PIN", "Nouveau PIN", "Confirmer PIN", "PIN correct", "PIN Incorrect !", "Delai depasse", "* essai restant", "Inserer carte", "Erreur carte", "PIN bloque" }; const char *de[] = { "PIN eingeben", "Neue PIN", "PIN bestatigen", "PIN korrect", "Falsche PIN !", "Zeit abgelaufen", "* Versuche ubrig", "Karte einstecken", "Fehler Karte", "PIN blockiert" }; const char *es[] = { "Introducir PIN", "Nuevo PIN", "Confirmar PIN", "PIN OK", "PIN Incorrecto !", "Tiempo Agotado", "* ensayos quedan", "Introducir Tarj.", "Error en Tarjeta", "PIN bloqueado" }; const char *it[] = { "Inserire PIN", "Nuovo PIN", "Confermare PIN", "PIN Corretto", "PIN Errato !", "Tempo scaduto", "* prove rimaste", "Inserire Carta", "Errore Carta", "PIN ostruito"}; const char *pt[] = { "Insira PIN", "Novo PIN", "Conf. novo PIN", "PIN OK", "PIN falhou!", "Tempo expirou", "* tentiv. restam", "Introduza cartao", "Erro cartao", "PIN bloqueado" }; const char *nl[] = { "Inbrengen code", "Nieuwe code", "Bevestig code", "Code aanvaard", "Foute code", "Time out", "* Nog Pogingen", "Kaart inbrengen", "Kaart fout", "Kaart blok" }; const char *tr[] = { "PIN Giriniz", "Yeni PIN", "PIN Onayala", "PIN OK", "Yanlis PIN", "Zaman Asimi", "* deneme kaldi", "Karti Takiniz", "Kart Hatasi", "Kart Kilitli" }; const char *en[] = { "Enter PIN", "New PIN", "Confirm PIN", "PIN OK", "Incorrect PIN!", "Time Out", "* retries left", "Insert Card", "Card Error", "PIN blocked" }; const char *lang; const char **l10n; #ifdef __APPLE__ CFArrayRef cfa; CFStringRef slang; /* Get the complete ordered list */ cfa = CFLocaleCopyPreferredLanguages(); /* Use the first/preferred language * As the driver is run as root we get the language * selected during install */ slang = CFArrayGetValueAtIndex(cfa, 0); /* CFString -> C string */ lang = CFStringGetCStringPtr(slang, kCFStringEncodingMacRoman); #else /* The other Unixes just use the LANG env variable */ lang = getenv("LANG"); #endif DEBUG_COMM2("Using lang: %s", lang); if (NULL == lang) l10n = en; else { if (0 == strncmp(lang, "fr", 2)) l10n = fr; else if (0 == strncmp(lang, "de", 2)) l10n = de; else if (0 == strncmp(lang, "es", 2)) l10n = es; else if (0 == strncmp(lang, "it", 2)) l10n = it; else if (0 == strncmp(lang, "pt", 2)) l10n = pt; else if (0 == strncmp(lang, "nl", 2)) l10n = nl; else if (0 == strncmp(lang, "tr", 2)) l10n = tr; else l10n = en; } #ifdef __APPLE__ /* Release the allocated array */ CFRelease(cfa); #endif offset = 0; cmd[offset++] = 0xB2; /* load strings */ cmd[offset++] = 0xA0; /* address of the memory */ cmd[offset++] = 0x00; /* address of the first byte */ cmd[offset++] = 0x4D; /* magic value */ cmd[offset++] = 0x4C; /* magic value */ /* for each string */ for (i=0; i<L10N_NB_STRING; i++) { /* copy the string */ for (j=0; l10n[i][j]; j++) cmd[offset++] = l10n[i][j]; /* pad with " " */ for (; j<L10N_STRING_MAX_SIZE; j++) cmd[offset++] = ' '; } (void)sleep(1); if (IFD_SUCCESS == CmdEscape(reader_index, cmd, sizeof(cmd), res, &length_res, DEFAULT_COM_READ_TIMEOUT)) { DEBUG_COMM("l10n string loaded successfully"); } else { DEBUG_COMM("Failed to load l10n strings"); return_value = IFD_COMMUNICATION_ERROR; } if (DriverOptions & DRIVER_OPTION_DISABLE_PIN_RETRIES) { /* disable VERIFY from reader */ const unsigned char cmd2[] = {0xb5, 0x00}; length_res = sizeof(res); if (IFD_SUCCESS == CmdEscape(reader_index, cmd2, sizeof(cmd2), res, &length_res, DEFAULT_COM_READ_TIMEOUT)) { DEBUG_COMM("Disable SPE retry counter successful"); } else { DEBUG_CRITICAL("Failed to disable SPE retry counter"); } } } break; case HPSMARTCARDKEYBOARD: case HP_CCIDSMARTCARDKEYBOARD: case FUJITSUSMARTKEYB: case CHICONYHPSKYLABKEYBOARD: /* the Secure Pin Entry is bogus so disable it * https://web.archive.org/web/20120320001756/http://martinpaljak.net/2011/03/19/insecure-hp-usb-smart-card-keyboard/ * * The problem is that the PIN code entered using the Secure * Pin Entry function is also sent to the host. */ case C3PO_LTC31_v2: ccid_descriptor->bPINSupport = 0; break; case HID_AVIATOR: /* OMNIKEY Generic */ case HID_OMNIKEY_3X21: /* OMNIKEY 3121 or 3021 or 1021 */ case HID_OMNIKEY_6121: /* OMNIKEY 6121 */ case CHERRY_XX44: /* Cherry Smart Terminal xx44 */ case FUJITSU_D323: /* Fujitsu Smartcard Reader D323 */ /* The chip advertises pinpad but actually doesn't have one */ ccid_descriptor->bPINSupport = 0; /* Firmware uses chaining */ ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_EXTENDED_APDU; break; case KOBIL_TRIBANK: /* Firmware does NOT supported extended APDU */ ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_SHORT_APDU; break; #if 0 /* SCM SCR331-DI contactless */ case SCR331DI: /* SCM SCR331-DI-NTTCOM contactless */ case SCR331DINTTCOM: /* SCM SDI010 contactless */ case SDI010: /* the contactless reader is in the second slot */ if (ccid_descriptor->bCurrentSlotIndex > 0) { unsigned char cmd1[] = { 0x00 }; /* command: 00 ?? * response: 06 10 03 03 00 00 00 01 FE FF FF FE 01 ?? */ unsigned char cmd2[] = { 0x02 }; /* command: 02 ?? * response: 00 ?? */ unsigned char res[20]; unsigned int length_res = sizeof(res); if ((IFD_SUCCESS == CmdEscape(reader_index, cmd1, sizeof(cmd1), res, &length_res, 0)) && (IFD_SUCCESS == CmdEscape(reader_index, cmd2, sizeof(cmd2), res, &length_res, 0))) { DEBUG_COMM("SCM SCR331-DI contactless detected"); } else { DEBUG_COMM("SCM SCR331-DI contactless init failed"); } /* hack since the contactless reader do not share dwFeatures */ ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_SHORT_APDU; ccid_descriptor->dwFeatures |= CCID_CLASS_AUTO_IFSD; } break; #endif case CHERRY_KC1000SC: if ((0x0100 == ccid_descriptor->IFD_bcdDevice) && (ccid_descriptor->dwFeatures & CCID_CLASS_EXCHANGE_MASK) == CCID_CLASS_SHORT_APDU) { /* firmware 1.00 is bogus * With a T=1 card and case 2 APDU (data from card to * host) the maximum size returned by the reader is 128 * byes. The reader is then using chaining as with * extended APDU. */ ccid_descriptor->dwFeatures &= ~CCID_CLASS_EXCHANGE_MASK; ccid_descriptor->dwFeatures |= CCID_CLASS_EXTENDED_APDU; } break; case ElatecTWN4_CCID_CDC: case ElatecTWN4_CCID: case SCM_SCL011: /* restore default timeout (modified in ccid_open_hack_pre()) */ ccid_descriptor->readTimeout = DEFAULT_COM_READ_TIMEOUT; break; case BIT4ID_MINILECTOR: /* The firmware 1.11 advertises pinpad but actually doesn't * have one */ ccid_descriptor->bPINSupport = 0; break; case SAFENET_ETOKEN_5100: /* the old SafeNet eToken 5110 SC (firmware 0.12 & 0.13) * does not like IFSD negotiation. So disable it. */ if ((0x0012 == ccid_descriptor->IFD_bcdDevice) || (0x0013 == ccid_descriptor->IFD_bcdDevice)) ccid_descriptor->dwFeatures |= CCID_CLASS_AUTO_IFSD; break; } /* Gemalto readers may report additional information */ if (GET_VENDOR(ccid_descriptor->readerID) == VENDOR_GEMALTO) set_gemalto_firmware_features(reader_index); return return_value; } /* ccid_open_hack_post */ /***************************************************************************** * * ccid_error * ****************************************************************************/ void ccid_error(int log_level, int error, const char *file, int line, const char *function) { #ifndef NO_LOG const char *text; char var_text[30]; switch (error) { case 0x00: text = "Command not supported or not allowed"; break; case 0x01: text = "Wrong command length"; break; case 0x05: text = "Invalid slot number"; break; case 0xA2: text = "Card short-circuiting. Card powered off"; break; case 0xA3: text = "ATR too long (> 33)"; break; case 0xAB: text = "No data exchanged"; break; case 0xB0: text = "Reader in EMV mode and T=1 message too long"; break; case 0xBB: text = "Protocol error in EMV mode"; break; case 0xBD: text = "Card error during T=1 exchange"; break; case 0xBE: text = "Wrong APDU command length"; break; case 0xE0: text = "Slot busy"; break; case 0xEF: text = "PIN cancelled"; break; case 0xF0: text = "PIN timeout"; break; case 0xF2: text = "Busy with autosequence"; break; case 0xF3: text = "Deactivated protocol"; break; case 0xF4: text = "Procedure byte conflict"; break; case 0xF5: text = "Class not supported"; break; case 0xF6: text = "Protocol not supported"; break; case 0xF7: text = "Invalid ATR checksum byte (TCK)"; break; case 0xF8: text = "Invalid ATR first byte"; break; case 0xFB: text = "Hardware error"; break; case 0xFC: text = "Overrun error"; break; case 0xFD: text = "Parity error during exchange"; break; case 0xFE: text = "Card absent or mute"; break; case 0xFF: text = "Activity aborted by Host"; break; default: if ((error >= 1) && (error <= 127)) (void)snprintf(var_text, sizeof(var_text), "error on byte %d", error); else (void)snprintf(var_text, sizeof(var_text), "Unknown CCID error: 0x%02X", error); text = var_text; break; } log_msg(log_level, "%s:%d:%s %s", file, line, function, text); #endif } /* ccid_error */
{ "content_hash": "7a5c682304f525189588da312461a94f", "timestamp": "", "source": "github", "line_count": 708, "max_line_length": 120, "avg_line_length": 26.257062146892654, "alnum_prop": 0.6110274341043572, "repo_name": "GoogleChromeLabs/chromeos_smart_card_connector", "id": "21a2fe843f71b6d86a5581764ef6972813bed31d", "size": "19380", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "third_party/ccid/src/src/ccid.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4254" }, { "name": "C++", "bytes": "722639" }, { "name": "CSS", "bytes": "9725" }, { "name": "HTML", "bytes": "17393" }, { "name": "JavaScript", "bytes": "361786" }, { "name": "Lua", "bytes": "1704" }, { "name": "Makefile", "bytes": "116814" }, { "name": "Python", "bytes": "27331" }, { "name": "Shell", "bytes": "12794" } ], "symlink_target": "" }
<?php namespace AthosHun\HTMLFilter; class HTMLFilterTest extends \PHPUnit_Framework_TestCase { private $filter; private $filter_config; private $mb_substitute_character; public function setUp() { $this->filter_config = new Configuration(); $this->filter = new HTMLFilter(); $this->mbstring_substitute_character = ini_get( "mbstring.substitute_character" ); ini_set("mbstring.substitute_character", "none"); } public function tearDown() { ini_set( "mbstring.substitute_character", $this->mbstring_substitute_character ); } public function testPlainTextWithoutAnyHtmlRemainsUnchanged() { $this->assertFilteredHTML("", ""); $this->assertFilteredHTML("hello", "hello"); } private function assertFilteredHTML($expected_html, $html) { $this->assertSame( $expected_html, $this->filter->filter($this->filter_config, $html) ); } public function testDisallowedTagsAreRemoved() { $this->assertFilteredHTML("lorem ipsum", "lorem <a>ipsum</a>"); } public function testAllowedTagsAreKept() { $this->filter_config->allowTag("a"); $html = "lorem <a>ipsum</a>"; $this->assertFilteredHTML($html, $html); } public function testDisallowedAttributesAreRemoved() { $this->filter_config->allowTag("a"); $this->assertFilteredHTML( "lorem <a>ipsum</a>", "lorem <a href=\"hello\">ipsum</a>" ); } public function testAllowedAttributesAreKept() { $this->filter_config->allowTag("a") ->allowAttribute("a", "href"); $html = "lorem <a href=\"hello\">ipsum</a>"; $this->assertFilteredHTML($html, $html); } public function testAllowedAttributesNotMatchingARegexpAreRemoved() { $this->filter_config->allowAttribute("a", "href", "/^hello\$/"); $this->assertFilteredHTML( "lorem <a>ipsum</a>", "lorem <a href=\"world\">ipsum</a>" ); } public function testHTMLEntitiesAreLeftUnchanged() { $this->filter_config->allowAttribute("a", "href"); $quoted_special_chars_attr = "&lt;&quot;&amp;&gt;'"; $quoted_special_chars_text = "&lt;\"&amp;&gt;'"; $quoted_html = "<a href=\"$quoted_special_chars_attr\">" . $quoted_special_chars_text . "</a>"; $this->assertFilteredHTML($quoted_html, $quoted_html); } public function testNodesAreCopiedRecursively() { $this->filter_config->allowTag("p") ->allowTag("b") ->allowAttribute("a", "href", "/^hello\$/"); $this->assertFilteredHTML( "Lorem <p><b><a>ipsum</a> dolor sit</b> amet</p>", "Lorem <p><b><a>ipsum</a> <em>dolor</em> <em>sit</em></b> amet</p>" ); } public function testHtmlCommentsArePreserved() { $html = "Lorem <!-- <Hello> --> Ipsum"; $this->assertFilteredHTML($html, $html); } public function testInvalidMarkupIsIgnored() { $this->assertFilteredHTML( "hello world", "<nosuchtag>hello world</x></nosuchtag>" ); } public function testWorksWithCjkCharacters() { $zh = "格萊美紅毯大戰誰是贏家"; $jp = "日本語です。"; $ko = "빛나리의 타잔 주제가"; $this->assertFilteredHTML( "$zh$jp$ko", "<p>$zh</p><p>$jp</p><p>$ko</p>" ); } public function testIgnoresInvalidUtf8() { $this->filter_config->allowTag("p"); $this->assertFilteredHTML( "prefix <p> onclick=alert(42)&gt;infix\n\nsuffix</p>", "prefix <p\xe6> onclick=alert(42)>infix\xe6\xff\n\nsuffix" ); } }
{ "content_hash": "f61eeb92e237cd679e501ddad089a222", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 79, "avg_line_length": 26.97945205479452, "alnum_prop": 0.5435389692815435, "repo_name": "attilammagyar/html-filter", "id": "d1914c9b2cfe8523cc2becf1d3643c460d386055", "size": "3991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AthosHun/HTMLFilter/HTMLFilterTest.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Makefile", "bytes": "1087" }, { "name": "PHP", "bytes": "14529" }, { "name": "Shell", "bytes": "3470" } ], "symlink_target": "" }
package com.commercetools.sunrise.ctp.client; import com.commercetools.sunrise.framework.controllers.metrics.SimpleMetricsSphereClientProvider; import com.google.inject.AbstractModule; import io.sphere.sdk.client.SphereClient; import io.sphere.sdk.client.SphereClientConfig; import javax.inject.Singleton; /** * Module that allows to inject a {@link SphereClient} and its configuration. */ public final class SphereClientModule extends AbstractModule { @Override protected void configure() { bind(SphereClientConfig.class) .toProvider(SphereClientConfigProvider.class) .in(Singleton.class); bind(SphereClient.class) .toProvider(SimpleMetricsSphereClientProvider.class) .in(Singleton.class); } }
{ "content_hash": "898ac78d013458f28f6588b960d41ae6", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 97, "avg_line_length": 31.76, "alnum_prop": 0.7292191435768262, "repo_name": "commercetools/commercetools-sunrise-java", "id": "32389817c989ed6a2214afa578cc8b50eade1d4a", "size": "794", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "common/app/com/commercetools/sunrise/ctp/client/SphereClientModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "730" }, { "name": "HTML", "bytes": "5125" }, { "name": "Java", "bytes": "1602231" }, { "name": "JavaScript", "bytes": "1831" }, { "name": "Scala", "bytes": "13450" }, { "name": "Shell", "bytes": "20940" } ], "symlink_target": "" }
//jshint strict: false module.exports = function(config) { config.set({ basePath: './app', files: [ 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', 'components/**/*.js', 'view*/**/*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
{ "content_hash": "91e5af3931c481c5bd163392a11f2ee8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 62, "avg_line_length": 21.636363636363637, "alnum_prop": 0.484593837535014, "repo_name": "saaresto/saaresto.github.io", "id": "8febba6a3ebd33842254c87a557857cd7e69a7af", "size": "714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "karma.conf.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1300" }, { "name": "HTML", "bytes": "4523" }, { "name": "JavaScript", "bytes": "10727" } ], "symlink_target": "" }
namespace blink { namespace EmulationAgentState { static const char scriptExecutionDisabled[] = "scriptExecutionDisabled"; static const char touchEventEmulationEnabled[] = "touchEventEmulationEnabled"; static const char emulatedMedia[] = "emulatedMedia"; } PassOwnPtrWillBeRawPtr<InspectorEmulationAgent> InspectorEmulationAgent::create(WebLocalFrameImpl* webLocalFrameImpl) { return adoptPtrWillBeNoop(new InspectorEmulationAgent(webLocalFrameImpl)); } InspectorEmulationAgent::InspectorEmulationAgent(WebLocalFrameImpl* webLocalFrameImpl) : InspectorBaseAgent<InspectorEmulationAgent, InspectorFrontend::Emulation>("Emulation") , m_webLocalFrameImpl(webLocalFrameImpl) { webViewImpl()->devToolsEmulator()->setEmulationAgent(this); } InspectorEmulationAgent::~InspectorEmulationAgent() { } WebViewImpl* InspectorEmulationAgent::webViewImpl() { return m_webLocalFrameImpl->viewImpl(); } void InspectorEmulationAgent::restore() { ErrorString error; setScriptExecutionDisabled(&error, m_state->getBoolean(EmulationAgentState::scriptExecutionDisabled)); setTouchEmulationEnabled(&error, m_state->getBoolean(EmulationAgentState::touchEventEmulationEnabled), nullptr); setEmulatedMedia(&error, m_state->getString(EmulationAgentState::emulatedMedia)); } void InspectorEmulationAgent::disable(ErrorString*) { ErrorString error; setScriptExecutionDisabled(&error, false); setTouchEmulationEnabled(&error, false, nullptr); setEmulatedMedia(&error, String()); } void InspectorEmulationAgent::discardAgent() { webViewImpl()->devToolsEmulator()->setEmulationAgent(nullptr); } void InspectorEmulationAgent::didCommitLoadForLocalFrame(LocalFrame* frame) { if (frame == m_webLocalFrameImpl->frame()) viewportChanged(); } void InspectorEmulationAgent::resetScrollAndPageScaleFactor(ErrorString*) { webViewImpl()->resetScrollAndScaleStateImmediately(); } void InspectorEmulationAgent::setPageScaleFactor(ErrorString*, double pageScaleFactor) { webViewImpl()->setPageScaleFactor(static_cast<float>(pageScaleFactor)); } void InspectorEmulationAgent::setScriptExecutionDisabled(ErrorString*, bool value) { m_state->setBoolean(EmulationAgentState::scriptExecutionDisabled, value); webViewImpl()->devToolsEmulator()->setScriptExecutionDisabled(value); } void InspectorEmulationAgent::setTouchEmulationEnabled(ErrorString*, bool enabled, const String* configuration) { m_state->setBoolean(EmulationAgentState::touchEventEmulationEnabled, enabled); webViewImpl()->devToolsEmulator()->setTouchEventEmulationEnabled(enabled); } void InspectorEmulationAgent::setEmulatedMedia(ErrorString*, const String& media) { m_state->setString(EmulationAgentState::emulatedMedia, media); webViewImpl()->page()->settings().setMediaTypeOverride(media); } void InspectorEmulationAgent::viewportChanged() { if (!webViewImpl()->devToolsEmulator()->deviceEmulationEnabled() || !frontend()) return; FrameView* view = m_webLocalFrameImpl->frameView(); if (!view) return; IntSize contentsSize = view->contentsSize(); FloatPoint scrollOffset; scrollOffset = FloatPoint(view->scrollableArea()->visibleContentRectDouble().location()); RefPtr<TypeBuilder::Emulation::Viewport> viewport = TypeBuilder::Emulation::Viewport::create() .setScrollX(scrollOffset.x()) .setScrollY(scrollOffset.y()) .setContentsWidth(contentsSize.width()) .setContentsHeight(contentsSize.height()) .setPageScaleFactor(webViewImpl()->page()->pageScaleFactor()) .setMinimumPageScaleFactor(webViewImpl()->minimumPageScaleFactor()) .setMaximumPageScaleFactor(webViewImpl()->maximumPageScaleFactor()); frontend()->viewportChanged(viewport); } DEFINE_TRACE(InspectorEmulationAgent) { visitor->trace(m_webLocalFrameImpl); InspectorBaseAgent::trace(visitor); } } // namespace blink
{ "content_hash": "03acf396dc44b436c24a71a2ca7013cb", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 117, "avg_line_length": 34.165217391304346, "alnum_prop": 0.7742428098752864, "repo_name": "Bysmyyr/chromium-crosswalk", "id": "b879e210a53ca61c8e4d99d71e29def99eb73e62", "size": "4470", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/web/InspectorEmulationAgent.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
from ..dojo_test_case import DojoTestCase, get_unit_tests_path from dojo.tools.trustwave_fusion_api.parser import TrustwaveFusionAPIParser from dojo.models import Test class TestTrustwaveFusionAPIParser(DojoTestCase): def test_parse_file_with_no_vuln_has_no_findings(self): testfile = open( get_unit_tests_path() + "/scans/trustwave_fusion_api/trustwave_fusion_api_zero_vul.json" ) parser = TrustwaveFusionAPIParser() findings = parser.get_findings(testfile, Test()) self.assertEqual(0, len(findings)) def test_vuln_with_valid_cve(self): testfile = open("unittests/scans/trustwave_fusion_api/test_cve.json") parser = TrustwaveFusionAPIParser() findings = parser.get_findings(testfile, Test()) for finding in findings: for endpoint in finding.unsaved_endpoints: endpoint.clean() # first example finding = findings[0] self.assertEqual("CVE-2017-7529", finding.cve) self.assertEqual( "Vulnerability/Missing Patch; CVEs: CVE-2017-7529", finding.description ) # second example finding = findings[1] self.assertEqual("CVE-2013-2566", finding.cve) # We use the first cve self.assertEqual( "Cryptography/Weak Cryptography; CVEs: CVE-2013-2566, CVE-2015-2808", finding.description, ) self.assertEqual(str(finding.unsaved_endpoints[0]), "https://google.com") def test_parse_file_with_multiple_vuln_has_multiple_findings(self): testfile = open( get_unit_tests_path() + "/scans/trustwave_fusion_api/trustwave_fusion_api_many_vul.json" ) parser = TrustwaveFusionAPIParser() findings = parser.get_findings(testfile, Test()) self.assertEqual(3, len(findings)) # checking dupes # endpoint validation for finding in findings: for endpoint in finding.unsaved_endpoints: endpoint.clean() finding = findings[0] self.assertEqual("0123456:id", finding.unique_id_from_tool) self.assertEqual("Website Detected", finding.title) self.assertEqual( "Information/Service Discovery; CVEs: no match", finding.description ) date = finding.date.strftime("%Y-%m-%dT%H:%M:%S.%f%z") self.assertEqual("2021-06-15T07:48:08.727000+0000", date) self.assertEqual("Info", finding.severity) self.assertIsNone(finding.cve) # should be none since CVE is "CVE-NO-MATCH" endpoint = finding.unsaved_endpoints[0] self.assertEqual(str(endpoint), "https://google.com") self.assertEqual(endpoint.host, "google.com") self.assertIsNone(endpoint.path) self.assertEqual(endpoint.port, 443) # testing component_name and component_version finding = findings[2] self.assertEqual("nginx:nginx", finding.component_name) self.assertEqual("1.20.0", finding.component_version)
{ "content_hash": "a7b24e84fb8f7a7fc5d5a1beed800110", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 100, "avg_line_length": 41.465753424657535, "alnum_prop": 0.6484968615791212, "repo_name": "rackerlabs/django-DefectDojo", "id": "c3179033dd33b19600f7477793741e94bf8fa3bb", "size": "3027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unittests/tools/test_trustwave_fusion_api_parser.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "18132" }, { "name": "Groff", "bytes": "91" }, { "name": "HTML", "bytes": "666571" }, { "name": "JavaScript", "bytes": "6393" }, { "name": "Python", "bytes": "524728" }, { "name": "Shell", "bytes": "20558" }, { "name": "XSLT", "bytes": "6624" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__twoIntsStruct_calloc_54c.c Label Definition File: CWE401_Memory_Leak.c.label.xml Template File: sources-sinks-54c.tmpl.c */ /* * @description * CWE: 401 Memory Leak * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call free() on data * BadSink : no deallocation of data * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD /* bad function declaration */ void CWE401_Memory_Leak__twoIntsStruct_calloc_54d_badSink(twoIntsStruct * data); void CWE401_Memory_Leak__twoIntsStruct_calloc_54c_badSink(twoIntsStruct * data) { CWE401_Memory_Leak__twoIntsStruct_calloc_54d_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE401_Memory_Leak__twoIntsStruct_calloc_54d_goodG2BSink(twoIntsStruct * data); void CWE401_Memory_Leak__twoIntsStruct_calloc_54c_goodG2BSink(twoIntsStruct * data) { CWE401_Memory_Leak__twoIntsStruct_calloc_54d_goodG2BSink(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE401_Memory_Leak__twoIntsStruct_calloc_54d_goodB2GSink(twoIntsStruct * data); void CWE401_Memory_Leak__twoIntsStruct_calloc_54c_goodB2GSink(twoIntsStruct * data) { CWE401_Memory_Leak__twoIntsStruct_calloc_54d_goodB2GSink(data); } #endif /* OMITGOOD */
{ "content_hash": "b62483460b7d2adb12ac48ad235385d7", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 157, "avg_line_length": 30.903846153846153, "alnum_prop": 0.7324206596141879, "repo_name": "maurer/tiamat", "id": "d88fcc265547738c7f5c0134c1175bdfb1cad13f", "size": "1607", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE401_Memory_Leak/s03/CWE401_Memory_Leak__twoIntsStruct_calloc_54c.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module EventHub module Components VERSION = "0.3.1" end end
{ "content_hash": "e93373eef392e1fa5d603afcd576c951", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 21, "avg_line_length": 13.6, "alnum_prop": 0.6764705882352942, "repo_name": "thomis/eventhub-components", "id": "3f0f6cecebca17630e6e82d12137a6e80c7755ec", "size": "68", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/eventhub/components/version.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "15347" } ], "symlink_target": "" }
@import url(http://fonts.googleapis.com/css?family=Slabo+27px); @import url(http://fonts.googleapis.com/css?family=Raleway:500,700,400); /* === === === === Tool Box Theme Css === === === === */ body { background: #282827 url('images/bg.png') repeat top left; margin-top: 100px; font-size: 14px; font-family: 'Raleway', sans-serif; line-height: 23px; color: #ffffff; } header { border-bottom: 2px dashed #666666; } h1 { color: #ffffff; font-size: 60px; font-weight: normal; } h2 { color: #ffffff; border-bottom: 1px dashed #666666; padding: 2px 0 5px 2px; font-weight: normal; } h3 { color: #ffffff; padding: 10px 0 0 0; font-weight: normal; font-size: 14px; text-transform: capitalize; } section ul li { margin: 10px 0; } .center { float: none !important; } footer { border-top: 2px dashed #666666; font-size: 12px; text-align: center; } #html { border: 1px solid #e1e1e8 !important; clear: both; margin-bottom: 30px; border-radius: 4px 4px; position: relative; } #html pre { padding: 10px 10px 10px 16px; font-size: 13px; line-height: 1.42857143; color: #333; word-break: break-all; word-wrap: break-word; background-color: #444; margin: 0; border: 0 solid #e1e1e8 !important; border-radius: 4px; } #html pre .tag { color: #89bdff; } #html pre .atn { color: #bdb76b; } #html pre .pun { color: #fff; } #html pre .atv { color: #65B042; } /* === === === === Tool Box Css === === === === */ .toolbox { margin: 0; padding: 0; border: 1px #000000 solid; display: inline-block; } .toolbox .title { margin: 0; padding: 2px; border-bottom: 1px solid #000000; background: #4d4d4d; color: #ffffff; float: left; width: 100%; } .toolbox .title .title_name { float: right; padding: 3px 5px 0 0; font-size: 12px; } .toolbox .title .title_btn { float: left; padding: 0 0 0 2px; } .toolbox .title .title_btn button { color: #ffffff; text-decoration: none; font-size: 11px; background: none; border: 0; outline: none; cursor: pointer; } .toolbox .toolbox_menu { float: left; margin: 0; padding: 0; } .toolbox .toolbox_menu ul { margin: 0; padding: 0; } .toolbox .toolbox_menu ul li { margin: 0; list-style: none; background: #ffffff; clear: both; border: 1px solid #e6e6e6; padding: 5px 10px; overflow: hidden; cursor: pointer; color: #666666; } .toolbox .toolbox_menu ul li.active { color: #3eceb5 !important; } .toolbox .toolbox_menu ul li:hover { color: #3eceb5; } .toolbox .toolbox_menu ul li span { float: left; height: 22px; line-height: 22px; } .toolbox .toolbox_menu ul li img { float: left; height: 22px; line-height: 22px; } .toolbox .toolbox_menu ul li p { float: left; margin: 0 0 0 5px; padding: 0; width: 80px; overflow: hidden; height: 22px; line-height: 22px; } /* === === === === Tool Box Line === === === === */ .toolbox-line { margin: 0; padding: 0; border: 1px #000000 solid; display: inline-block; } .toolbox-line .title { margin: 0; padding: 1px; border-bottom: 1px solid #000000; background: #4d4d4d; color: #ffffff; float: left; width: 100%; } .toolbox-line .title .title_name { float: right; padding: 3px 5px 0 0; font-size: 12px; } .toolbox-line .title .title_btn { float: left; padding: 0 0 0 2px; } .toolbox-line .title .title_btn button { color: #ffffff; text-decoration: none; font-size: 11px; background: none; border: 0; outline: none; cursor: pointer; } .toolbox-line .toolbox-line-left, .toolbox-line .toolbox-line-right { float: left; margin: 0; padding: 0; } .toolbox-line .toolbox-line-left ul, .toolbox-line .toolbox-line-right ul { margin: 0; padding: 0; } .toolbox-line .toolbox-line-left ul li, .toolbox-line .toolbox-line-right ul li { margin: 0; list-style: none; background: #ffffff; clear: both; border: 1px solid #e6e6e6; padding: 5px 10px; overflow: hidden; cursor: pointer; color: #666666; } .toolbox-line .toolbox-line-left ul li:hover, .toolbox-line .toolbox-line-right ul li:hover { color: #3eceb5; } .toolbox-line .toolbox-line-left ul li.active, .toolbox-line .toolbox-line-right ul li.active { color: #3eceb5; } .toolbox-line .toolbox-line-left ul li span, .toolbox-line .toolbox-line-right ul li span { float: left; height: 22px; line-height: 22px; } .toolbox-line .toolbox-line-left ul li p, .toolbox-line .toolbox-line-right ul li p { float: left; margin: 0 0 0 5px; padding: 0; width: 80px; overflow: hidden; height: 22px; line-height: 22px; } /* === === === === Tool Box without text === === === === */ .toolbox-without-text { margin: 0; padding: 0; border: 1px #000000 solid; display: inline-block; } .toolbox-without-text .title { margin: 0; padding: 2px; border-bottom: 1px solid #000000; background: #4d4d4d; color: #ffffff; float: left; width: 100%; } .toolbox-without-text .title .title_name { float: right; padding: 3px 5px 0 0; font-size: 12px; } .toolbox-without-text .title .title_btn { float: left; padding: 0 0 0 2px; } .toolbox-without-text .title .title_btn button { color: #ffffff; text-decoration: none; font-size: 11px; background: none; border: 0; outline: none; cursor: pointer; } .toolbox-without-text .toolbox-line-left, .toolbox-without-text .toolbox-line-right { float: left; margin: 0; padding: 0; } .toolbox-without-text .toolbox-line-left ul, .toolbox-without-text .toolbox-line-right ul { margin: 0; padding: 0; } .toolbox-without-text .toolbox-line-left ul li, .toolbox-without-text .toolbox-line-right ul li { margin: 0; list-style: none; background: #ffffff; clear: both; border: 1px solid #e6e6e6; padding: 5px 10px; overflow: hidden; cursor: pointer; color: #666666; } .toolbox-without-text .toolbox-line-left ul li:hover, .toolbox-without-text .toolbox-line-right ul li:hover { color: #3eceb5; } .toolbox-without-text .toolbox-line-left ul li.active, .toolbox-without-text .toolbox-line-right ul li.active { color: #3eceb5; } .toolbox-without-text .toolbox-line-left ul li span, .toolbox-without-text .toolbox-line-right ul li span { float: left; height: 22px; line-height: 22px; } .toolbox-without-text .toolbox-line-left ul li p, .toolbox-without-text .toolbox-line-right ul li p { float: left; margin: 0 0 0 5px; padding: 0; width: 80px; overflow: hidden; height: 22px; line-height: 22px; display: none; } .both { clear: both; } .hide { display: none; } .show { display: block; } /* === === === === Tool Box colors === === === === */ #toolbox-blue, #toolbox-cyan, #toolbox-green, #toolbox-orange, #toolbox-red { margin: 0; padding: 0; display: inline-block; } #toolbox-blue .title, #toolbox-cyan .title, #toolbox-green .title, #toolbox-orange .title, #toolbox-red .title { margin: 0; padding: 2px; float: left; width: 100%; } #toolbox-blue .title .title_name, #toolbox-cyan .title .title_name, #toolbox-green .title .title_name, #toolbox-orange .title .title_name, #toolbox-red .title .title_name { float: right; padding: 3px 5px 0 0; font-size: 12px; } #toolbox-blue .title .title_btn, #toolbox-cyan .title .title_btn, #toolbox-green .title .title_btn, #toolbox-orange .title .title_btn, #toolbox-red .title .title_btn { float: left; padding: 0 0 0 2px; } #toolbox-blue .title .title_btn button, #toolbox-cyan .title .title_btn button, #toolbox-green .title .title_btn button, #toolbox-orange .title .title_btn button, #toolbox-red .title .title_btn button { text-decoration: none; font-size: 11px; background: none; border: 0; outline: none; cursor: pointer; } #toolbox-blue .toolbox_menu, #toolbox-cyan .toolbox_menu, #toolbox-green .toolbox_menu, #toolbox-orange .toolbox_menu, #toolbox-red .toolbox_menu { float: left; margin: 0; padding: 0; } #toolbox-blue .toolbox_menu ul, #toolbox-cyan .toolbox_menu ul, #toolbox-green .toolbox_menu ul, #toolbox-orange .toolbox_menu ul, #toolbox-red .toolbox_menu ul { margin: 0; padding: 0; } #toolbox-blue .toolbox_menu ul li, #toolbox-cyan .toolbox_menu ul li, #toolbox-green .toolbox_menu ul li, #toolbox-orange .toolbox_menu ul li, #toolbox-red .toolbox_menu ul li { margin: 0; list-style: none; clear: both; padding: 5px 10px; overflow: hidden; cursor: pointer; } #toolbox-blue .toolbox_menu ul li span, #toolbox-cyan .toolbox_menu ul li span, #toolbox-green .toolbox_menu ul li span, #toolbox-orange .toolbox_menu ul li span, #toolbox-red .toolbox_menu ul li span { float: left; height: 22px; line-height: 22px; } #toolbox-blue .toolbox_menu ul li p, #toolbox-cyan .toolbox_menu ul li p, #toolbox-green .toolbox_menu ul li p, #toolbox-orange .toolbox_menu ul li p, #toolbox-red .toolbox_menu ul li p { float: left; margin: 0 0 0 5px; padding: 0; width: 80px; overflow: hidden; height: 22px; line-height: 22px; } /* === === === === Blue Colors === === === === */ #toolbox-blue { border: 1px #23a7e0 solid; } #toolbox-blue .title { border-bottom: 1px solid #23a7e0; background: #50b9e6; color: #ffffff; } #toolbox-blue .title .title_btn button { color: #ffffff; } #toolbox-blue .toolbox_menu ul li { background: #ffffff; border: 1px solid #e6e6e6; color: #666666; } #toolbox-blue .toolbox_menu ul li.active, #toolbox-blue .toolbox_menu ul li:hover { color: #50b9e6 !important; } /* === === === === Cyan Colors === === === === */ #toolbox-cyan { border: 1px #2eb59e solid; } #toolbox-cyan .title { border-bottom: 1px solid #2eb59e; background: #3eceb5; color: #ffffff; } #toolbox-cyan .title .title_btn button { color: #ffffff; } #toolbox-cyan .toolbox_menu ul li { background: #ffffff; border: 1px solid #e6e6e6; color: #666666; } #toolbox-cyan .toolbox_menu ul li.active, #toolbox-cyan .toolbox_menu ul li:hover { color: #3eceb5 !important; } /* === === === === Green Colors === === === === */ #toolbox-green { border: 1px #87c940 solid; } #toolbox-green .title { border-bottom: 1px solid #87c940; background: #a0d468; color: #ffffff; } #toolbox-green .title .title_btn button { color: #ffffff; } #toolbox-green .toolbox_menu ul li { background: #ffffff; border: 1px solid #e6e6e6; color: #666666; } #toolbox-green .toolbox_menu ul li.active, #toolbox-green .toolbox_menu ul li:hover { color: #a0d468 !important; } /* === === === === Orange Colors === === === === */ #toolbox-orange { border: 1px #f78d11 solid; } #toolbox-orange .title { border-bottom: 1px solid #f78d11; background: #f9a542; color: #ffffff; } #toolbox-orange .title .title_btn button { color: #ffffff; } #toolbox-orange .toolbox_menu ul li { background: #ffffff; border: 1px solid #e6e6e6; color: #666666; } #toolbox-orange .toolbox_menu ul li.active, #toolbox-orange .toolbox_menu ul li:hover { color: #f9a542 !important; } /* === === === === Red Colors === === === === */ #toolbox-red { border: 1px #ff2e2d solid; } #toolbox-red .title { border-bottom: 1px solid #ff2e2d; background: #ff6160; color: #ffffff; } #toolbox-red .title .title_btn button { color: #ffffff; } #toolbox-red .toolbox_menu ul li { background: #ffffff; border: 1px solid #e6e6e6; color: #666666; } #toolbox-red .toolbox_menu ul li.active, #toolbox-red .toolbox_menu ul li:hover { color: #ff6160 !important; } /*# sourceMappingURL=style.css.map */
{ "content_hash": "23cf212cb184ca58f5185c49ce2c0c33", "timestamp": "", "source": "github", "line_count": 531, "max_line_length": 72, "avg_line_length": 21.429378531073446, "alnum_prop": 0.657702785833553, "repo_name": "srinivaserukulla/toolbox", "id": "710fc716f47fe5d9ed1d88488a566e1453b6dcae", "size": "11381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "styles/style.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "391201" }, { "name": "JavaScript", "bytes": "4433" } ], "symlink_target": "" }
""" Copyright (C) 2010-2013, Ryan Fan <ryan.fan@oracle.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from __future__ import absolute_import import requests import json import urllib from celery import shared_task, Task from sdk.constants import * from sdk.web.helper import WebHelper class BaseWeb(Task): abstract = True web_helper = WebHelper(Task.app.db) app_id, app_key = Task.app.db.hmget(WXMP_CONFIG, 'APP_ID', 'APP_KEY') #class get_access_token(BaseWeb): # def run(self, open_id): # return self.web_helper.get_access_token(open_id) class auth(BaseWeb): """ Authorization to obtain web access token @param: code @return: if succeed, returns openid """ def run(self, code): if not self.app_id or not self.app_key: print "No app_id or app_key when doing web authentication" return None url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' \ 'appid={0}&secret={1}&code={2}&' \ 'grant_type=authorization_code'.format(self.app_id, self.app_key, code) try: resp = requests.get(url).json() except Exception,e: print "Failed to do web authentication because of:{0}".format(e) return None if not isinstance(resp, dict): print "Invalid response format when do web authentication" return None if 'errcode' in resp.keys() and (resp['errcode'] != 0): print "Error response when do web authentication: {0}".format(resp['errmsg']) return None if not self.web_helper.save_auth_info(resp): return None return resp['openid'] class get_auth_url(BaseWeb): def run(self, redirect_url, scope): if not self.app_id: print "Failed to get app_id in get_auth_url()" return None auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' \ 'appid={0}&redirect_uri={1}&response_type=code' \ '&scope={2}#wechat_redirect'.format(self.app_id, urllib.quote_plus(redirect_url), scope) return auth_url class get_user_info(BaseWeb): def refresh_access_token(self, open_id): if not self.app_id: print "Failed to get app_id when refresh web access token" return None refresh_token = self.web_helper.get_refresh_token(open_id) if not refresh_token: return None url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?' \ 'appid={0}&grant_type=refresh_token&refresh_token={1}'.format( self.app_id, refresh_token ) try: resp = requests.get(url).json() except Exception,e: print "Failed to get refresh web access token because of:{0}".format(e) return None if not isinstance(resp, dict): print "Invalid response format when refresh web access token" return None if 'errcode' in resp.keys() and (resp['errcode'] != 0): print "Error response when refresh web access token: {0}".format(resp['errmsg']) return None # resp is a authentication info dict contains following: # # { # "access_token":"ACCESS_TOKEN", # "expires_in":7200, # "refresh_token":"REFRESH_TOKEN", # "openid":"OPENID", # "scope":"SCOPE" # } if not self.web_helper.save_auth_info(resp): return None return resp['access_token'] def run(self, open_id): access_token = self.web_helper.get_access_token(open_id) # first time check if we can get valid access_token from db if not access_token: # may be access_token expired, try refresh it print "Failed to get valid access_token from db, try to refresh it..." access_token = self.refresh_access_token(open_id) # second time check after refresh if not access_token: print "Failed to get access_token after refresh" return None url = 'https://api.weixin.qq.com/sns/userinfo?' \ 'access_token={0}&openid={1}&lang=zh_CN'.format(access_token, open_id) try: resp = requests.get(url) # Important: Must not use requests.response.json() method here # otherwise, requests will doing ascii encode against the unicode string resp = json.loads(resp.content) except Exception,e: print "Failed to get userinfo because of:{0}".format(e) return None if not isinstance(resp, dict): print "Invalid response format when get userinfo from Weixin server" return None if 'errcode' in resp.keys() and (resp['errcode'] != 0): print "Error response when get userinfo info from Weixin server: {0}".format(resp['errmsg']) return None return resp
{ "content_hash": "94f12d3659b8416633cd8c9ab8b3c340", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 108, "avg_line_length": 35.59119496855346, "alnum_prop": 0.6149496377451846, "repo_name": "rfancn/wxgigo", "id": "77e1048da9cc794719964911b7bbf2dd86b86e2a", "size": "5696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wxgigo/wxmp/api/webauth.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2696" }, { "name": "HTML", "bytes": "50544" }, { "name": "JavaScript", "bytes": "4201" }, { "name": "Python", "bytes": "356710" }, { "name": "Shell", "bytes": "1220" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Общомедия</string> <string name="menu_settings">Настройки</string> <string name="username">Потребителско име</string> <string name="password">Парола</string> <string name="login">Влизане</string> <string name="signup">Регистриране</string> <string name="logging_in_title">Влизане в системата</string> <string name="logging_in_message">Изчакайте…</string> <string name="login_success">Успешно вписване.</string> <string name="login_failed">Неуспешно вписване!</string> <string name="upload_failed">Файлът не е намерен. Моля, опитайте с друг файл.</string> <string name="authentication_failed">Неуспешен опит за удостоверяване!</string> <string name="uploading_started">Качването започна!</string> <string name="upload_completed_notification_title">Файл %1$s е качен!</string> <string name="upload_completed_notification_text">Докоснете, за да видите качения файл</string> <string name="upload_progress_notification_title_start">Качването на файл %1$s започна</string> <string name="upload_progress_notification_title_in_progress">Файл %1$s е в процес на качване</string> <string name="title_activity_contributions">Моите последни качвания</string> <string name="contribution_state_starting">Качване</string> <string name="provider_contributions">Моите качвания</string> <string name="menu_share">Споделяне</string> <string name="menu_open_in_browser">Преглед в браузъра</string> <string name="share_title_hint">Заглавие</string> <string name="share_description_hint">Описание</string> <string name="login_failed_network">Неуспешно влизане – проблем в мрежата</string> <string name="login_failed_username">Неуспешно влизане – моля проверете потребителското си име</string> <string name="login_failed_password">Неуспешно влизане – моля проверете паролата си</string> <string name="share_upload_button">Качване</string> <string name="provider_modifications">Изменения</string> <string name="menu_upload_single">Качване</string> <string name="menu_save_categories">Съхраняване</string> <plurals name="multiple_uploads_title"> <item quantity="one">%d качване</item> <item quantity="other">%d качвания</item> </plurals> <string name="categories_activity_title">Категории</string> <string name="title_activity_settings">Настройки</string> <string name="title_activity_signup">Регистриране</string> <string name="menu_about">Относно</string> <string name="title_activity_about">Относно</string> <string name="no_email_client">Не е инсталирана програма за електронна поща</string> <string name="menu_retry_upload">Повторен опит</string> <string name="menu_cancel_upload">Отказване</string> <string name="menu_download">Изтегляне</string> <string name="preference_license">Лиценз</string> <string name="preference_theme">Нощен режим</string> <string name="license_name_cc0">CC0</string> <string name="license_name_cc_by_sa_3_0">CC BY-SA 3.0</string> <string name="license_name_cc_by_sa_3_0_at">CC BY-SA 3.0 (Австрия)</string> <string name="license_name_cc_by_sa_3_0_de">CC BY-SA 3.0 (Германия)</string> <string name="license_name_cc_by_sa_3_0_ee">CC BY-SA 3.0 (Естония)</string> <string name="license_name_cc_by_sa_3_0_es">CC BY-SA 3.0 (Испания)</string> <string name="license_name_cc_by_sa_3_0_lu">CC BY-SA 3.0 (Люксембург)</string> <string name="license_name_cc_by_sa_3_0_no">CC BY-SA 3.0 (Норвегия)</string> <string name="license_name_cc_by_sa_3_0_pl">CC BY-SA 3.0 (Полша)</string> <string name="license_name_cc_by_sa_3_0_ro">CC BY-SA 3.0 (Румъния)</string> <string name="license_name_cc_by_3_0">CC BY 3.0</string> <string name="license_name_cc_by_sa_4_0">CC BY-SA 4.0</string> <string name="license_name_cc_by_4_0">CC BY 4.0</string> <string name="license_name_cc_zero">CC Zero</string> <string name="tutorial_1_text">В Общомедия се намират повечето изображения, използвани в Уикипедия.</string> <string name="tutorial_1_subtext">Вашите изображения помагат за образоването на хората по целия свят!</string> <string name="tutorial_3_text">Моля, НЕ качвайте:</string> <string name="welcome_final_button_text">Да!</string> <string name="detail_panel_cats_label">Категории</string> <string name="detail_panel_cats_loading">Зареждане…</string> <string name="detail_description_empty">Няма описание</string> <string name="detail_license_empty">Непознат лиценз</string> <string name="menu_refresh">Обновяване</string> <string name="ok">Добре</string> <string name="warning">Предупреждение</string> <string name="file_exists">Този файл вече съществува в Общомедия. Наистина ли искате да продължите?</string> <string name="yes">Да</string> <string name="no">Не</string> <string name="media_detail_title">Заглавие</string> <string name="media_detail_description">Описание</string> <string name="media_detail_uploaded_date">Дата на качване</string> <string name="welcome_image_llamas">Лами</string> <string name="welcome_image_tulip">Лале</string> <string name="cancel">Отказ</string> <string name="navigation_drawer_open">Отваряне</string> <string name="navigation_drawer_close">Затваряне</string> <string name="navigation_item_home">Начало</string> <string name="navigation_item_upload">Качване</string> <string name="navigation_item_nearby">Наблизо</string> <string name="navigation_item_about">За приложението</string> <string name="navigation_item_settings">Настройки</string> <string name="navigation_item_feedback">Обратна връзка</string> <string name="navigation_item_logout">Излизане</string> </resources>
{ "content_hash": "8eb4384b3752e35648c58b64a0ae48c0", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 112, "avg_line_length": 61.45652173913044, "alnum_prop": 0.7357622921825256, "repo_name": "tobias47n9e/apps-android-commons", "id": "5d3a16b8bb2ad0c2c9bf9b5dbc4600bc5f2182e2", "size": "6774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values-bg/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "445689" }, { "name": "Makefile", "bytes": "595" }, { "name": "PHP", "bytes": "3156" }, { "name": "Shell", "bytes": "1449" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class Archive {} exports.Archive = Archive; class StreamMap { // Index of folder for each file. // fileFolderIndex: Array<number> toString() { return `StreamMap, offsets of ${this.packStreamOffsets.length} packed streams, first files of ${this.folderFirstFileIndex.length} folders`; } } exports.StreamMap = StreamMap; //# sourceMappingURL=Archive.js.map
{ "content_hash": "a6d233d83ba9b5948e22fe6a835b93c6", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 147, "avg_line_length": 30.6, "alnum_prop": 0.7058823529411765, "repo_name": "erdanieee/imagePicker", "id": "955400d7213086ef76a0453c741bd38d674f6d7b", "size": "459", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/app-package-builder/out/Archive.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "243" }, { "name": "JavaScript", "bytes": "873" } ], "symlink_target": "" }
module ActionGuard class Role attr_reader :level def initialize(value, level) @value = value @level = level end def >=(other) level <= other.level end def < (other) level > other.level end def to_s "Role(:#{@value})" end end end
{ "content_hash": "ec32a337172cf1106e6340e045ccda32", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 32, "avg_line_length": 14.380952380952381, "alnum_prop": 0.5397350993377483, "repo_name": "rwestgeest/action-guard", "id": "774a2f2cf7c483fd55026b6ddfffc0b79e62f720", "size": "302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/action-guard/role.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21148" } ], "symlink_target": "" }