code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** @internal ** @file vl_siftdescriptor_python.cpp ** @author Andrea Vedaldi ** @author Mikael Rousson (Python wrapping) ** @brief SIFT descriptor - MEX **/ #include "../py_vlfeat.h" extern "C" { #include <vl/mathop.h> #include <vl/sift.h> } #include <math.h> #include <assert.h> #include <iostream> /* option codes */ enum { opt_magnif, opt_verbose }; /** ------------------------------------------------------------------ ** @internal ** @brief Transpose descriptor ** ** @param dst destination buffer. ** @param src source buffer. ** ** The function writes to @a dst the transpose of the SIFT descriptor ** @a src. The transpose is defined as the descriptor that one ** obtains from computing the normal descriptor on the transposed ** image. **/ VL_INLINE void transpose_descriptor(vl_sift_pix* dst, vl_sift_pix* src) { int const BO = 8; /* number of orientation bins */ int const BP = 4; /* number of spatial bins */ int i, j, t; for (j = 0; j < BP; ++j) { int jp = BP - 1 - j; for (i = 0; i < BP; ++i) { int o = BO * i + BP * BO * j; int op = BO * i + BP * BO * jp; dst[op] = src[o]; for (t = 1; t < BO; ++t) dst[BO - t + op] = src[t + o]; } } } /** ------------------------------------------------------------------ ** @brief MEX entry point **/ PyObject * vl_siftdescriptor_python( PyArrayObject & in_grad, PyArrayObject & in_frames) { // TODO: check types and dim // "GRAD must be a 2xMxN matrix of class SINGLE." assert(in_grad.descr->type_num == PyArray_FLOAT); assert(in_frames.descr->type_num == PyArray_FLOAT64); assert(in_grad.flags & NPY_FORTRAN); assert(in_frames.flags & NPY_FORTRAN); int verbose = 0; int opt; // TODO: check if we need to do a copy of the grad array float * grad_array; vl_sift_pix *grad; int M, N; double magnif = -1; double *ikeys = 0; int nikeys = 0; int i, j; /* ----------------------------------------------------------------- * Check the arguments * -------------------------------------------------------------- */ // get frames nb and data pointer nikeys = in_frames.dimensions[1]; ikeys = (double *) in_frames.data; // TODO: deal with optional params // while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) { // switch (opt) { // // case opt_verbose : // ++ verbose ; // break ; // // case opt_magnif : // if (!uIsRealScalar(optarg) || (magnif = *mxGetPr(optarg)) < 0) { // mexErrMsgTxt("MAGNIF must be a non-negative scalar.") ; // } // break ; // // default : // assert(0) ; // break ; // } // } // TODO: convert to Python //grad_array = mxDuplicateArray(in[IN_GRAD]); (copy?) grad = (float*) in_grad.data; //mxGetData(grad_array); M = in_grad.dimensions[1]; N = in_grad.dimensions[2]; /* transpose angles */ for (i = 1; i < 2 * M * N; i += 2) { grad[i] = VL_PI / 2 - grad[i]; } /* ----------------------------------------------------------------- * Do job * -------------------------------------------------------------- */ PyArrayObject * _descr; { VlSiftFilt *filt = 0; vl_uint8 *descr = 0; /* create a filter to process the image */ filt = vl_sift_new(M, N, -1, -1, 0); if (magnif >= 0) vl_sift_set_magnif(filt, magnif); if (verbose) { printf("siftdescriptor: filter settings:\n"); printf( "siftdescriptor: magnif = %g\n", vl_sift_get_magnif(filt)); printf("siftdescriptor: num of frames = %d\n", nikeys); } { npy_intp dims[2]; dims[0] = 128; dims[1] = nikeys; _descr = (PyArrayObject*) PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(PyArray_UBYTE), 2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL); descr = (vl_uint8*) _descr->data; } /* ............................................................... * Process each octave * ............................................................ */ for (i = 0; i < nikeys; ++i) { vl_sift_pix buf[128], rbuf[128]; double y = *ikeys++; double x = *ikeys++; double s = *ikeys++; double th = VL_PI / 2 - *ikeys++; vl_sift_calc_raw_descriptor(filt, grad, buf, M, N, x, y, s, th); transpose_descriptor(rbuf, buf); for (j = 0; j < 128; ++j) { double x = 512.0 * rbuf[j]; x = (x < 255.0) ? x : 255.0; *descr++ = (vl_uint8) (x); } } /* cleanup */ // mxDestroyArray(grad_array); vl_sift_delete(filt); } /* job done */ return PyArray_Return(_descr); }
DerThorsten/pyvlfeat
vlfeat/sift/vl_siftdescriptor.cpp
C++
gpl-2.0
4,699
/*! * jQuery Form Plugin * version: 3.33.0-2013.05.02 * @requires jQuery v1.5 or later * Copyright (c) 2013 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */ /*global ActiveXObject */ ;(function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; var hasProp = !!$.fn.prop; // attr2 uses prop when it can but checks the return type for // an expected string. this accounts for the case where a form // contains inputs with names like "action" or "method"; in those // cases "prop" returns the element $.fn.attr2 = function() { if ( ! hasProp ) return this.attr.apply(this, arguments); var val = this.prop.apply(this, arguments); if ( ( val && val.jquery ) || typeof val === 'string' ) return val; return this.attr.apply(this, arguments); }; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr2('method'); action = this.attr2('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; if (options.error) { var oldError = options.error; options.error = function(xhr, status, error) { var context = options.context || this; oldError.apply(context, [xhr, status, error, $form]); }; } if (options.complete) { var oldComplete = options.complete; options.complete = function(xhr, status) { var context = options.context || this; oldComplete.apply(context, [xhr, status, $form]); }; } // are there files to upload? // [value] (issue #113), also see comment: // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled[value!=""]', this); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData).split('&'); var len = serialized.length; var result = []; var i, part; for (i=0; i < len; i++) { // #252; undo param space replacement serialized[i] = serialized[i].replace(/\+/g,' '); part = serialized[i].split('='); // #278; use array instead of object storage, favoring array serializations result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (i=0; i < serializedData.length; i++) if (serializedData[i]) formdata.append(serializedData[i][0], serializedData[i][1]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }, false); } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { o.data = formdata; if(beforeSend) beforeSend.call(this, xhr, o); }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var deferred = $.Deferred(); if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( hasProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr2('name'); if (!n) $io.attr2('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; try { // #214, #257 if (io.contentWindow.document.execCommand) { io.contentWindow.document.execCommand('Stop'); } } catch(ignore) {} $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy */ var doc = null; // IE8 cascading access check try { if (frame.contentWindow) { doc = frame.contentWindow.document; } } catch(err) { // IE8 access denied under ssl & missing protocol log('cannot get iframe.contentWindow document: ' + err); } if (doc) { // successful getting content return doc; } try { // simply checking may throw in ie8 under ssl or mismatched protocol doc = frame.contentDocument ? frame.contentDocument : frame.document; } catch(err) { // last attempt log('cannot get iframe.contentDocument: ' + err); doc = frame.document; } return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr2('target'), a = $form.attr2('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').val(s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); try { form.submit(); } catch(err) { // just in case form has element with name/id of 'submit' var submitFn = document.createElement('form').submit; submitFn.apply(form); } } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } doc = getDoc(io); if(!doc) { log('cannot access response document'); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (err) { status = 'parsererror'; xhr.error = errMsg = (err || status); } } catch (err) { log('error caught: ',err); status = 'error'; xhr.error = errMsg = (err || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); deferred.resolve(xhr.responseText, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); deferred.reject(xhr, 'error', errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n || el.disabled) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file') { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (t == "file") { if (/MSIE/.test(navigator.userAgent)) { $(this).replaceWith($(this).clone(true)); } else { $(this).val(''); } } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })(jQuery);
12sm/erinmyers
wp-content/plugins/wp-toolbar-editor/js/jquery.form.js
JavaScript
gpl-2.0
41,603
<?php if (isset($_POST['gdsr_action']) && $_POST['gdsr_action'] == 'save') { $gdsr_options["bot_message"] = $_POST['gdsr_bot_message']; $gdsr_options["no_votes_percentage"] = $_POST['gdsr_no_votes_percentage']; $gdsr_options["cached_loading"] = isset($_POST['gdsr_cached_loading']) ? 1 : 0; $gdsr_options["include_opacity"] = isset($_POST['gdsr_include_opacity']) ? 1 : 0; $gdsr_options["comments_integration_articles_active"] = isset($_POST['gdsr_cmmintartactive']) ? 1 : 0; $gdsr_options["update_report_usage"] = isset($_POST['gdsr_update_report_usage']) ? 1 : 0; $gdsr_options["int_comment_std_zero"] = isset($_POST['gdsr_int_comment_std_zero']) ? 1 : 0; $gdsr_options["int_comment_mur_zero"] = isset($_POST['gdsr_int_comment_mur_zero']) ? 1 : 0; $gdsr_options["thumbs_active"] = isset($_POST['gdsr_thumbs_act']) ? 1 : 0; $gdsr_options["wp_query_handler"] = isset($_POST['gdsr_wp_query_handler']) ? 1 : 0; $gdsr_options["disable_ie6_check"] = isset($_POST['gdsr_disable_ie6_check']) ? 1 : 0; $gdsr_options["news_feed_active"] = isset($_POST['gdsr_news_feed_active']) ? 1 : 0; $gdsr_options["widgets_hidempty"] = isset($_POST['gdsr_widgets_hidempty']) ? 1 : 0; $gdsr_options["encoding"] = $_POST['gdsr_encoding']; $gdsr_options["admin_rows"] = $_POST['gdsr_admin_rows']; $gdsr_options["gfx_generator_auto"] = isset($_POST['gdsr_gfx_generator_auto']) ? 1 : 0; $gdsr_options["gfx_prevent_leeching"] = isset($_POST['gdsr_gfx_prevent_leeching']) ? 1 : 0; $gdsr_options["external_rating_css"] = isset($_POST['gdsr_external_rating_css']) ? 1 : 0; $gdsr_options["css_cache_active"] = isset($_POST['gdsr_css_cache_active']) ? 1 : 0; $gdsr_options["external_css"] = isset($_POST['gdsr_external_css']) ? 1 : 0; $gdsr_options["cmm_integration_replay_hide_review"] = isset($_POST['gdsr_cmm_integration_replay_hide_review']) ? 1 : 0; $gdsr_options["cmm_integration_prevent_duplicates"] = isset($_POST['gdsr_cmm_integration_prevent_duplicates']) ? 1 : 0; $gdsr_options["admin_advanced"] = isset($_POST['gdsr_admin_advanced']) ? 1 : 0; $gdsr_options["admin_placement"] = isset($_POST['gdsr_admin_placement']) ? 1 : 0; $gdsr_options["admin_defaults"] = isset($_POST['gdsr_admin_defaults']) ? 1 : 0; $gdsr_options["admin_import"] = isset($_POST['gdsr_admin_import']) ? 1 : 0; $gdsr_options["admin_export"] = isset($_POST['gdsr_admin_export']) ? 1 : 0; $gdsr_options["admin_setup"] = isset($_POST['gdsr_admin_setup']) ? 1 : 0; $gdsr_options["admin_ips"] = isset($_POST['gdsr_admin_ips']) ? 1 : 0; $gdsr_options["admin_views"] = isset($_POST['gdsr_admin_views']) ? 1 : 0; $gdsr_options["prefetch_data"] = isset($_POST['gdsr_prefetch_data']) ? 1 : 0; $gdsr_options["allow_mixed_ip_votes"] = isset($_POST['gdsr_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["cmm_allow_mixed_ip_votes"] = isset($_POST['gdsr_cmm_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["mur_allow_mixed_ip_votes"] = isset($_POST['gdsr_mur_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["cache_active"] = isset($_POST['gdsr_cache_active']) ? 1 : 0; $gdsr_options["cache_forced"] = isset($_POST['gdsr_cache_forced']) ? 1 : 0; $gdsr_options["cache_cleanup_auto"] = isset($_POST['gdsr_cache_cleanup_auto']) ? 1 : 0; $gdsr_options["cache_cleanup_days"] = $_POST['gdsr_cache_cleanup_days']; $gdsr_options["wait_show_article"] = isset($_POST['gdsr_wait_show_article']) ? 1 : 0; $gdsr_options["wait_show_comment"] = isset($_POST['gdsr_wait_show_comment']) ? 1 : 0; $gdsr_options["wait_show_multis"] = isset($_POST['gdsr_wait_show_multis']) ? 1 : 0; $gdsr_options["wait_loader_article"] = $_POST['gdsr_wait_loader_article']; $gdsr_options["wait_loader_comment"] = $_POST['gdsr_wait_loader_comment']; $gdsr_options["wait_loader_multis"] = $_POST['gdsr_wait_loader_multis']; $gdsr_options["wait_text_article"] = $_POST['gdsr_wait_text_article']; $gdsr_options["wait_text_comment"] = $_POST['gdsr_wait_text_comment']; $gdsr_options["wait_text_multis"] = $_POST['gdsr_wait_text_multis']; $gdsr_options["wait_class_article"] = $_POST['gdsr_wait_class_article']; $gdsr_options["wait_class_comment"] = $_POST['gdsr_wait_class_comment']; $gdsr_options["wait_class_multis"] = $_POST['gdsr_wait_class_multis']; $gdsr_options["wait_loader_artthumb"] = $_POST['gdsr_wait_loader_artthumb']; $gdsr_options["wait_loader_cmmthumb"] = $_POST['gdsr_wait_loader_cmmthumb']; $gdsr_options["security_showdashboard_user_level"] = $_POST['gdsr_security_showdashboard_user_level']; $gdsr_options["security_showip_user_level"] = $_POST['gdsr_security_showip_user_level']; $gdsr_options["google_rich_snippets_format"] = $_POST['gdsr_grs_format']; $gdsr_options["google_rich_snippets_location"] = $_POST['gdsr_grs_location']; $gdsr_options["google_rich_snippets_datasource"] = $_POST['gdsr_grs_datasource']; $gdsr_options["google_rich_snippets_active"] = isset($_POST['gdsr_grs']) ? 1 : 0; $gdsr_options["debug_wpquery"] = isset($_POST['gdsr_debug_wpquery']) ? 1 : 0; $gdsr_options["debug_active"] = isset($_POST['gdsr_debug_active']) ? 1 : 0; $gdsr_options["debug_inline"] = isset($_POST['gdsr_debug_inline']) ? 1 : 0; $gdsr_options["use_nonce"] = isset($_POST['gdsr_use_nonce']) ? 1 : 0; $gdsr_options["ajax_jsonp"] = isset($_POST['gdsr_ajax_jsonp']) ? 1 : 0; $gdsr_options["ip_filtering"] = isset($_POST['gdsr_ip_filtering']) ? 1 : 0; $gdsr_options["ip_filtering_restrictive"] = isset($_POST['gdsr_ip_filtering_restrictive']) ? 1 : 0; $gdsr_options["widget_articles"] = isset($_POST['gdsr_widget_articles']) ? 1 : 0; $gdsr_options["widget_top"] = isset($_POST['gdsr_widget_top']) ? 1 : 0; $gdsr_options["widget_comments"] = isset($_POST['gdsr_widget_comments']) ? 1 : 0; $gdsr_options["display_pages"] = isset($_POST['gdsr_pages']) ? 1 : 0; $gdsr_options["display_posts"] = isset($_POST['gdsr_posts']) ? 1 : 0; $gdsr_options["display_archive"] = isset($_POST['gdsr_archive']) ? 1 : 0; $gdsr_options["display_home"] = isset($_POST['gdsr_home']) ? 1 : 0; $gdsr_options["display_search"] = isset($_POST['gdsr_search']) ? 1 : 0; $gdsr_options["display_comment"] = isset($_POST['gdsr_dispcomment']) ? 1 : 0; $gdsr_options["display_comment_page"] = isset($_POST['gdsr_dispcomment_pages']) ? 1 : 0; $gdsr_options["moderation_active"] = isset($_POST['gdsr_modactive']) ? 1 : 0; $gdsr_options["multis_active"] = isset($_POST['gdsr_multis']) ? 1 : 0; $gdsr_options["timer_active"] = isset($_POST['gdsr_timer']) ? 1 : 0; $gdsr_options["rss_active"] = isset($_POST['gdsr_rss']) ? 1 : 0; $gdsr_options["save_user_agent"] = isset($_POST['gdsr_save_user_agent']) ? 1 : 0; $gdsr_options["save_cookies"] = isset($_POST['gdsr_save_cookies']) ? 1 : 0; $gdsr_options["ie_opacity_fix"] = isset($_POST['gdsr_ieopacityfix']) ? 1 : 0; $gdsr_options["override_display_comment"] = isset($_POST['gdsr_override_display_comment']) ? 1 : 0; $gdsr_options["override_thumb_display_comment"] = isset($_POST['gdsr_override_thumb_display_comment']) ? 1 : 0; $gdsr_options["integrate_dashboard"] = isset($_POST['gdsr_integrate_dashboard']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest"] = isset($_POST['gdsr_integrate_dashboard_latest']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_thumb_std"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_thumb_std']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_thumb_cmm"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_thumb_cmm']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_std"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_std']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_cmm"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_cmm']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_mur"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_mur']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_count"] = $_POST['gdsr_integrate_dashboard_latest_count']; $gdsr_options["integrate_post_edit"] = isset($_POST['gdsr_integrate_post_edit']) ? 1 : 0; $gdsr_options["integrate_post_edit_mur"] = isset($_POST['gdsr_integrate_post_edit_mur']) ? 1 : 0; $gdsr_options["integrate_tinymce"] = isset($_POST['gdsr_integrate_tinymce']) ? 1 : 0; $gdsr_options["integrate_rss_powered"] = isset($_POST['gdsr_integrate_rss_powered']) ? 1 : 0; $gdsr_options["trend_last"] = $_POST['gdsr_trend_last']; $gdsr_options["trend_over"] = $_POST['gdsr_trend_over']; $gdsr_options["bayesian_minimal"] = $_POST['gdsr_bayesian_minimal']; $gdsr_options["bayesian_mean"] = $_POST['gdsr_bayesian_mean']; $gdsr_options["auto_display_position"] = $_POST['gdsr_auto_display_position']; $gdsr_options["auto_display_comment_position"] = $_POST['gdsr_auto_display_comment_position']; $gdsr_options["default_timer_type"] = isset($_POST['gdsr_default_timer_type']) ? $_POST['gdsr_default_timer_type'] : "N"; $gdsr_options["default_timer_countdown_value"] = isset($_POST['gdsr_default_timer_countdown_value']) ? $_POST['gdsr_default_timer_countdown_value'] : 30; $gdsr_options["default_timer_countdown_type"] = isset($_POST['gdsr_default_timer_countdown_type']) ? $_POST['gdsr_default_timer_countdown_type'] : "D"; $gdsr_options["default_timer_value"] = $gdsr_options["default_timer_countdown_type"].$gdsr_options["default_timer_countdown_value"]; $gdsr_options["default_mur_timer_type"] = isset($_POST['gdsr_default_mur_timer_type']) ? $_POST['gdsr_default_mur_timer_type'] : "N"; $gdsr_options["default_mur_timer_countdown_value"] = isset($_POST['gdsr_default_mur_timer_countdown_value']) ? $_POST['gdsr_default_mur_timer_countdown_value'] : 30; $gdsr_options["default_mur_timer_countdown_type"] = isset($_POST['gdsr_default_mur_timer_countdown_type']) ? $_POST['gdsr_default_mur_timer_countdown_type'] : "D"; $gdsr_options["default_mur_timer_value"] = $gdsr_options["default_mur_timer_countdown_type"].$gdsr_options["default_mur_timer_countdown_value"]; $gdsr_options["review_active"] = isset($_POST['gdsr_reviewactive']) ? 1 : 0; $gdsr_options["comments_active"] = isset($_POST['gdsr_commentsactive']) ? 1 : 0; $gdsr_options["comments_review_active"] = isset($_POST['gdsr_cmmreviewactive']) ? 1 : 0; $gdsr_options["hide_empty_rating"] = isset($_POST['gdsr_haderating']) ? 1 : 0; $gdsr_options["cookies"] = isset($_POST['gdsr_cookies']) ? 1 : 0; $gdsr_options["cmm_cookies"] = isset($_POST['gdsr_cmm_cookies']) ? 1 : 0; $gdsr_options["author_vote"] = isset($_POST['gdsr_authorvote']) ? 1 : 0; $gdsr_options["cmm_author_vote"] = isset($_POST['gdsr_cmm_authorvote']) ? 1 : 0; $gdsr_options["logged"] = isset($_POST['gdsr_logged']) ? 1 : 0; $gdsr_options["cmm_logged"] = isset($_POST['gdsr_cmm_logged']) ? 1 : 0; $gdsr_options["rss_datasource"] = $_POST['gdsr_rss_datasource']; $gdsr_options["rss_style"] = $_POST['gdsr_rss_style']; $gdsr_options["rss_size"] = $_POST['gdsr_rss_size']; $gdsr_options["thumb_rss_style"] = $_POST['gdsr_thumb_rss_style']; $gdsr_options["thumb_rss_size"] = $_POST['gdsr_thumb_rss_size']; $gdsr_options["rss_header_text"] = stripslashes(htmlentities($_POST['gdsr_rss_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["style"] = $_POST['gdsr_style']; $gdsr_options["style_ie6"] = $_POST['gdsr_style_ie6']; $gdsr_options["size"] = $_POST['gdsr_size']; $gdsr_options["header_text"] = stripslashes(htmlentities($_POST['gdsr_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["thumb_style"] = $_POST['gdsr_thumb_style']; $gdsr_options["thumb_style_ie6"] = $_POST['gdsr_thumb_style_ie6']; $gdsr_options["thumb_size"] = $_POST['gdsr_thumb_size']; $gdsr_options["thumb_header_text"] = stripslashes(htmlentities($_POST['gdsr_thumb_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["thumb_cmm_style"] = $_POST['gdsr_thumb_cmm_style']; $gdsr_options["thumb_cmm_style_ie6"] = $_POST['gdsr_thumb_cmm_style_ie6']; $gdsr_options["thumb_cmm_size"] = $_POST['gdsr_thumb_cmm_size']; $gdsr_options["thumb_cmm_header_text"] = stripslashes(htmlentities($_POST['gdsr_thumb_cmm_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["default_srb_template"] = $_POST['gdsr_default_srb_template']; $gdsr_options["default_crb_template"] = $_POST['gdsr_default_crb_template']; $gdsr_options["default_ssb_template"] = $_POST['gdsr_default_ssb_template']; $gdsr_options["default_mrb_template"] = $_POST['gdsr_default_mrb_template']; $gdsr_options["default_tab_template"] = $_POST['gdsr_default_tab_template']; $gdsr_options["default_tcb_template"] = $_POST['gdsr_default_tcb_template']; $gdsr_options["srb_class_block"] = $_POST['gdsr_classblock']; $gdsr_options["srb_class_text"] = $_POST['gdsr_classtext']; $gdsr_options["srb_class_header"] = $_POST['gdsr_classheader']; $gdsr_options["srb_class_stars"] = $_POST['gdsr_classstars']; $gdsr_options["cmm_class_block"] = $_POST['gdsr_cmm_classblock']; $gdsr_options["cmm_class_text"] = $_POST['gdsr_cmm_classtext']; $gdsr_options["cmm_class_header"] = $_POST['gdsr_cmm_classheader']; $gdsr_options["cmm_class_stars"] = $_POST['gdsr_cmm_classstars']; $gdsr_options["mur_style"] = $_POST['gdsr_mur_style']; $gdsr_options["mur_style_ie6"] = $_POST['gdsr_mur_style_ie6']; $gdsr_options["mur_size"] = $_POST['gdsr_mur_size']; $gdsr_options["mur_header_text"] = stripslashes(htmlentities($_POST['gdsr_mur_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["mur_class_block"] = $_POST['gdsr_mur_classblock']; $gdsr_options["mur_class_text"] = $_POST['gdsr_mur_classtext']; $gdsr_options["mur_class_header"] = $_POST['gdsr_mur_classheader']; $gdsr_options["mur_class_button"] = $_POST['gdsr_mur_classbutton']; $gdsr_options["mur_button_text"] = $_POST['gdsr_mur_submittext']; $gdsr_options["mur_button_active"] = isset($_POST['gdsr_mur_submitactive']) ? 1 : 0; $gdsr_options["cmm_aggr_style"] = $_POST['gdsr_cmm_aggr_style']; $gdsr_options["cmm_aggr_style_ie6"] = $_POST['gdsr_cmm_aggr_style_ie6']; $gdsr_options["cmm_aggr_size"] = $_POST['gdsr_cmm_aggr_size']; $gdsr_options["cmm_style"] = $_POST['gdsr_cmm_style']; $gdsr_options["cmm_style_ie6"] = $_POST['gdsr_cmm_style_ie6']; $gdsr_options["cmm_size"] = $_POST['gdsr_cmm_size']; $gdsr_options["cmm_header_text"] = stripslashes(htmlentities($_POST['gdsr_cmm_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["review_style"] = $_POST['gdsr_review_style']; $gdsr_options["review_style_ie6"] = $_POST['gdsr_review_style_ie6']; $gdsr_options["review_size"] = $_POST['gdsr_review_size']; $gdsr_options["review_stars"] = $_POST['gdsr_review_stars']; $gdsr_options["review_header_text"] = stripslashes(htmlentities($_POST['gdsr_review_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["review_class_block"] = $_POST['gdsr_review_classblock']; $gdsr_options["cmm_review_style"] = isset($_POST['gdsr_cmm_review_style']) ? $_POST['gdsr_cmm_review_style'] : "oxyen"; $gdsr_options["cmm_review_style_ie6"] = isset($_POST['gdsr_cmm_review_style_ie6']) ? $_POST['gdsr_cmm_review_style_ie6'] : "oxyen_gif"; $gdsr_options["cmm_review_size"] = isset($_POST['gdsr_cmm_review_size']) ? $_POST['gdsr_cmm_review_size'] : 20; $gdsr_options["default_voterules_multis"] = $_POST['gdsr_default_vote_multis']; $gdsr_options["default_voterules_articles"] = $_POST['gdsr_default_vote_articles']; $gdsr_options["default_voterules_comments"] = $_POST['gdsr_default_vote_comments']; $gdsr_options["recc_default_voterules_articles"] = $_POST['gdsr_recc_default_vote_articles']; $gdsr_options["recc_default_voterules_comments"] = $_POST['gdsr_recc_default_vote_comments']; $gdsr_options["default_moderation_multis"] = isset($_POST['gdsr_default_mod_multis']) ? $_POST['gdsr_default_mod_multis'] : ""; $gdsr_options["default_moderation_articles"] = isset($_POST['gdsr_default_mod_articles']) ? $_POST['gdsr_default_mod_articles'] : ""; $gdsr_options["default_moderation_comments"] = isset($_POST['gdsr_default_mod_comments']) ? $_POST['gdsr_default_mod_comments'] : ""; $gdsr_options["recc_default_moderation_articles"] = isset($_POST['gdsr_recc_default_mod_articles']) ? $_POST['gdsr_recc_default_mod_articles'] : ""; $gdsr_options["recc_default_moderation_comments"] = isset($_POST['gdsr_recc_default_mod_comments']) ? $_POST['gdsr_recc_default_mod_comments'] : ""; $gdsr_options["thumb_display_pages"] = isset($_POST['gdsr_thumb_pages']) ? 1 : 0; $gdsr_options["thumb_display_posts"] = isset($_POST['gdsr_thumb_posts']) ? 1 : 0; $gdsr_options["thumb_display_archive"] = isset($_POST['gdsr_thumb_archive']) ? 1 : 0; $gdsr_options["thumb_display_home"] = isset($_POST['gdsr_thumb_home']) ? 1 : 0; $gdsr_options["thumb_display_search"] = isset($_POST['gdsr_thumb_search']) ? 1 : 0; $gdsr_options["thumb_display_comment"] = isset($_POST['gdsr_thumb_dispcomment']) ? 1 : 0; $gdsr_options["thumb_display_comment_page"] = isset($_POST['gdsr_thumb_dispcomment_pages']) ? 1 : 0; $gdsr_options["thumb_auto_display_position"] = $_POST['gdsr_thumb_auto_display_position']; $gdsr_options["thumb_auto_display_comment_position"] = $_POST['gdsr_thumb_auto_display_comment_position']; $gdsr_options["css_last_changed"] = time(); update_option("gd-star-rating", $gdsr_options); $bots = explode("\r\n", $_POST["gdsr_bots"]); foreach($bots as $key => $value) { if(trim($value) == "") { unset($bots[$key]); } } $bots = array_values($bots); update_option("gd-star-rating-bots", $bots); } ?>
imshashank/The-Perfect-Self
wp-content/plugins/gd-star-rating/code/adm/save_settings.php
PHP
gpl-2.0
18,252
<?php require_once('../conexiones/conexione.php'); mysql_select_db($base_datos, $conectar); date_default_timezone_set("America/Bogota"); include ("../registro_movimientos/registro_movimientos.php"); //$cod_factura = $_GET['cod_factura']; $fecha_ini = $_GET['fecha_ini']; $fecha_fin = $_GET['fecha_fin']; $tabla = $_GET['tabla']; $tipo = $_GET['tipo']; $fecha = date("Y/m/d"); $hora = date("H:i:s"); $salida = ""; $nombre = $tabla.'_'.$fecha.'_Hora_'.$hora.'-'.$tipo.'-'.$fecha_ini.'-'.$fecha_fin.'.csv'; $sql = mysql_query("SELECT * FROM $tabla WHERE fecha_anyo BETWEEN '$fecha_ini' AND '$fecha_fin'"); $total_columnas = mysql_num_fields($sql); // Obtener El Nombre de Campo /* for ($i = 0; $i < $total_columnas; $i++) { $encabezado = mysql_field_name($sql, $i); $salida .= '"'.$encabezado.'",'; } $salida .="\n"; */ // Obtener los Registros de la tabla while ($datos = mysql_fetch_array($sql)) { for ($i = 0; $i < $total_columnas; $i++) { $salida .=''.$datos["$i"].','; //$salida .='"'.$datos["$i"].'",'; } $salida .="\n"; } // DESCARGAR ARCHIVO header('Content-type: application/csv'); header('Content-Disposition: attachment; filename='.$nombre); echo $salida; exit; ?>
dataxe/proyectos
panashopping/admin/descargar_factura_externa_temporal_archivo_csv_por_dias.php
PHP
gpl-3.0
1,184
package com.laytonsmith.abstraction; import com.laytonsmith.abstraction.enums.MCDisplaySlot; import java.util.Set; public interface MCScoreboard { public void clearSlot(MCDisplaySlot slot); public MCObjective getObjective(MCDisplaySlot slot); public MCObjective getObjective(String name); /** * * @return Set of all objectives on this scoreboard */ public Set<MCObjective> getObjectives(); public Set<MCObjective> getObjectivesByCriteria(String criteria); /** * * @return Set of all players tracked by this scoreboard */ public Set<String> getEntries(); public MCTeam getPlayerTeam(MCOfflinePlayer player); public Set<MCScore> getScores(String entry); public MCTeam getTeam(String teamName); public Set<MCTeam> getTeams(); public MCObjective registerNewObjective(String name, String criteria); public MCTeam registerNewTeam(String name); public void resetScores(String entry); }
Murreey/CommandHelper
src/main/java/com/laytonsmith/abstraction/MCScoreboard.java
Java
gpl-3.0
908
package cn.nukkit.block; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.level.sound.NoteBoxSound; import cn.nukkit.network.protocol.BlockEventPacket; /** * Created by Snake1999 on 2016/1/17. * Package cn.nukkit.block in project nukkit. */ public class BlockNoteblock extends BlockSolid { public BlockNoteblock() { this(0); } public BlockNoteblock(int meta) { super(meta); } @Override public String getName() { return "Note Block"; } @Override public int getId() { return NOTEBLOCK; } @Override public int getToolType() { return ItemTool.TYPE_AXE; } @Override public double getHardness() { return 0.8D; } @Override public double getResistance() { return 4D; } public boolean canBeActivated() { return true; } public int getStrength() { return this.meta; } public void increaseStrength() { if (this.meta < 24) { this.meta++; } else { this.meta = 0; } } public int getInstrument() { Block below = this.down(); switch (below.getId()) { case WOODEN_PLANK: case NOTEBLOCK: case CRAFTING_TABLE: return NoteBoxSound.INSTRUMENT_BASS; case SAND: case SANDSTONE: case SOUL_SAND: return NoteBoxSound.INSTRUMENT_TABOUR; case GLASS: case GLASS_PANEL: case GLOWSTONE_BLOCK: return NoteBoxSound.INSTRUMENT_CLICK; case COAL_ORE: case DIAMOND_ORE: case EMERALD_ORE: case GLOWING_REDSTONE_ORE: case GOLD_ORE: case IRON_ORE: case LAPIS_ORE: case REDSTONE_ORE: return NoteBoxSound.INSTRUMENT_BASS_DRUM; default: return NoteBoxSound.INSTRUMENT_PIANO; } } public void emitSound() { BlockEventPacket pk = new BlockEventPacket(); pk.x = (int) this.x; pk.y = (int) this.y; pk.z = (int) this.z; pk.case1 = this.getInstrument(); pk.case2 = this.getStrength(); this.getLevel().addChunkPacket((int) this.x >> 4, (int) this.z >> 4, pk); this.getLevel().addSound(new NoteBoxSound(this, this.getInstrument(), this.getStrength())); } public boolean onActivate(Item item) { return this.onActivate(item, null); } public boolean onActivate(Item item, Player player) { Block up = this.up(); if (up.getId() == Block.AIR) { this.increaseStrength(); this.emitSound(); return true; } else { return false; } } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) { //TODO: redstone } return 0; } }
yescallop/Nukkit
src/main/java/cn/nukkit/block/BlockNoteblock.java
Java
gpl-3.0
3,101
/* * Copyright (C) 2012 The Android Open Source Project * * 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.android.cts.verifier.p2p.testcase; import java.util.ArrayList; import java.util.List; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener; import android.util.Log; /** * The utility class for testing * android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener callback function. */ public class DnsSdResponseListenerTest extends ListenerTest implements DnsSdServiceResponseListener { private static final String TAG = "DnsSdResponseListenerTest"; public static final List<ListenerArgument> NO_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> ALL_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> IPP_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> AFP_DNS_PTR = new ArrayList<ListenerArgument>(); /** * The target device address. */ private String mTargetAddr; static { initialize(); } public DnsSdResponseListenerTest(String targetAddr) { mTargetAddr = targetAddr; } @Override public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice) { Log.d(TAG, instanceName + " " + registrationType + " received from " + srcDevice.deviceAddress); /* * Check only the response from the target device. * The response from other devices are ignored. */ if (srcDevice.deviceAddress.equalsIgnoreCase(mTargetAddr)) { receiveCallback(new Argument(instanceName, registrationType)); } } private static void initialize() { String ippInstanceName = "MyPrinter"; String ippRegistrationType = "_ipp._tcp.local."; String afpInstanceName = "Example"; String afpRegistrationType = "_afpovertcp._tcp.local."; IPP_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); AFP_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); ALL_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); ALL_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); } /** * The container of the argument of {@link #onDnsSdServiceAvailable}. */ static class Argument extends ListenerArgument { private String mInstanceName; private String mRegistrationType; /** * Set the argument of {@link #onDnsSdServiceAvailable}. * * @param instanceName instance name. * @param registrationType registration type. */ Argument(String instanceName, String registrationType) { mInstanceName = instanceName; mRegistrationType = registrationType; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Argument)) { return false; } Argument arg = (Argument)obj; return equals(mInstanceName, arg.mInstanceName) && equals(mRegistrationType, arg.mRegistrationType); } private boolean equals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[type=dns_ptr instant_name="); sb.append(mInstanceName); sb.append(" registration type="); sb.append(mRegistrationType); sb.append("\n"); return "instanceName=" + mInstanceName + " registrationType=" + mRegistrationType; } } }
s20121035/rk3288_android5.1_repo
cts/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/DnsSdResponseListenerTest.java
Java
gpl-3.0
4,616
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /* $Id: SqlTool.java,v 1.72 2007/06/29 12:23:47 unsaved Exp $ */ /** * Sql Tool. A command-line and/or interactive SQL tool. * (Note: For every Javadoc block comment, I'm using a single blank line * immediately after the description, just like's Sun's examples in * their Coding Conventions document). * * See JavaDocs for the main method for syntax of how to run. * This class is mostly used in a static (a.o.t. object) way, because most * of the work is done in the static main class. * This class should be refactored so that the main work is done in an * object method, and the static main invokes the object method. * Then programmatic users could use instances of this class in the normal * Java way. * * @see #main() * @version $Revision: 1.72 $ * @author Blaine Simpson unsaved@users */ public class SqlTool { private static final String DEFAULT_RCFILE = System.getProperty("user.home") + "/sqltool.rc"; // N.b. the following is static! private static String revnum = null; public static final int SQLTOOLERR_EXITVAL = 1; public static final int SYNTAXERR_EXITVAL = 11; public static final int RCERR_EXITVAL = 2; public static final int SQLERR_EXITVAL = 3; public static final int IOERR_EXITVAL = 4; public static final int FILEERR_EXITVAL = 5; public static final int INPUTERR_EXITVAL = 6; public static final int CONNECTERR_EXITVAL = 7; /** * The configuration identifier to use when connection parameters are * specified on the command line */ private static String CMDLINE_ID = "cmdline"; static private SqltoolRB rb = null; // Must use a shared static RB object, since we need to get messages // inside of static methods. // This means that the locale will be set the first time this class // is accessed. Subsequent calls will not update the RB if the locale // changes (could have it check and reload the RB if this becomes an // issue). static { revnum = "333"; try { rb = new SqltoolRB(); rb.validate(); rb.setMissingPosValueBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); rb.setMissingPropertyBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); } catch (RuntimeException re) { System.err.println("Failed to initialize resource bundle"); throw re; } } public static String LS = System.getProperty("line.separator"); /** Utility nested class for internal use. */ private static class BadCmdline extends Exception { static final long serialVersionUID = -2134764796788108325L; BadCmdline() {} } /** Utility object for internal use. */ private static BadCmdline bcl = new BadCmdline(); /** For trapping of exceptions inside this class. * These are always handled inside this class. */ private static class PrivateException extends Exception { static final long serialVersionUID = -7765061479594523462L; PrivateException() { super(); } PrivateException(String s) { super(s); } } public static class SqlToolException extends Exception { static final long serialVersionUID = 1424909871915188519L; int exitValue = 1; SqlToolException(String message, int exitValue) { super(message); this.exitValue = exitValue; } SqlToolException(int exitValue, String message) { this(message, exitValue); } SqlToolException(int exitValue) { super(); this.exitValue = exitValue; } } /** * Prompt the user for a password. * * @param username The user the password is for * @return The password the user entered */ private static String promptForPassword(String username) throws PrivateException { BufferedReader console; String password; password = null; try { console = new BufferedReader(new InputStreamReader(System.in)); // Prompt for password System.out.print(rb.getString(SqltoolRB.PASSWORDFOR_PROMPT, RCData.expandSysPropVars(username))); // Read the password from the command line password = console.readLine(); if (password == null) { password = ""; } else { password = password.trim(); } } catch (IOException e) { throw new PrivateException(e.getMessage()); } return password; } /** * Parses a comma delimited string of name value pairs into a * <code>Map</code> object. * * @param varString The string to parse * @param varMap The map to save the paired values into * @param lowerCaseKeys Set to <code>true</code> if the map keys should be * converted to lower case */ private static void varParser(String varString, Map varMap, boolean lowerCaseKeys) throws PrivateException { int equals; String var; String val; String[] allvars; if ((varMap == null) || (varString == null)) { throw new IllegalArgumentException( "varMap or varString are null in SqlTool.varParser call"); } allvars = varString.split("\\s*,\\s*"); for (int i = 0; i < allvars.length; i++) { equals = allvars[i].indexOf('='); if (equals < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } var = allvars[i].substring(0, equals).trim(); val = allvars[i].substring(equals + 1).trim(); if (var.length() < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } if (lowerCaseKeys) { var = var.toLowerCase(); } varMap.put(var, val); } } /** * A static wrapper for objectMain, so that that method may be executed * as a Java "program". * * Throws only RuntimExceptions or Errors, because this method is intended * to System.exit() for all but disasterous system problems, for which * the inconvenience of a a stack trace would be the least of your worries. * * If you don't want SqlTool to System.exit(), then use the method * objectMain() instead of this method. * * @see objectMain(String[]) */ public static void main(String[] args) { try { SqlTool.objectMain(args); } catch (SqlToolException fr) { if (fr.getMessage() != null) { System.err.println(fr.getMessage()); } System.exit(fr.exitValue); } System.exit(0); } /** * Connect to a JDBC Database and execute the commands given on * stdin or in SQL file(s). * * This method is changed for HSQLDB 1.8.0.8 and 1.9.0.x to never * System.exit(). * * @param arg Run "java... org.hsqldb.util.SqlTool --help" for syntax. * @throws SqlToolException Upon any fatal error, with useful * reason as the exception's message. */ static public void objectMain(String[] arg) throws SqlToolException { /* * The big picture is, we parse input args; load a RCData; * get a JDBC Connection with the RCData; instantiate and * execute as many SqlFiles as we need to. */ String rcFile = null; File tmpFile = null; String sqlText = null; String driver = null; String targetDb = null; String varSettings = null; boolean debug = false; File[] scriptFiles = null; int i = -1; boolean listMode = false; boolean interactive = false; boolean noinput = false; boolean noautoFile = false; boolean autoCommit = false; Boolean coeOverride = null; Boolean stdinputOverride = null; String rcParams = null; String rcUrl = null; String rcUsername = null; String rcPassword = null; String rcCharset = null; String rcTruststore = null; Map rcFields = null; String parameter; try { while ((i + 1 < arg.length) && arg[i + 1].startsWith("--")) { i++; if (arg[i].length() == 2) { break; // "--" } parameter = arg[i].substring(2).toLowerCase(); if (parameter.equals("help")) { System.out.println(rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); return; } if (parameter.equals("abortonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.FALSE; } else if (parameter.equals("continueonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.TRUE; } else if (parameter.equals("list")) { listMode = true; } else if (parameter.equals("rcfile")) { if (++i == arg.length) { throw bcl; } rcFile = arg[i]; } else if (parameter.equals("setvar")) { if (++i == arg.length) { throw bcl; } varSettings = arg[i]; } else if (parameter.equals("sql")) { noinput = true; // but turn back on if file "-" specd. if (++i == arg.length) { throw bcl; } sqlText = arg[i]; } else if (parameter.equals("debug")) { debug = true; } else if (parameter.equals("noautofile")) { noautoFile = true; } else if (parameter.equals("autocommit")) { autoCommit = true; } else if (parameter.equals("stdinput")) { noinput = false; stdinputOverride = Boolean.TRUE; } else if (parameter.equals("noinput")) { noinput = true; stdinputOverride = Boolean.FALSE; } else if (parameter.equals("driver")) { if (++i == arg.length) { throw bcl; } driver = arg[i]; } else if (parameter.equals("inlinerc")) { if (++i == arg.length) { throw bcl; } rcParams = arg[i]; } else { throw bcl; } } if (!listMode) { // If an inline RC file was specified, don't worry about the targetDb if (rcParams == null) { if (++i == arg.length) { throw bcl; } targetDb = arg[i]; } } int scriptIndex = 0; if (sqlText != null) { try { tmpFile = File.createTempFile("sqltool-", ".sql"); //(new java.io.FileWriter(tmpFile)).write(sqlText); java.io.FileWriter fw = new java.io.FileWriter(tmpFile); try { fw.write("/* " + (new java.util.Date()) + ". " + SqlTool.class.getName() + " command-line SQL. */" + LS + LS); fw.write(sqlText + LS); fw.flush(); } finally { fw.close(); } } catch (IOException ioe) { throw new SqlToolException(IOERR_EXITVAL, rb.getString(SqltoolRB.SQLTEMPFILE_FAIL, ioe.toString())); } } if (stdinputOverride != null) { noinput = !stdinputOverride.booleanValue(); } interactive = (!noinput) && (arg.length <= i + 1); if (arg.length == i + 2 && arg[i + 1].equals("-")) { if (stdinputOverride == null) { noinput = false; } } else if (arg.length > i + 1) { // I.e., if there are any SQL files specified. scriptFiles = new File[arg.length - i - 1 + ((stdinputOverride == null ||!stdinputOverride.booleanValue()) ? 0 : 1)]; if (debug) { System.err.println("scriptFiles has " + scriptFiles.length + " elements"); } while (i + 1 < arg.length) { scriptFiles[scriptIndex++] = new File(arg[++i]); } if (stdinputOverride != null && stdinputOverride.booleanValue()) { scriptFiles[scriptIndex++] = null; noinput = true; } } } catch (BadCmdline bcl) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); } RCData conData = null; // Use the inline RC file if it was specified if (rcParams != null) { rcFields = new HashMap(); try { varParser(rcParams, rcFields, true); } catch (PrivateException e) { throw new SqlToolException(SYNTAXERR_EXITVAL, e.getMessage()); } rcUrl = (String) rcFields.remove("url"); rcUsername = (String) rcFields.remove("user"); rcCharset = (String) rcFields.remove("charset"); rcTruststore = (String) rcFields.remove("truststore"); rcPassword = (String) rcFields.remove("password"); // Don't ask for password if what we have already is invalid! if (rcUrl == null || rcUrl.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEURL_MISSING)); if (rcUsername == null || rcUsername.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEUSERNAME_MISSING)); if (rcPassword != null && rcPassword.length() > 0) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_PASSWORD_VISIBLE)); if (rcFields.size() > 0) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.RCDATA_INLINE_EXTRAVARS, rcFields.keySet().toString())); } if (rcPassword == null) try { rcPassword = promptForPassword(rcUsername); } catch (PrivateException e) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.PASSWORD_READFAIL, e.getMessage())); } try { conData = new RCData(CMDLINE_ID, rcUrl, rcUsername, rcPassword, driver, rcCharset, rcTruststore); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_GENFROMVALUES_FAIL, e.getMessage())); } } else { try { conData = new RCData(new File((rcFile == null) ? DEFAULT_RCFILE : rcFile), targetDb); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.CONNDATA_RETRIEVAL_FAIL, targetDb, e.getMessage())); } } if (listMode) { return; } if (debug) { conData.report(); } Connection conn = null; try { conn = conData.getConnection( driver, System.getProperty("sqlfile.charset"), System.getProperty("javax.net.ssl.trustStore")); conn.setAutoCommit(autoCommit); DatabaseMetaData md = null; if (interactive && (md = conn.getMetaData()) != null) { System.out.println( rb.getString(SqltoolRB.JDBC_ESTABLISHED, md.getDatabaseProductName(), md.getDatabaseProductVersion(), md.getUserName())); } } catch (Exception e) { //e.printStackTrace(); // Let's not continue as if nothing is wrong. throw new SqlToolException(CONNECTERR_EXITVAL, rb.getString(SqltoolRB.CONNECTION_FAIL, conData.url, conData.username, e.getMessage())); } File[] emptyFileArray = {}; File[] singleNullFileArray = { null }; File autoFile = null; if (interactive &&!noautoFile) { autoFile = new File(System.getProperty("user.home") + "/auto.sql"); if ((!autoFile.isFile()) ||!autoFile.canRead()) { autoFile = null; } } if (scriptFiles == null) { // I.e., if no SQL files given on command-line. // Input file list is either nothing or {null} to read stdin. scriptFiles = (noinput ? emptyFileArray : singleNullFileArray); } int numFiles = scriptFiles.length; if (tmpFile != null) { numFiles += 1; } if (autoFile != null) { numFiles += 1; } SqlFile[] sqlFiles = new SqlFile[numFiles]; Map userVars = new HashMap(); if (varSettings != null) try { varParser(varSettings, userVars, false); } catch (PrivateException pe) { throw new SqlToolException(RCERR_EXITVAL, pe.getMessage()); } // We print version before execing this one. int interactiveFileIndex = -1; try { int fileIndex = 0; if (autoFile != null) { sqlFiles[fileIndex++] = new SqlFile(autoFile, false, userVars); } if (tmpFile != null) { sqlFiles[fileIndex++] = new SqlFile(tmpFile, false, userVars); } for (int j = 0; j < scriptFiles.length; j++) { if (interactiveFileIndex < 0 && interactive) { interactiveFileIndex = fileIndex; } sqlFiles[fileIndex++] = new SqlFile(scriptFiles[j], interactive, userVars); } } catch (IOException ioe) { try { conn.close(); } catch (Exception e) {} throw new SqlToolException(FILEERR_EXITVAL, ioe.getMessage()); } try { for (int j = 0; j < sqlFiles.length; j++) { if (j == interactiveFileIndex) { System.out.print("SqlTool v. " + revnum + ". "); } sqlFiles[j].execute(conn, coeOverride); } // Following two Exception types are handled properly inside of // SqlFile. We just need to return an appropriate error status. } catch (SqlToolError ste) { throw new SqlToolException(SQLTOOLERR_EXITVAL); } catch (SQLException se) { // SqlTool will only throw an SQLException if it is in // "\c false" mode. throw new SqlToolException(SQLERR_EXITVAL); } finally { try { conn.close(); } catch (Exception e) {} } // Taking file removal out of final block because this is good debug // info to keep around if the program aborts. if (tmpFile != null && !tmpFile.delete()) { System.err.println(conData.url + rb.getString( SqltoolRB.TEMPFILE_REMOVAL_FAIL, tmpFile.toString())); } } }
danielbejaranogonzalez/Mobile-Network-Designer
db/hsqldb/src/org/hsqldb/util/SqlTool.java
Java
gpl-3.0
23,912
<?php namespace Drupal\language\Form; use Drupal\Core\Block\BlockManagerInterface; use Drupal\Component\Utility\Unicode; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Extension\ThemeHandlerInterface; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Url; use Drupal\language\ConfigurableLanguageManagerInterface; use Drupal\language\LanguageNegotiatorInterface; use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Configure the selected language negotiation method for this site. */ class NegotiationConfigureForm extends ConfigFormBase { /** * Stores the configuration object for language.types. * * @var \Drupal\Core\Config\Config */ protected $languageTypes; /** * The language manager. * * @var \Drupal\language\ConfigurableLanguageManagerInterface */ protected $languageManager; /** * The language negotiator. * * @var \Drupal\language\LanguageNegotiatorInterface */ protected $negotiator; /** * The block manager. * * @var \Drupal\Core\Block\BlockManagerInterface */ protected $blockManager; /** * The block storage. * * @var \Drupal\Core\Entity\EntityStorageInterface|null */ protected $blockStorage; /** * The theme handler. * * @var \Drupal\Core\Extension\ThemeHandlerInterface */ protected $themeHandler; /** * Constructs a NegotiationConfigureForm object. * * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * The factory for configuration objects. * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager * The language manager. * @param \Drupal\language\LanguageNegotiatorInterface $negotiator * The language negotiation methods manager. * @param \Drupal\Core\Block\BlockManagerInterface $block_manager * The block manager. * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler * The theme handler. * @param \Drupal\Core\Entity\EntityStorageInterface $block_storage * The block storage, or NULL if not available. */ public function __construct(ConfigFactoryInterface $config_factory, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, BlockManagerInterface $block_manager, ThemeHandlerInterface $theme_handler, EntityStorageInterface $block_storage = NULL) { parent::__construct($config_factory); $this->languageTypes = $this->config('language.types'); $this->languageManager = $language_manager; $this->negotiator = $negotiator; $this->blockManager = $block_manager; $this->themeHandler = $theme_handler; $this->blockStorage = $block_storage; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { $entity_manager = $container->get('entity.manager'); $block_storage = $entity_manager->hasHandler('block', 'storage') ? $entity_manager->getStorage('block') : NULL; return new static( $container->get('config.factory'), $container->get('language_manager'), $container->get('language_negotiator'), $container->get('plugin.manager.block'), $container->get('theme_handler'), $block_storage ); } /** * {@inheritdoc} */ public function getFormId() { return 'language_negotiation_configure_form'; } /** * {@inheritdoc} */ protected function getEditableConfigNames() { return ['language.types']; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $configurable = $this->languageTypes->get('configurable'); $form = [ '#theme' => 'language_negotiation_configure_form', '#language_types_info' => $this->languageManager->getDefinedLanguageTypesInfo(), '#language_negotiation_info' => $this->negotiator->getNegotiationMethods(), ]; $form['#language_types'] = []; foreach ($form['#language_types_info'] as $type => $info) { // Show locked language types only if they are configurable. if (empty($info['locked']) || in_array($type, $configurable)) { $form['#language_types'][] = $type; } } foreach ($form['#language_types'] as $type) { $this->configureFormTable($form, $type); } $form['actions'] = ['#type' => 'actions']; $form['actions']['submit'] = [ '#type' => 'submit', '#button_type' => 'primary', '#value' => $this->t('Save settings'), ]; return $form; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $configurable_types = $form['#language_types']; $stored_values = $this->languageTypes->get('configurable'); $customized = []; $method_weights_type = []; foreach ($configurable_types as $type) { $customized[$type] = in_array($type, $stored_values); $method_weights = []; $enabled_methods = $form_state->getValue([$type, 'enabled']); $enabled_methods[LanguageNegotiationSelected::METHOD_ID] = TRUE; $method_weights_input = $form_state->getValue([$type, 'weight']); if ($form_state->hasValue([$type, 'configurable'])) { $customized[$type] = !$form_state->isValueEmpty([$type, 'configurable']); } foreach ($method_weights_input as $method_id => $weight) { if ($enabled_methods[$method_id]) { $method_weights[$method_id] = $weight; } } $method_weights_type[$type] = $method_weights; $this->languageTypes->set('negotiation.' . $type . '.method_weights', $method_weights_input)->save(); } // Update non-configurable language types and the related language // negotiation configuration. $this->negotiator->updateConfiguration(array_keys(array_filter($customized))); // Update the language negotiations after setting the configurability. foreach ($method_weights_type as $type => $method_weights) { $this->negotiator->saveConfiguration($type, $method_weights); } // Clear block definitions cache since the available blocks and their names // may have been changed based on the configurable types. if ($this->blockStorage) { // If there is an active language switcher for a language type that has // been made not configurable, deactivate it first. $non_configurable = array_keys(array_diff($customized, array_filter($customized))); $this->disableLanguageSwitcher($non_configurable); } $this->blockManager->clearCachedDefinitions(); $form_state->setRedirect('language.negotiation'); drupal_set_message($this->t('Language detection configuration saved.')); } /** * Builds a language negotiation method configuration table. * * @param array $form * The language negotiation configuration form. * @param string $type * The language type to generate the table for. */ protected function configureFormTable(array &$form, $type) { $info = $form['#language_types_info'][$type]; $table_form = [ '#title' => $this->t('@type language detection', ['@type' => $info['name']]), '#tree' => TRUE, '#description' => $info['description'], '#language_negotiation_info' => [], '#show_operations' => FALSE, 'weight' => ['#tree' => TRUE], ]; // Only show configurability checkbox for the unlocked language types. if (empty($info['locked'])) { $configurable = $this->languageTypes->get('configurable'); $table_form['configurable'] = [ '#type' => 'checkbox', '#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', ['%language_name' => $info['name']]), '#default_value' => in_array($type, $configurable), '#attributes' => ['class' => ['language-customization-checkbox']], '#attached' => [ 'library' => [ 'language/drupal.language.admin' ], ], ]; } $negotiation_info = $form['#language_negotiation_info']; $enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: []; $methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: []; // Add missing data to the methods lists. foreach ($negotiation_info as $method_id => $method) { if (!isset($methods_weight[$method_id])) { $methods_weight[$method_id] = isset($method['weight']) ? $method['weight'] : 0; } } // Order methods list by weight. asort($methods_weight); foreach ($methods_weight as $method_id => $weight) { // A language method might be no more available if the defining module has // been disabled after the last configuration saving. if (!isset($negotiation_info[$method_id])) { continue; } $enabled = isset($enabled_methods[$method_id]); $method = $negotiation_info[$method_id]; // List the method only if the current type is defined in its 'types' key. // If it is not defined default to all the configurable language types. $types = array_flip(isset($method['types']) ? $method['types'] : $form['#language_types']); if (isset($types[$type])) { $table_form['#language_negotiation_info'][$method_id] = $method; $method_name = $method['name']; $table_form['weight'][$method_id] = [ '#type' => 'weight', '#title' => $this->t('Weight for @title language detection method', ['@title' => Unicode::strtolower($method_name)]), '#title_display' => 'invisible', '#default_value' => $weight, '#attributes' => ['class' => ["language-method-weight-$type"]], '#delta' => 20, ]; $table_form['title'][$method_id] = ['#plain_text' => $method_name]; $table_form['enabled'][$method_id] = [ '#type' => 'checkbox', '#title' => $this->t('Enable @title language detection method', ['@title' => Unicode::strtolower($method_name)]), '#title_display' => 'invisible', '#default_value' => $enabled, ]; if ($method_id === LanguageNegotiationSelected::METHOD_ID) { $table_form['enabled'][$method_id]['#default_value'] = TRUE; $table_form['enabled'][$method_id]['#attributes'] = ['disabled' => 'disabled']; } $table_form['description'][$method_id] = ['#markup' => $method['description']]; $config_op = []; if (isset($method['config_route_name'])) { $config_op['configure'] = [ 'title' => $this->t('Configure'), 'url' => Url::fromRoute($method['config_route_name']), ]; // If there is at least one operation enabled show the operation // column. $table_form['#show_operations'] = TRUE; } $table_form['operation'][$method_id] = [ '#type' => 'operations', '#links' => $config_op, ]; } } $form[$type] = $table_form; } /** * Disables the language switcher blocks. * * @param array $language_types * An array containing all language types whose language switchers need to * be disabled. */ protected function disableLanguageSwitcher(array $language_types) { $theme = $this->themeHandler->getDefault(); $blocks = $this->blockStorage->loadByProperties(['theme' => $theme]); foreach ($language_types as $language_type) { foreach ($blocks as $block) { if ($block->getPluginId() == 'language_block:' . $language_type) { $block->delete(); } } } } }
oeru/techblog
drupal8/core/modules/language/src/Form/NegotiationConfigureForm.php
PHP
gpl-3.0
11,818
<?php class Appconfig extends CI_Model { public function exists($key) { $this->db->from('app_config'); $this->db->where('app_config.key', $key); return ($this->db->get()->num_rows() == 1); } public function get_all() { $this->db->from('app_config'); $this->db->order_by('key', 'asc'); return $this->db->get(); } public function get($key) { $query = $this->db->get_where('app_config', array('key' => $key), 1); if($query->num_rows() == 1) { return $query->row()->value; } return ''; } public function save($key, $value) { $config_data = array( 'key' => $key, 'value' => $value ); if(!$this->exists($key)) { return $this->db->insert('app_config', $config_data); } $this->db->where('key', $key); return $this->db->update('app_config', $config_data); } public function batch_save($data) { $success = TRUE; //Run these queries as a transaction, we want to make sure we do all or nothing $this->db->trans_start(); foreach($data as $key=>$value) { $success &= $this->save($key, $value); } $this->db->trans_complete(); $success &= $this->db->trans_status(); return $success; } public function delete($key) { return $this->db->delete('app_config', array('key' => $key)); } public function delete_all() { return $this->db->empty_table('app_config'); } } ?>
digyna/digyna-CMS
application/models/mypanel/Appconfig.php
PHP
gpl-3.0
1,375
/* sdsl - succinct data structures library Copyright (C) 2010 Simon Gog This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ . */ /*! \file algorithms_for_string_matching.hpp \brief algorithms_for_string_matching.hpp contains algorithms for string matching like backward_search, ... \author Simon Gog */ #ifndef INCLUDED_SDSL_ALGORITHMS_FOR_STRING_MATCHING #define INCLUDED_SDSL_ALGORITHMS_FOR_STRING_MATCHING #include "int_vector.hpp" #include <stdexcept> // for exceptions #include <iostream> #include <cassert> #include <stack> #include <utility> namespace sdsl { /*! \author Simon Gog */ namespace algorithm { //! Backward search for a character c on an interval \f$[\ell..r]\f$ of the suffix array. /*! * \param csa The csa in which the backward_search should be done. * \param l Left border of the lcp-interval \f$ [\ell..r]\f$. * \param r Right border of the lcp-interval \f$ [\ell..r]\f$. * \param c The character c which is the starting character of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ . * \param l_res Reference to the resulting left border. * \param r_res Reference to the resulting right border. * \return The size of the new interval [\ell_{new}..r_{new}]. * \pre \f$ 0 \leq \ell \leq r < csa.size() \f$ * * \par Time complexity * \f$ \Order{ t_{rank\_bwt} } \f$ * \par References * Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000. */ template<class Csa> static typename Csa::csa_size_type backward_search( const Csa& csa, typename Csa::size_type l, typename Csa::size_type r, typename Csa::char_type c, typename Csa::size_type& l_res, typename Csa::size_type& r_res ) { assert(l <= r); assert(r < csa.size()); typename Csa::size_type c_begin = csa.C[csa.char2comp[c]]; l_res = c_begin + csa.rank_bwt(l, c); // count c in bwt[0..l-1] r_res = c_begin + csa.rank_bwt(r+1, c) - 1; // count c in bwt[0..r] assert(r_res+1-l_res >= 0); return r_res+1-l_res; } //! Backward search for a pattern pat on an interval \f$[\ell..r]\f$ of the suffix array. /*! * \param csa The csa in which the backward_search should be done. * \param l Left border of the lcp-interval \f$ [\ell..r]\f$. * \param r Right border of the lcp-interval \f$ [\ell..r]\f$. * \param pat The string which is the prefix of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ . * \param len The length of pat. * \param l_res Reference to the resulting left border. * \param r_res Reference to the resulting right border. * \return The size of the new interval [\ell_{new}..r_{new}]. * \pre \f$ 0 \leq \ell \leq r < csa.size() \f$ * * \par Time complexity * \f$ \Order{ len \cdot t_{rank\_bwt} } \f$ * \par References * Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000. */ template<class Csa> static typename Csa::csa_size_type backward_search(const Csa& csa, typename Csa::size_type l, typename Csa::size_type r, typename Csa::pattern_type pat, typename Csa::size_type len, typename Csa::size_type& l_res, typename Csa::size_type& r_res) { typename Csa::size_type i = 0; l_res = l; r_res = r; while (i < len and backward_search(csa, l_res, r_res, pat[len-i-1], l_res, r_res)) { ++i; } return r_res+1-l_res; } // TODO: forward search. Include original text??? //! Counts the number of occurences of pattern pat in the string of the compressed suffix array csa. /*! * \param csa The compressed suffix array. * \param pat The pattern for which we count the occurences in the string of the compressed suffix array. * \param len The length of the pattern. * \return The number of occurences of pattern pat in the string of the compressed suffix array. * * \par Time complexity * \f$ \Order{ t_{backward\_search} } \f$ */ template<class Csa> static typename Csa::csa_size_type count(const Csa& csa, typename Csa::pattern_type pat, typename Csa::size_type len) { if (len > csa.size()) return 0; typename Csa::size_type t1,t2; t1=t2=0; // dummy varaiable for the backward_search call return backward_search(csa, 0, csa.size()-1, pat, len, t1, t2); } //! Calculates all occurences of pattern pat in the string of the compressed suffix array csa. /*! * \param csa The compressed suffix array. * \param pat The pattern for which we get the occurences in the string of the compressed suffix array. * \param len The length of the pattern. * \param occ A resizable random access container in which the occurences are stored. * \return The number of occurences of pattern pat of lenght len in the string of the compressed suffix array. * * \par Time complexity * \f$ \Order{ t_{backward\_search} + z \cdot t_{SA} } \f$, where \f$z\f$ is the number of * occurences of pat in the text of the compressed suffix array. */ template<class Csa, class RandomAccessContainer> static typename Csa::csa_size_type locate(const Csa& csa, typename Csa::pattern_type pattern, typename Csa::size_type pattern_len, RandomAccessContainer& occ) { typename Csa::size_type occ_begin, occ_end, occs; occs = backward_search(csa, 0, csa.size()-1, pattern, pattern_len, occ_begin, occ_end); occ.resize(occs); for (typename Csa::size_type i=0; i < occs; ++i) { occ[i] = csa[occ_begin+i]; } return occs; } //! Returns the substring T[begin..end] of the original text T from the corresponding compressed suffix array. /*! * \param csa The compressed suffix array. * \param begin Index of the starting position (inclusive) of the substring in the original text. * \param end Index of the end position (inclusive) of the substring in the original text. * \param text A pointer to the extracted text. The memory has to be initialized before the call of the function! * \pre text has to be initialized with enough memory (end-begin+2 bytes) to hold the extracted text. * \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$ * \par Time complexity * \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$ */ // Is it cheaper to call T[i] = BWT[iSA[i+1]]??? Additional ranks but H_0 average access // TODO: extract backward!!! is faster in most cases! template<class Csa> static void extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end, unsigned char* text) { assert(end <= csa.size()); assert(begin <= end); for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) { uint16_t c_begin = 1, c_end = 257, mid; while (c_begin < c_end) { mid = (c_begin+c_end)>>1; if (csa.C[mid] <= order) { c_begin = mid+1; } else { c_end = mid; } } text[i-begin] = csa.comp2char[c_begin-1]; } if (text[end-begin]!=0) text[end-begin+1] = 0; // set terminal character } //! Reconstructs the text from position \f$begin\f$ to position \f$end\f$ (inclusive) from the compressed suffix array. /*! * \param csa The compressed suffix array. * \param begin Starting position (inclusive) of the text to extract. * \param end End position (inclusive) of the text to extract. * \return A std::string holding the extracted text. * \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$ * \par Time complexity * \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$ */ // TODO: use extract with four parameters to implement this method template<class Csa> static std::string extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end) { assert(end <= csa.size()); assert(begin <= end); std::string result(end-begin+1,' '); for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) { uint16_t c_begin = 1, c_end = 257, mid; while (c_begin < c_end) { mid = (c_begin+c_end)>>1; if (csa.C[mid] <= order) { c_begin = mid+1; } else { c_end = mid; } } result[i-begin] = csa.comp2char[c_begin-1]; } return result; } //! Forward search for a character c on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The compressed suffix tree. * \param v The node at the endpoint of the current edge. * \param d The current depth of the path. 0 = first character on each edge of the root node. * \param c The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$. * \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template<class Cst> typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v, const typename Cst::size_type d, const typename Cst::char_type c, typename Cst::size_type& char_pos) { unsigned char cc = cst.csa.char2comp[c]; // check if c occures in the text of the csa if (cc==0 and cc!=c) // " " " " " " " " " " return 0; typename Cst::size_type depth_node = cst.depth(v); if (d < depth_node) { // char_pos = cst.csa.psi[char_pos]; if (char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1]) return 0; return cst.leaves_in_the_subtree(v); } else if (d == depth_node) { // v = cst.child(v, c, char_pos); if (v == cst.root()) return 0; else return cst.leaves_in_the_subtree(v); } else { throw std::invalid_argument("depth d should be smaller or equal than node depth of v!"); return 0; } } //! Forward search for a pattern pat on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The compressed suffix tree. * \param v The node at the endpoint of the current edge. * \param d The current depth of the path. 0 = first character on each edge of the root node. * \param pat The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$. * \param len The length of the pattern. * \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template<class Cst> typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v, typename Cst::size_type d, typename Cst::pattern_type pat, typename Cst::size_type len, typename Cst::size_type& char_pos ) { if (len==0) return cst.leaves_in_the_subtree(v); typename Cst::size_type i=0, size=0; while (i < len and (size=forward_search(cst, v, d, pat[i], char_pos))) { ++d; ++i; } return size; } //! Calculates the count method for a (compressed) suffix tree of type Cst. /*! \param cst A const reference to the (compressed) suffix tree. * \param pat The pattern we seach the number of occurences. * \param len The length of the pattern. * \return Number of occurences of the pattern in the text of the (compressed) suffix tree. */ template<class Cst> typename Cst::cst_size_type count(const Cst& cst, typename Cst::pattern_type pat, typename Cst::size_type len) { typename Cst::node_type v = cst.root(); typename Cst::size_type char_pos = 0; return forward_search(cst, v, 0, pat, len, char_pos); } //! Calculates the locate method for a (compressed) suffix tree of type Cst. /*! \param cst A const reference to the (compressed) suffix tree. * \param pat The pattern for which we seach the occurences for. * \param len The length of the pattern. * \param occ A reference to a random access container in which we store the occurences of pattern in the text of the (compressed suffix array). * \return Number of occurences of the pattern in the text of the (compressed) suffix tree. */ template<class Cst, class RandomAccessContainer> typename Cst::cst_size_type locate(const Cst& cst, typename Cst::pattern_type pat, typename Cst::size_type len, RandomAccessContainer& occ) { typedef typename Cst::size_type size_type; typename Cst::node_type v = cst.root(); size_type char_pos = 0; typename Cst::cst_size_type occs = forward_search(cst, v, 0, pat, len, char_pos); occ.resize(occs); if (occs == 0) return 0; // because v equals cst.root() size_type left = cst.lb(v); // get range in the size_type right = cst.rb(v); for (size_type i=left; i <= right; ++i) occ[i-left] = cst.csa[i]; return occs; } //! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst. /*! * \param cst A const reference to the compressed suffix tree. * \param v The node where the concatenation of the edge labels ends. * \param text A pointer in which the string representing the concatenation of edge labels form the root to the node v will be stored. * \pre text has to be initialized with enough memory (\f$ cst.depth(v)+1\f$ bytes) to hold the extracted text. */ template<class Cst> void extract(const Cst& cst, const typename Cst::node_type& v, unsigned char* text) { if (v == cst.root()) { text[0] = 0; return; } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename Cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array extract(cst.csa, begin, begin + cst.depth(v) - 1, text); } //! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst. /*! * \param cst A const reference to the compressed suffix tree. * \param v The node where the concatenation of the edge labels ends. * \return The string of the concatenated edge labels from the root to the node v. */ template<class Cst> std::string extract(const Cst& cst, const typename Cst::node_type& v) { if (v==cst.root()) { return std::string(); } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename Cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array return extract(cst.csa, begin, begin + cst.depth(v) - 1); } /* template<class Cst> typename Cst::size_type count( const Cst &cst, typename Cst::pattern_type pattern, typename Cst::size_type pattern_len){ if(pattern_len==0){ return 0; } typedef typename Cst::size_type size_type; typedef typename Cst::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos); if( newnode == cst.root() )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position depth(node) for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } return cst.leaves_in_the_subtree(node); } */ /* template<class Cst, class RandomAccessContainer> typename Cst::size_type locate( const Cst &cst, typename Cst::pattern_type pattern, typename Cst::size_type pattern_len, RandomAccessContainer &occ){ occ.resize(0); typedef typename Cst::size_type size_type; typedef typename Cst::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos); if( newnode == cst.root() )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position depth(node) for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } size_type occs = cst.leaves_in_the_subtree(node); occ.resize(occs); size_type left = cst.leftmost_suffix_array_index_in_the_subtree(node); size_type right = cst.rightmost_suffix_array_index_in_the_subtree(node); for(size_type i=left; i <= right; ++i) occ[i-left] = cst.csa[i]; return occs; } */ /* template<class Csa, class Lcp, class Bp_support> typename cst_sct<Csa, Lcp, Bp_support>::size_type count( const cst_sct<Csa, Lcp, Bp_support> &cst, typename cst_sct<Csa, Lcp, Bp_support>::pattern_type pattern, typename cst_sct<Csa, Lcp, Bp_support>::size_type pattern_len){ if(pattern_len==0){ return 0; } typedef typename cst_sct<Csa, Lcp, Bp_support>::size_type size_type; typedef typename cst_sct<Csa, Lcp, Bp_support>::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; node.l < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[node.l], char_pos); if( newnode.l == 0 )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position node.l for(size_type j=node.l+1; j < newnode.l and j< pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } return cst.leaves_in_the_subtree(node); } */ } // end namespace algorithm } // end namespace sdsl #endif
andmaj/unrank-bottleneck-bench
sdsl_linear/include/sdsl/algorithms_for_string_matching.hpp
C++
gpl-3.0
18,541
/* * Copyright (C) 2014 The Android Open Source Project * * 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.google.android.exoplayer.text.tx3g; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.Subtitle; import com.google.android.exoplayer.text.SubtitleParser; import com.google.android.exoplayer.util.MimeTypes; import com.google.android.exoplayer.util.ParsableByteArray; /** * A {@link SubtitleParser} for tx3g. * <p> * Currently only supports parsing of a single text track. */ public final class Tx3gParser implements SubtitleParser { private final ParsableByteArray parsableByteArray; public Tx3gParser() { parsableByteArray = new ParsableByteArray(); } @Override public boolean canParse(String mimeType) { return MimeTypes.APPLICATION_TX3G.equals(mimeType); } @Override public Subtitle parse(byte[] bytes, int offset, int length) { parsableByteArray.reset(bytes, length); int textLength = parsableByteArray.readUnsignedShort(); if (textLength == 0) { return Tx3gSubtitle.EMPTY; } String cueText = parsableByteArray.readString(textLength); return new Tx3gSubtitle(new Cue(cueText)); } }
Lee-Wills/-tv
mmd/library/src/main/java/com/google/android/exoplayer/text/tx3g/Tx3gParser.java
Java
gpl-3.0
1,720
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using OpenRA.Network; using OpenRA.Widgets; namespace OpenRA.Mods.Common.Widgets.Logic { public class GameTimerLogic { [ObjectCreator.UseCtor] public GameTimerLogic(Widget widget, OrderManager orderManager, World world) { var timer = widget.GetOrNull<LabelWidget>("GAME_TIMER"); var status = widget.GetOrNull<LabelWidget>("GAME_TIMER_STATUS"); var startTick = Ui.LastTickTime; Func<bool> shouldShowStatus = () => (world.Paused || world.Timestep != Game.Timestep) && (Ui.LastTickTime - startTick) / 1000 % 2 == 0; Func<string> statusText = () => { if (world.Paused || world.Timestep == 0) return "Paused"; if (world.Timestep == 1) return "Max Speed"; return "{0}% Speed".F(Game.Timestep * 100 / world.Timestep); }; if (timer != null) { timer.GetText = () => { if (status == null && shouldShowStatus()) return statusText(); return WidgetUtils.FormatTime(world.WorldTick); }; } if (status != null) { // Blink the status line status.IsVisible = shouldShowStatus; status.GetText = statusText; } var percentage = widget.GetOrNull<LabelWidget>("GAME_TIMER_PERCENTAGE"); if (percentage != null) { var connection = orderManager.Connection as ReplayConnection; if (connection != null && connection.TickCount != 0) percentage.GetText = () => "({0}%)".F(orderManager.NetFrameNumber * 100 / connection.TickCount); else timer.Bounds.Width += percentage.Bounds.Width; } } } }
Sithil-F/OpenRA
OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs
C#
gpl-3.0
1,876
# # Copyright 2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, optfir from gnuradio.blks2impl.fm_emph import fm_deemph from math import pi class fm_demod_cf(gr.hier_block2): """ Generalized FM demodulation block with deemphasis and audio filtering. This block demodulates a band-limited, complex down-converted FM channel into the the original baseband signal, optionally applying deemphasis. Low pass filtering is done on the resultant signal. It produces an output float strem in the range of [-1.0, +1.0]. @param channel_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param deviation: maximum FM deviation (default = 5000) @type deviation: float @param audio_decim: input to output decimation rate @type audio_decim: integer @param audio_pass: audio low pass filter passband frequency @type audio_pass: float @param audio_stop: audio low pass filter stop frequency @type audio_stop: float @param gain: gain applied to audio output (default = 1.0) @type gain: float @param tau: deemphasis time constant (default = 75e-6), specify 'None' to prevent deemphasis """ def __init__(self, channel_rate, audio_decim, deviation, audio_pass, audio_stop, gain=1.0, tau=75e-6): gr.hier_block2.__init__(self, "fm_demod_cf", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature k = channel_rate/(2*pi*deviation) QUAD = gr.quadrature_demod_cf(k) audio_taps = optfir.low_pass(gain, # Filter gain channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple 60) # Stopband attenuation LPF = gr.fir_filter_fff(audio_decim, audio_taps) if tau is not None: DEEMPH = fm_deemph(channel_rate, tau) self.connect(self, QUAD, DEEMPH, LPF, self) else: self.connect(self, QUAD, LPF, self) class demod_20k0f3e_cf(fm_demod_cf): """ NBFM demodulation block, 20 KHz channels This block demodulates a complex, downconverted, narrowband FM channel conforming to 20K0F3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Deviation 3000, # Audio passband frequency 4500) # Audio stopband frequency class demod_200kf3e_cf(fm_demod_cf): """ WFM demodulation block, mono. This block demodulates a complex, downconverted, wideband FM channel conforming to 200KF3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 75000, # Deviation 15000, # Audio passband 16000, # Audio stopband 20.0) # Audio gain
n4hy/gnuradio
gnuradio-core/src/python/gnuradio/blks2impl/fm_demod.py
Python
gpl-3.0
4,236
class PortalGroup::Admin::Piece::SiteAreasController < Cms::Admin::Piece::BaseController end
tao-k/zomeki
app/controllers/portal_group/admin/piece/site_areas_controller.rb
Ruby
gpl-3.0
93
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines the base class for question import and export formats. * * @package moodlecore * @subpackage questionbank * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Base class for question import and export formats. * * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qformat_default { public $displayerrors = true; public $category = null; public $questions = array(); public $course = null; public $filename = ''; public $realfilename = ''; public $matchgrades = 'error'; public $catfromfile = 0; public $contextfromfile = 0; public $cattofile = 0; public $contexttofile = 0; public $questionids = array(); public $importerrors = 0; public $stoponerror = true; public $translator = null; public $canaccessbackupdata = true; protected $importcontext = null; // functions to indicate import/export functionality // override to return true if implemented /** @return bool whether this plugin provides import functionality. */ public function provide_import() { return false; } /** @return bool whether this plugin provides export functionality. */ public function provide_export() { return false; } /** The string mime-type of the files that this plugin reads or writes. */ public function mime_type() { return mimeinfo('type', $this->export_file_extension()); } /** * @return string the file extension (including .) that is normally used for * files handled by this plugin. */ public function export_file_extension() { return '.txt'; } /** * Check if the given file is capable of being imported by this plugin. * * Note that expensive or detailed integrity checks on the file should * not be performed by this method. Simple file type or magic-number tests * would be suitable. * * @param stored_file $file the file to check * @return bool whether this plugin can import the file */ public function can_import_file($file) { return ($file->get_mimetype() == $this->mime_type()); } // Accessor methods /** * set the category * @param object category the category object */ public function setCategory($category) { if (count($this->questions)) { debugging('You shouldn\'t call setCategory after setQuestions'); } $this->category = $category; $this->importcontext = context::instance_by_id($this->category->contextid); } /** * Set the specific questions to export. Should not include questions with * parents (sub questions of cloze question type). * Only used for question export. * @param array of question objects */ public function setQuestions($questions) { if ($this->category !== null) { debugging('You shouldn\'t call setQuestions after setCategory'); } $this->questions = $questions; } /** * set the course class variable * @param course object Moodle course variable */ public function setCourse($course) { $this->course = $course; } /** * set an array of contexts. * @param array $contexts Moodle course variable */ public function setContexts($contexts) { $this->contexts = $contexts; $this->translator = new context_to_string_translator($this->contexts); } /** * set the filename * @param string filename name of file to import/export */ public function setFilename($filename) { $this->filename = $filename; } /** * set the "real" filename * (this is what the user typed, regardless of wha happened next) * @param string realfilename name of file as typed by user */ public function setRealfilename($realfilename) { $this->realfilename = $realfilename; } /** * set matchgrades * @param string matchgrades error or nearest for grades */ public function setMatchgrades($matchgrades) { $this->matchgrades = $matchgrades; } /** * set catfromfile * @param bool catfromfile allow categories embedded in import file */ public function setCatfromfile($catfromfile) { $this->catfromfile = $catfromfile; } /** * set contextfromfile * @param bool $contextfromfile allow contexts embedded in import file */ public function setContextfromfile($contextfromfile) { $this->contextfromfile = $contextfromfile; } /** * set cattofile * @param bool cattofile exports categories within export file */ public function setCattofile($cattofile) { $this->cattofile = $cattofile; } /** * set contexttofile * @param bool cattofile exports categories within export file */ public function setContexttofile($contexttofile) { $this->contexttofile = $contexttofile; } /** * set stoponerror * @param bool stoponerror stops database write if any errors reported */ public function setStoponerror($stoponerror) { $this->stoponerror = $stoponerror; } /** * @param bool $canaccess Whether the current use can access the backup data folder. Determines * where export files are saved. */ public function set_can_access_backupdata($canaccess) { $this->canaccessbackupdata = $canaccess; } /*********************** * IMPORTING FUNCTIONS ***********************/ /** * Handle parsing error */ protected function error($message, $text='', $questionname='') { $importerrorquestion = get_string('importerrorquestion', 'question'); echo "<div class=\"importerror\">\n"; echo "<strong>$importerrorquestion $questionname</strong>"; if (!empty($text)) { $text = s($text); echo "<blockquote>$text</blockquote>\n"; } echo "<strong>$message</strong>\n"; echo "</div>"; $this->importerrors++; } /** * Import for questiontype plugins * Do not override. * @param data mixed The segment of data containing the question * @param question object processed (so far) by standard import code if appropriate * @param extra mixed any additional format specific data that may be passed by the format * @param qtypehint hint about a question type from format * @return object question object suitable for save_options() or false if cannot handle */ public function try_importing_using_qtypes($data, $question = null, $extra = null, $qtypehint = '') { // work out what format we are using $formatname = substr(get_class($this), strlen('qformat_')); $methodname = "import_from_$formatname"; //first try importing using a hint from format if (!empty($qtypehint)) { $qtype = question_bank::get_qtype($qtypehint, false); if (is_object($qtype) && method_exists($qtype, $methodname)) { $question = $qtype->$methodname($data, $question, $this, $extra); if ($question) { return $question; } } } // loop through installed questiontypes checking for // function to handle this question foreach (question_bank::get_all_qtypes() as $qtype) { if (method_exists($qtype, $methodname)) { if ($question = $qtype->$methodname($data, $question, $this, $extra)) { return $question; } } } return false; } /** * Perform any required pre-processing * @return bool success */ public function importpreprocess() { return true; } /** * Process the file * This method should not normally be overidden * @param object $category * @return bool success */ public function importprocess($category) { global $USER, $CFG, $DB, $OUTPUT; // reset the timer in case file upload was slow set_time_limit(0); // STAGE 1: Parse the file echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess'); if (! $lines = $this->readdata($this->filename)) { echo $OUTPUT->notification(get_string('cannotread', 'question')); return false; } if (!$questions = $this->readquestions($lines)) { // Extract all the questions echo $OUTPUT->notification(get_string('noquestionsinfile', 'question')); return false; } // STAGE 2: Write data to database echo $OUTPUT->notification(get_string('importingquestions', 'question', $this->count_questions($questions)), 'notifysuccess'); // check for errors before we continue if ($this->stoponerror and ($this->importerrors>0)) { echo $OUTPUT->notification(get_string('importparseerror', 'question')); return true; } // get list of valid answer grades $gradeoptionsfull = question_bank::fraction_options_full(); // check answer grades are valid // (now need to do this here because of 'stop on error': MDL-10689) $gradeerrors = 0; $goodquestions = array(); foreach ($questions as $question) { if (!empty($question->fraction) and (is_array($question->fraction))) { $fractions = $question->fraction; $invalidfractions = array(); foreach ($fractions as $key => $fraction) { $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades); if ($newfraction === false) { $invalidfractions[] = $fraction; } else { $fractions[$key] = $newfraction; } } if ($invalidfractions) { echo $OUTPUT->notification(get_string('invalidgrade', 'question', implode(', ', $invalidfractions))); ++$gradeerrors; continue; } else { $question->fraction = $fractions; } } $goodquestions[] = $question; } $questions = $goodquestions; // check for errors before we continue if ($this->stoponerror && $gradeerrors > 0) { return false; } // count number of questions processed $count = 0; foreach ($questions as $question) { // Process and store each question // reset the php timeout set_time_limit(0); // check for category modifiers if ($question->qtype == 'category') { if ($this->catfromfile) { // find/create category object $catpath = $question->category; $newcategory = $this->create_category_path($catpath); if (!empty($newcategory)) { $this->category = $newcategory; } } continue; } $question->context = $this->importcontext; $count++; echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>"; $question->category = $this->category->id; $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed) $question->createdby = $USER->id; $question->timecreated = time(); $question->modifiedby = $USER->id; $question->timemodified = time(); $fileoptions = array( 'subdirs' => true, 'maxfiles' => -1, 'maxbytes' => 0, ); $question->id = $DB->insert_record('question', $question); if (isset($question->questiontextitemid)) { $question->questiontext = file_save_draft_area_files($question->questiontextitemid, $this->importcontext->id, 'question', 'questiontext', $question->id, $fileoptions, $question->questiontext); } else if (isset($question->questiontextfiles)) { foreach ($question->questiontextfiles as $file) { question_bank::get_qtype($question->qtype)->import_file( $this->importcontext, 'question', 'questiontext', $question->id, $file); } } if (isset($question->generalfeedbackitemid)) { $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid, $this->importcontext->id, 'question', 'generalfeedback', $question->id, $fileoptions, $question->generalfeedback); } else if (isset($question->generalfeedbackfiles)) { foreach ($question->generalfeedbackfiles as $file) { question_bank::get_qtype($question->qtype)->import_file( $this->importcontext, 'question', 'generalfeedback', $question->id, $file); } } $DB->update_record('question', $question); $this->questionids[] = $question->id; // Now to save all the answers and type-specific options $result = question_bank::get_qtype($question->qtype)->save_question_options($question); if (!empty($CFG->usetags) && isset($question->tags)) { require_once($CFG->dirroot . '/tag/lib.php'); tag_set('question', $question->id, $question->tags); } if (!empty($result->error)) { echo $OUTPUT->notification($result->error); return false; } if (!empty($result->notice)) { echo $OUTPUT->notification($result->notice); return true; } // Give the question a unique version stamp determined by question_hash() $DB->set_field('question', 'version', question_hash($question), array('id' => $question->id)); } return true; } /** * Count all non-category questions in the questions array. * * @param array questions An array of question objects. * @return int The count. * */ protected function count_questions($questions) { $count = 0; if (!is_array($questions)) { return $count; } foreach ($questions as $question) { if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) { continue; } $count++; } return $count; } /** * find and/or create the category described by a delimited list * e.g. $course$/tom/dick/harry or tom/dick/harry * * removes any context string no matter whether $getcontext is set * but if $getcontext is set then ignore the context and use selected category context. * * @param string catpath delimited category path * @param int courseid course to search for categories * @return mixed category object or null if fails */ protected function create_category_path($catpath) { global $DB; $catnames = $this->split_category_path($catpath); $parent = 0; $category = null; // check for context id in path, it might not be there in pre 1.9 exports $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches); if ($matchcount == 1) { $contextid = $this->translator->string_to_context($matches[1]); array_shift($catnames); } else { $contextid = false; } if ($this->contextfromfile && $contextid !== false) { $context = context::instance_by_id($contextid); require_capability('moodle/question:add', $context); } else { $context = context::instance_by_id($this->category->contextid); } $this->importcontext = $context; // Now create any categories that need to be created. foreach ($catnames as $catname) { if ($category = $DB->get_record('question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) { $parent = $category->id; } else { require_capability('moodle/question:managecategory', $context); // create the new category $category = new stdClass(); $category->contextid = $context->id; $category->name = $catname; $category->info = ''; $category->parent = $parent; $category->sortorder = 999; $category->stamp = make_unique_id_code(); $id = $DB->insert_record('question_categories', $category); $category->id = $id; $parent = $id; } } return $category; } /** * Return complete file within an array, one item per line * @param string filename name of file * @return mixed contents array or false on failure */ protected function readdata($filename) { if (is_readable($filename)) { $filearray = file($filename); // If the first line of the file starts with a UTF-8 BOM, remove it. $filearray[0] = core_text::trim_utf8_bom($filearray[0]); // Check for Macintosh OS line returns (ie file on one line), and fix. if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) { return explode("\r", $filearray[0]); } else { return $filearray; } } return false; } /** * Parses an array of lines into an array of questions, * where each item is a question object as defined by * readquestion(). Questions are defined as anything * between blank lines. * * NOTE this method used to take $context as a second argument. However, at * the point where this method was called, it was impossible to know what * context the quetsions were going to be saved into, so the value could be * wrong. Also, none of the standard question formats were using this argument, * so it was removed. See MDL-32220. * * If your format does not use blank lines as a delimiter * then you will need to override this method. Even then * try to use readquestion for each question * @param array lines array of lines from readdata * @return array array of question objects */ protected function readquestions($lines) { $questions = array(); $currentquestion = array(); foreach ($lines as $line) { $line = trim($line); if (empty($line)) { if (!empty($currentquestion)) { if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } $currentquestion = array(); } } else { $currentquestion[] = $line; } } if (!empty($currentquestion)) { // There may be a final question if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } } return $questions; } /** * return an "empty" question * Somewhere to specify question parameters that are not handled * by import but are required db fields. * This should not be overridden. * @return object default question */ protected function defaultquestion() { global $CFG; static $defaultshuffleanswers = null; if (is_null($defaultshuffleanswers)) { $defaultshuffleanswers = get_config('quiz', 'shuffleanswers'); } $question = new stdClass(); $question->shuffleanswers = $defaultshuffleanswers; $question->defaultmark = 1; $question->image = ""; $question->usecase = 0; $question->multiplier = array(); $question->questiontextformat = FORMAT_MOODLE; $question->generalfeedback = ''; $question->generalfeedbackformat = FORMAT_MOODLE; $question->correctfeedback = ''; $question->partiallycorrectfeedback = ''; $question->incorrectfeedback = ''; $question->answernumbering = 'abc'; $question->penalty = 0.3333333; $question->length = 1; // this option in case the questiontypes class wants // to know where the data came from $question->export_process = true; $question->import_process = true; return $question; } /** * Construct a reasonable default question name, based on the start of the question text. * @param string $questiontext the question text. * @param string $default default question name to use if the constructed one comes out blank. * @return string a reasonable question name. */ public function create_default_question_name($questiontext, $default) { $name = $this->clean_question_name(shorten_text($questiontext, 80)); if ($name) { return $name; } else { return $default; } } /** * Ensure that a question name does not contain anything nasty, and will fit in the DB field. * @param string $name the raw question name. * @return string a safe question name. */ public function clean_question_name($name) { $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does. $name = trim($name); $trimlength = 251; while (core_text::strlen($name) > 255 && $trimlength > 0) { $name = shorten_text($name, $trimlength); $trimlength -= 10; } return $name; } /** * Add a blank combined feedback to a question object. * @param object question * @return object question */ protected function add_blank_combined_feedback($question) { $question->correctfeedback['text'] = ''; $question->correctfeedback['format'] = $question->questiontextformat; $question->correctfeedback['files'] = array(); $question->partiallycorrectfeedback['text'] = ''; $question->partiallycorrectfeedback['format'] = $question->questiontextformat; $question->partiallycorrectfeedback['files'] = array(); $question->incorrectfeedback['text'] = ''; $question->incorrectfeedback['format'] = $question->questiontextformat; $question->incorrectfeedback['files'] = array(); return $question; } /** * Given the data known to define a question in * this format, this function converts it into a question * object suitable for processing and insertion into Moodle. * * If your format does not use blank lines to delimit questions * (e.g. an XML format) you must override 'readquestions' too * @param $lines mixed data that represents question * @return object question object */ protected function readquestion($lines) { $formatnotimplemented = get_string('formatnotimplemented', 'question'); echo "<p>$formatnotimplemented</p>"; return null; } /** * Override if any post-processing is required * @return bool success */ public function importpostprocess() { return true; } /******************* * EXPORT FUNCTIONS *******************/ /** * Provide export functionality for plugin questiontypes * Do not override * @param name questiontype name * @param question object data to export * @param extra mixed any addition format specific data needed * @return string the data to append to export or false if error (or unhandled) */ protected function try_exporting_using_qtypes($name, $question, $extra=null) { // work out the name of format in use $formatname = substr(get_class($this), strlen('qformat_')); $methodname = "export_to_$formatname"; $qtype = question_bank::get_qtype($name, false); if (method_exists($qtype, $methodname)) { return $qtype->$methodname($question, $this, $extra); } return false; } /** * Do any pre-processing that may be required * @param bool success */ public function exportpreprocess() { return true; } /** * Enable any processing to be done on the content * just prior to the file being saved * default is to do nothing * @param string output text * @param string processed output text */ protected function presave_process($content) { return $content; } /** * Do the export * For most types this should not need to be overrided * @return stored_file */ public function exportprocess() { global $CFG, $OUTPUT, $DB, $USER; // get the questions (from database) in this category // only get q's with no parents (no cloze subquestions specifically) if ($this->category) { $questions = get_questions_category($this->category, true); } else { $questions = $this->questions; } $count = 0; // results are first written into string (and then to a file) // so create/initialize the string here $expout = ""; // track which category questions are in // if it changes we will record the category change in the output // file if selected. 0 means that it will get printed before the 1st question $trackcategory = 0; // iterate through questions foreach ($questions as $question) { // used by file api $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $question->category)); $question->contextid = $contextid; // do not export hidden questions if (!empty($question->hidden)) { continue; } // do not export random questions if ($question->qtype == 'random') { continue; } // check if we need to record category change if ($this->cattofile) { if ($question->category != $trackcategory) { $trackcategory = $question->category; $categoryname = $this->get_category_path($trackcategory, $this->contexttofile); // create 'dummy' question for category export $dummyquestion = new stdClass(); $dummyquestion->qtype = 'category'; $dummyquestion->category = $categoryname; $dummyquestion->name = 'Switch category to ' . $categoryname; $dummyquestion->id = 0; $dummyquestion->questiontextformat = ''; $dummyquestion->contextid = 0; $expout .= $this->writequestion($dummyquestion) . "\n"; } } // export the question displaying message $count++; if (question_has_capability_on($question, 'view', $question->category)) { $expout .= $this->writequestion($question, $contextid) . "\n"; } } // continue path for following error checks $course = $this->course; $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id"; // did we actually process anything if ($count==0) { print_error('noquestions', 'question', $continuepath); } // final pre-process on exported data $expout = $this->presave_process($expout); return $expout; } /** * get the category as a path (e.g., tom/dick/harry) * @param int id the id of the most nested catgory * @return string the path */ protected function get_category_path($id, $includecontext = true) { global $DB; if (!$category = $DB->get_record('question_categories', array('id' => $id))) { print_error('cannotfindcategory', 'error', '', $id); } $contextstring = $this->translator->context_to_string($category->contextid); $pathsections = array(); do { $pathsections[] = $category->name; $id = $category->parent; } while ($category = $DB->get_record('question_categories', array('id' => $id))); if ($includecontext) { $pathsections[] = '$' . $contextstring . '$'; } $path = $this->assemble_category_path(array_reverse($pathsections)); return $path; } /** * Convert a list of category names, possibly preceeded by one of the * context tokens like $course$, into a string representation of the * category path. * * Names are separated by / delimiters. And /s in the name are replaced by //. * * To reverse the process and split the paths into names, use * {@link split_category_path()}. * * @param array $names * @return string */ protected function assemble_category_path($names) { $escapednames = array(); foreach ($names as $name) { $escapedname = str_replace('/', '//', $name); if (substr($escapedname, 0, 1) == '/') { $escapedname = ' ' . $escapedname; } if (substr($escapedname, -1) == '/') { $escapedname = $escapedname . ' '; } $escapednames[] = $escapedname; } return implode('/', $escapednames); } /** * Convert a string, as returned by {@link assemble_category_path()}, * back into an array of category names. * * Each category name is cleaned by a call to clean_param(, PARAM_TEXT), * which matches the cleaning in question/category_form.php. * * @param string $path * @return array of category names. */ protected function split_category_path($path) { $rawnames = preg_split('~(?<!/)/(?!/)~', $path); $names = array(); foreach ($rawnames as $rawname) { $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT); } return $names; } /** * Do an post-processing that may be required * @return bool success */ protected function exportpostprocess() { return true; } /** * convert a single question object into text output in the given * format. * This must be overriden * @param object question question object * @return mixed question export text or null if not implemented */ protected function writequestion($question) { // if not overidden, then this is an error. $formatnotimplemented = get_string('formatnotimplemented', 'question'); echo "<p>$formatnotimplemented</p>"; return null; } /** * Convert the question text to plain text, so it can safely be displayed * during import to let the user see roughly what is going on. */ protected function format_question_text($question) { return question_utils::to_plain_text($question->questiontext, $question->questiontextformat); } } class qformat_based_on_xml extends qformat_default { /** * A lot of imported files contain unwanted entities. * This method tries to clean up all known problems. * @param string str string to correct * @return string the corrected string */ public function cleaninput($str) { $html_code_list = array( "&#039;" => "'", "&#8217;" => "'", "&#8220;" => "\"", "&#8221;" => "\"", "&#8211;" => "-", "&#8212;" => "-", ); $str = strtr($str, $html_code_list); // Use core_text entities_to_utf8 function to convert only numerical entities. $str = core_text::entities_to_utf8($str, false); return $str; } /** * Return the array moodle is expecting * for an HTML text. No processing is done on $text. * qformat classes that want to process $text * for instance to import external images files * and recode urls in $text must overwrite this method. * @param array $text some HTML text string * @return array with keys text, format and files. */ public function text_field($text) { return array( 'text' => trim($text), 'format' => FORMAT_HTML, 'files' => array(), ); } /** * Return the value of a node, given a path to the node * if it doesn't exist return the default value. * @param array xml data to read * @param array path path to node expressed as array * @param mixed default * @param bool istext process as text * @param string error if set value must exist, return false and issue message if not * @return mixed value */ public function getpath($xml, $path, $default, $istext=false, $error='') { foreach ($path as $index) { if (!isset($xml[$index])) { if (!empty($error)) { $this->error($error); return false; } else { return $default; } } $xml = $xml[$index]; } if ($istext) { if (!is_string($xml)) { $this->error(get_string('invalidxml', 'qformat_xml')); } $xml = trim($xml); } return $xml; } }
dslab-epfl/accessibility-checker
question/format.php
PHP
gpl-3.0
35,327
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Classes representing HTML elements, used by $OUTPUT methods * * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML * for an overview. * * @package core * @category output * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Interface marking other classes as suitable for renderer_base::render() * * @copyright 2010 Petr Skoda (skodak) info@skodak.org * @package core * @category output */ interface renderable { // intentionally empty } /** * Data structure representing a file picker. * * @copyright 2010 Dongsheng Cai * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class file_picker implements renderable { /** * @var stdClass An object containing options for the file picker */ public $options; /** * Constructs a file picker object. * * The following are possible options for the filepicker: * - accepted_types (*) * - return_types (FILE_INTERNAL) * - env (filepicker) * - client_id (uniqid) * - itemid (0) * - maxbytes (-1) * - maxfiles (1) * - buttonname (false) * * @param stdClass $options An object containing options for the file picker. */ public function __construct(stdClass $options) { global $CFG, $USER, $PAGE; require_once($CFG->dirroot. '/repository/lib.php'); $defaults = array( 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL, 'env' => 'filepicker', 'client_id' => uniqid(), 'itemid' => 0, 'maxbytes'=>-1, 'maxfiles'=>1, 'buttonname'=>false ); foreach ($defaults as $key=>$value) { if (empty($options->$key)) { $options->$key = $value; } } $options->currentfile = ''; if (!empty($options->itemid)) { $fs = get_file_storage(); $usercontext = context_user::instance($USER->id); if (empty($options->filename)) { if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) { $file = reset($files); } } else { $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename); } if (!empty($file)) { $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename()); } } // initilise options, getting files in root path $this->options = initialise_filepicker($options); // copying other options foreach ($options as $name=>$value) { if (!isset($this->options->$name)) { $this->options->$name = $value; } } } } /** * Data structure representing a user picture. * * @copyright 2009 Nicolas Connault, 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Modle 2.0 * @package core * @category output */ class user_picture implements renderable { /** * @var array List of mandatory fields in user record here. (do not include * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE) */ protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic', 'middlename', 'alternatename', 'imagealt', 'email'); /** * @var stdClass A user object with at least fields all columns specified * in $fields array constant set. */ public $user; /** * @var int The course id. Used when constructing the link to the user's * profile, page course id used if not specified. */ public $courseid; /** * @var bool Add course profile link to image */ public $link = true; /** * @var int Size in pixels. Special values are (true/1 = 100px) and * (false/0 = 35px) * for backward compatibility. */ public $size = 35; /** * @var bool Add non-blank alt-text to the image. * Default true, set to false when image alt just duplicates text in screenreaders. */ public $alttext = true; /** * @var bool Whether or not to open the link in a popup window. */ public $popup = false; /** * @var string Image class attribute */ public $class = 'userpicture'; /** * @var bool Whether to be visible to screen readers. */ public $visibletoscreenreaders = true; /** * User picture constructor. * * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set. * It is recommended to add also contextid of the user for performance reasons. */ public function __construct(stdClass $user) { global $DB; if (empty($user->id)) { throw new coding_exception('User id is required when printing user avatar image.'); } // only touch the DB if we are missing data and complain loudly... $needrec = false; foreach (self::$fields as $field) { if (!array_key_exists($field, $user)) { $needrec = true; debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. ' .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER); break; } } if ($needrec) { $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST); } else { $this->user = clone($user); } } /** * Returns a list of required user fields, useful when fetching required user info from db. * * In some cases we have to fetch the user data together with some other information, * the idalias is useful there because the id would otherwise override the main * id of the result record. Please note it has to be converted back to id before rendering. * * @param string $tableprefix name of database table prefix in query * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE) * @param string $idalias alias of id field * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id' * @return string */ public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') { if (!$tableprefix and !$extrafields and !$idalias) { return implode(',', self::$fields); } if ($tableprefix) { $tableprefix .= '.'; } foreach (self::$fields as $field) { if ($field === 'id' and $idalias and $idalias !== 'id') { $fields[$field] = "$tableprefix$field AS $idalias"; } else { if ($fieldprefix and $field !== 'id') { $fields[$field] = "$tableprefix$field AS $fieldprefix$field"; } else { $fields[$field] = "$tableprefix$field"; } } } // add extra fields if not already there if ($extrafields) { foreach ($extrafields as $e) { if ($e === 'id' or isset($fields[$e])) { continue; } if ($fieldprefix) { $fields[$e] = "$tableprefix$e AS $fieldprefix$e"; } else { $fields[$e] = "$tableprefix$e"; } } } return implode(',', $fields); } /** * Extract the aliased user fields from a given record * * Given a record that was previously obtained using {@link self::fields()} with aliases, * this method extracts user related unaliased fields. * * @param stdClass $record containing user picture fields * @param array $extrafields extra fields included in the $record * @param string $idalias alias of the id field * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id' * @return stdClass object with unaliased user fields */ public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') { if (empty($idalias)) { $idalias = 'id'; } $return = new stdClass(); foreach (self::$fields as $field) { if ($field === 'id') { if (property_exists($record, $idalias)) { $return->id = $record->{$idalias}; } } else { if (property_exists($record, $fieldprefix.$field)) { $return->{$field} = $record->{$fieldprefix.$field}; } } } // add extra fields if not already there if ($extrafields) { foreach ($extrafields as $e) { if ($e === 'id' or property_exists($return, $e)) { continue; } $return->{$e} = $record->{$fieldprefix.$e}; } } return $return; } /** * Works out the URL for the users picture. * * This method is recommended as it avoids costly redirects of user pictures * if requests are made for non-existent files etc. * * @param moodle_page $page * @param renderer_base $renderer * @return moodle_url */ public function get_url(moodle_page $page, renderer_base $renderer = null) { global $CFG; if (is_null($renderer)) { $renderer = $page->get_renderer('core'); } // Sort out the filename and size. Size is only required for the gravatar // implementation presently. if (empty($this->size)) { $filename = 'f2'; $size = 35; } else if ($this->size === true or $this->size == 1) { $filename = 'f1'; $size = 100; } else if ($this->size > 100) { $filename = 'f3'; $size = (int)$this->size; } else if ($this->size >= 50) { $filename = 'f1'; $size = (int)$this->size; } else { $filename = 'f2'; $size = (int)$this->size; } $defaulturl = $renderer->pix_url('u/'.$filename); // default image if ((!empty($CFG->forcelogin) and !isloggedin()) || (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) { // Protect images if login required and not logged in; // also if login is required for profile images and is not logged in or guest // do not use require_login() because it is expensive and not suitable here anyway. return $defaulturl; } // First try to detect deleted users - but do not read from database for performance reasons! if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) { // All deleted users should have email replaced by md5 hash, // all active users are expected to have valid email. return $defaulturl; } // Did the user upload a picture? if ($this->user->picture > 0) { if (!empty($this->user->contextid)) { $contextid = $this->user->contextid; } else { $context = context_user::instance($this->user->id, IGNORE_MISSING); if (!$context) { // This must be an incorrectly deleted user, all other users have context. return $defaulturl; } $contextid = $context->id; } $path = '/'; if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) { // We append the theme name to the file path if we have it so that // in the circumstance that the profile picture is not available // when the user actually requests it they still get the profile // picture for the correct theme. $path .= $page->theme->name.'/'; } // Set the image URL to the URL for the uploaded file and return. $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename); $url->param('rev', $this->user->picture); return $url; } if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) { // Normalise the size variable to acceptable bounds if ($size < 1 || $size > 512) { $size = 35; } // Hash the users email address $md5 = md5(strtolower(trim($this->user->email))); // Build a gravatar URL with what we know. // Find the best default image URL we can (MDL-35669) if (empty($CFG->gravatardefaulturl)) { $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core'); if (strpos($absoluteimagepath, $CFG->dirroot) === 0) { $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot)); } else { $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png'; } } else { $gravatardefault = $CFG->gravatardefaulturl; } // If the currently requested page is https then we'll return an // https gravatar page. if (is_https()) { $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url. return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); } else { return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); } } return $defaulturl; } } /** * Data structure representing a help icon. * * @copyright 2010 Petr Skoda (info@skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class help_icon implements renderable { /** * @var string lang pack identifier (without the "_help" suffix), * both get_string($identifier, $component) and get_string($identifier.'_help', $component) * must exist. */ public $identifier; /** * @var string Component name, the same as in get_string() */ public $component; /** * @var string Extra descriptive text next to the icon */ public $linktext = null; /** * Constructor * * @param string $identifier string for help page title, * string with _help suffix is used for the actual help text. * string with _link suffix is used to create a link to further info (if it exists) * @param string $component */ public function __construct($identifier, $component) { $this->identifier = $identifier; $this->component = $component; } /** * Verifies that both help strings exists, shows debug warnings if not */ public function diag_strings() { $sm = get_string_manager(); if (!$sm->string_exists($this->identifier, $this->component)) { debugging("Help title string does not exist: [$this->identifier, $this->component]"); } if (!$sm->string_exists($this->identifier.'_help', $this->component)) { debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]"); } } } /** * Data structure representing an icon. * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class pix_icon implements renderable { /** * @var string The icon name */ var $pix; /** * @var string The component the icon belongs to. */ var $component; /** * @var array An array of attributes to use on the icon */ var $attributes = array(); /** * Constructor * * @param string $pix short icon name * @param string $alt The alt text to use for the icon * @param string $component component name * @param array $attributes html attributes */ public function __construct($pix, $alt, $component='moodle', array $attributes = null) { $this->pix = $pix; $this->component = $component; $this->attributes = (array)$attributes; $this->attributes['alt'] = $alt; if (empty($this->attributes['class'])) { $this->attributes['class'] = 'smallicon'; } if (!isset($this->attributes['title'])) { $this->attributes['title'] = $this->attributes['alt']; } else if (empty($this->attributes['title'])) { // Remove the title attribute if empty, we probably want to use the parent node's title // and some browsers might overwrite it with an empty title. unset($this->attributes['title']); } } } /** * Data structure representing an emoticon image * * @copyright 2010 David Mudrak * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class pix_emoticon extends pix_icon implements renderable { /** * Constructor * @param string $pix short icon name * @param string $alt alternative text * @param string $component emoticon image provider * @param array $attributes explicit HTML attributes */ public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) { if (empty($attributes['class'])) { $attributes['class'] = 'emoticon'; } parent::__construct($pix, $alt, $component, $attributes); } } /** * Data structure representing a simple form with only one button. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class single_button implements renderable { /** * @var moodle_url Target url */ var $url; /** * @var string Button label */ var $label; /** * @var string Form submit method post or get */ var $method = 'post'; /** * @var string Wrapping div class */ var $class = 'singlebutton'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid; /** * @var array List of attached actions */ var $actions = array(); /** * Constructor * @param moodle_url $url * @param string $label button text * @param string $method get or post submit method */ public function __construct(moodle_url $url, $label, $method='post') { $this->url = clone($url); $this->label = $label; $this->method = $method; } /** * Shortcut for adding a JS confirm dialog when the button is clicked. * The message must be a yes/no question. * * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur. */ public function add_confirm_action($confirmmessage) { $this->add_action(new confirm_action($confirmmessage)); } /** * Add action to the button. * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } } /** * Simple form with just one select field that gets submitted automatically. * * If JS not enabled small go button is printed too. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class single_select implements renderable { /** * @var moodle_url Target url - includes hidden fields */ var $url; /** * @var string Name of the select element. */ var $name; /** * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ var $options; /** * @var string Selected option */ var $selected; /** * @var array Nothing selected */ var $nothing; /** * @var array Extra select field attributes */ var $attributes = array(); /** * @var string Button label */ var $label = ''; /** * @var array Button label's attributes */ var $labelattributes = array(); /** * @var string Form submit method post or get */ var $method = 'get'; /** * @var string Wrapping div class */ var $class = 'singleselect'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid = null; /** * @var array List of attached actions */ var $helpicon = null; /** * Constructor * @param moodle_url $url form action target, includes hidden fields * @param string $name name of selection field - the changing parameter in url * @param array $options list of options * @param string $selected selected element * @param array $nothing * @param string $formid */ public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) { $this->url = $url; $this->name = $name; $this->options = $options; $this->selected = $selected; $this->nothing = $nothing; $this->formid = $formid; } /** * Shortcut for adding a JS confirm dialog when the button is clicked. * The message must be a yes/no question. * * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur. */ public function add_confirm_action($confirmmessage) { $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage))); } /** * Add action to the button. * * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } /** * Adds help icon. * * @deprecated since Moodle 2.0 */ public function set_old_help_icon($helppage, $title, $component = 'moodle') { throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().'); } /** * Adds help icon. * * @param string $identifier The keyword that defines a help page * @param string $component */ public function set_help_icon($identifier, $component = 'moodle') { $this->helpicon = new help_icon($identifier, $component); } /** * Sets select's label * * @param string $label * @param array $attributes (optional) */ public function set_label($label, $attributes = array()) { $this->label = $label; $this->labelattributes = $attributes; } } /** * Simple URL selection widget description. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class url_select implements renderable { /** * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ var $urls; /** * @var string Selected option */ var $selected; /** * @var array Nothing selected */ var $nothing; /** * @var array Extra select field attributes */ var $attributes = array(); /** * @var string Button label */ var $label = ''; /** * @var array Button label's attributes */ var $labelattributes = array(); /** * @var string Wrapping div class */ var $class = 'urlselect'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid = null; /** * @var array List of attached actions */ var $helpicon = null; /** * @var string If set, makes button visible with given name for button */ var $showbutton = null; /** * Constructor * @param array $urls list of options * @param string $selected selected element * @param array $nothing * @param string $formid * @param string $showbutton Set to text of button if it should be visible * or null if it should be hidden (hidden version always has text 'go') */ public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) { $this->urls = $urls; $this->selected = $selected; $this->nothing = $nothing; $this->formid = $formid; $this->showbutton = $showbutton; } /** * Adds help icon. * * @deprecated since Moodle 2.0 */ public function set_old_help_icon($helppage, $title, $component = 'moodle') { throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().'); } /** * Adds help icon. * * @param string $identifier The keyword that defines a help page * @param string $component */ public function set_help_icon($identifier, $component = 'moodle') { $this->helpicon = new help_icon($identifier, $component); } /** * Sets select's label * * @param string $label * @param array $attributes (optional) */ public function set_label($label, $attributes = array()) { $this->label = $label; $this->labelattributes = $attributes; } } /** * Data structure describing html link with special action attached. * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class action_link implements renderable { /** * @var moodle_url Href url */ public $url; /** * @var string Link text HTML fragment */ public $text; /** * @var array HTML attributes */ public $attributes; /** * @var array List of actions attached to link */ public $actions; /** * @var pix_icon Optional pix icon to render with the link */ public $icon; /** * Constructor * @param moodle_url $url * @param string $text HTML fragment * @param component_action $action * @param array $attributes associative array of html link attributes + disabled * @param pix_icon $icon optional pix_icon to render with the link text */ public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null, pix_icon $icon=null) { $this->url = clone($url); $this->text = $text; $this->attributes = (array)$attributes; if ($action) { $this->add_action($action); } $this->icon = $icon; } /** * Add action to the link. * * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } /** * Adds a CSS class to this action link object * @param string $class */ public function add_class($class) { if (empty($this->attributes['class'])) { $this->attributes['class'] = $class; } else { $this->attributes['class'] .= ' ' . $class; } } /** * Returns true if the specified class has been added to this link. * @param string $class * @return bool */ public function has_class($class) { return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false; } } /** * Simple html output class * * @copyright 2009 Tim Hunt, 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_writer { /** * Outputs a tag with attributes and contents * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function tag($tagname, $contents, array $attributes = null) { return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname); } /** * Outputs an opening tag with attributes * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function start_tag($tagname, array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . '>'; } /** * Outputs a closing tag * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @return string HTML fragment */ public static function end_tag($tagname) { return '</' . $tagname . '>'; } /** * Outputs an empty tag with attributes * * @param string $tagname The name of tag ('input', 'img', 'br' etc.) * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function empty_tag($tagname, array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . ' />'; } /** * Outputs a tag, but only if the contents are not empty * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function nonempty_tag($tagname, $contents, array $attributes = null) { if ($contents === '' || is_null($contents)) { return ''; } return self::tag($tagname, $contents, $attributes); } /** * Outputs a HTML attribute and value * * @param string $name The name of the attribute ('src', 'href', 'class' etc.) * @param string $value The value of the attribute. The value will be escaped with {@link s()} * @return string HTML fragment */ public static function attribute($name, $value) { if ($value instanceof moodle_url) { return ' ' . $name . '="' . $value->out() . '"'; } // special case, we do not want these in output if ($value === null) { return ''; } // no sloppy trimming here! return ' ' . $name . '="' . s($value) . '"'; } /** * Outputs a list of HTML attributes and values * * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * The values will be escaped with {@link s()} * @return string HTML fragment */ public static function attributes(array $attributes = null) { $attributes = (array)$attributes; $output = ''; foreach ($attributes as $name => $value) { $output .= self::attribute($name, $value); } return $output; } /** * Generates a simple image tag with attributes. * * @param string $src The source of image * @param string $alt The alternate text for image * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function img($src, $alt, array $attributes = null) { $attributes = (array)$attributes; $attributes['src'] = $src; $attributes['alt'] = $alt; return self::empty_tag('img', $attributes); } /** * Generates random html element id. * * @staticvar int $counter * @staticvar type $uniq * @param string $base A string fragment that will be included in the random ID. * @return string A unique ID */ public static function random_id($base='random') { static $counter = 0; static $uniq; if (!isset($uniq)) { $uniq = uniqid(); } $counter++; return $base.$uniq.$counter; } /** * Generates a simple html link * * @param string|moodle_url $url The URL * @param string $text The text * @param array $attributes HTML attributes * @return string HTML fragment */ public static function link($url, $text, array $attributes = null) { $attributes = (array)$attributes; $attributes['href'] = $url; return self::tag('a', $text, $attributes); } /** * Generates a simple checkbox with optional label * * @param string $name The name of the checkbox * @param string $value The value of the checkbox * @param bool $checked Whether the checkbox is checked * @param string $label The label for the checkbox * @param array $attributes Any attributes to apply to the checkbox * @return string html fragment */ public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) { $attributes = (array)$attributes; $output = ''; if ($label !== '' and !is_null($label)) { if (empty($attributes['id'])) { $attributes['id'] = self::random_id('checkbox_'); } } $attributes['type'] = 'checkbox'; $attributes['value'] = $value; $attributes['name'] = $name; $attributes['checked'] = $checked ? 'checked' : null; $output .= self::empty_tag('input', $attributes); if ($label !== '' and !is_null($label)) { $output .= self::tag('label', $label, array('for'=>$attributes['id'])); } return $output; } /** * Generates a simple select yes/no form field * * @param string $name name of select element * @param bool $selected * @param array $attributes - html select element attributes * @return string HTML fragment */ public static function select_yes_no($name, $selected=true, array $attributes = null) { $options = array('1'=>get_string('yes'), '0'=>get_string('no')); return self::select($options, $name, $selected, null, $attributes); } /** * Generates a simple select form field * * @param array $options associative array value=>label ex.: * array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) * @param string $name name of select element * @param string|array $selected value or array of values depending on multiple attribute * @param array|bool $nothing add nothing selected option, or false of not added * @param array $attributes html select element attributes * @return string HTML fragment */ public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) { $attributes = (array)$attributes; if (is_array($nothing)) { foreach ($nothing as $k=>$v) { if ($v === 'choose' or $v === 'choosedots') { $nothing[$k] = get_string('choosedots'); } } $options = $nothing + $options; // keep keys, do not override } else if (is_string($nothing) and $nothing !== '') { // BC $options = array(''=>$nothing) + $options; } // we may accept more values if multiple attribute specified $selected = (array)$selected; foreach ($selected as $k=>$v) { $selected[$k] = (string)$v; } if (!isset($attributes['id'])) { $id = 'menu'.$name; // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading $id = str_replace('[', '', $id); $id = str_replace(']', '', $id); $attributes['id'] = $id; } if (!isset($attributes['class'])) { $class = 'menu'.$name; // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading $class = str_replace('[', '', $class); $class = str_replace(']', '', $class); $attributes['class'] = $class; } $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always $attributes['name'] = $name; if (!empty($attributes['disabled'])) { $attributes['disabled'] = 'disabled'; } else { unset($attributes['disabled']); } $output = ''; foreach ($options as $value=>$label) { if (is_array($label)) { // ignore key, it just has to be unique $output .= self::select_optgroup(key($label), current($label), $selected); } else { $output .= self::select_option($label, $value, $selected); } } return self::tag('select', $output, $attributes); } /** * Returns HTML to display a select box option. * * @param string $label The label to display as the option. * @param string|int $value The value the option represents * @param array $selected An array of selected options * @return string HTML fragment */ private static function select_option($label, $value, array $selected) { $attributes = array(); $value = (string)$value; if (in_array($value, $selected, true)) { $attributes['selected'] = 'selected'; } $attributes['value'] = $value; return self::tag('option', $label, $attributes); } /** * Returns HTML to display a select box option group. * * @param string $groupname The label to use for the group * @param array $options The options in the group * @param array $selected An array of selected values. * @return string HTML fragment. */ private static function select_optgroup($groupname, $options, array $selected) { if (empty($options)) { return ''; } $attributes = array('label'=>$groupname); $output = ''; foreach ($options as $value=>$label) { $output .= self::select_option($label, $value, $selected); } return self::tag('optgroup', $output, $attributes); } /** * This is a shortcut for making an hour selector menu. * * @param string $type The type of selector (years, months, days, hours, minutes) * @param string $name fieldname * @param int $currenttime A default timestamp in GMT * @param int $step minute spacing * @param array $attributes - html select element attributes * @return HTML fragment */ public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) { if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); $userdatetype = $type; $timeunits = array(); switch ($type) { case 'years': for ($i=1970; $i<=2020; $i++) { $timeunits[$i] = $i; } $userdatetype = 'year'; break; case 'months': for ($i=1; $i<=12; $i++) { $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B"); } $userdatetype = 'month'; $currentdate['month'] = (int)$currentdate['mon']; break; case 'days': for ($i=1; $i<=31; $i++) { $timeunits[$i] = $i; } $userdatetype = 'mday'; break; case 'hours': for ($i=0; $i<=23; $i++) { $timeunits[$i] = sprintf("%02d",$i); } break; case 'minutes': if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step; } for ($i=0; $i<=59; $i+=$step) { $timeunits[$i] = sprintf("%02d",$i); } break; default: throw new coding_exception("Time type $type is not supported by html_writer::select_time()."); } if (empty($attributes['id'])) { $attributes['id'] = self::random_id('ts_'); } $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes); $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide')); return $label.$timerselector; } /** * Shortcut for quick making of lists * * Note: 'list' is a reserved keyword ;-) * * @param array $items * @param array $attributes * @param string $tag ul or ol * @return string */ public static function alist(array $items, array $attributes = null, $tag = 'ul') { $output = html_writer::start_tag($tag, $attributes)."\n"; foreach ($items as $item) { $output .= html_writer::tag('li', $item)."\n"; } $output .= html_writer::end_tag($tag); return $output; } /** * Returns hidden input fields created from url parameters. * * @param moodle_url $url * @param array $exclude list of excluded parameters * @return string HTML fragment */ public static function input_hidden_params(moodle_url $url, array $exclude = null) { $exclude = (array)$exclude; $params = $url->params(); foreach ($exclude as $key) { unset($params[$key]); } $output = ''; foreach ($params as $key => $value) { $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value); $output .= self::empty_tag('input', $attributes)."\n"; } return $output; } /** * Generate a script tag containing the the specified code. * * @param string $jscode the JavaScript code * @param moodle_url|string $url optional url of the external script, $code ignored if specified * @return string HTML, the code wrapped in <script> tags. */ public static function script($jscode, $url=null) { if ($jscode) { $attributes = array('type'=>'text/javascript'); return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n"; } else if ($url) { $attributes = array('type'=>'text/javascript', 'src'=>$url); return self::tag('script', '', $attributes) . "\n"; } else { return ''; } } /** * Renders HTML table * * This method may modify the passed instance by adding some default properties if they are not set yet. * If this is not what you want, you should make a full clone of your data before passing them to this * method. In most cases this is not an issue at all so we do not clone by default for performance * and memory consumption reasons. * * Please do not use .r0/.r1 for css, as they will be removed in Moodle 2.9. * @todo MDL-43902 , remove r0 and r1 from tr classes. * * @param html_table $table data to be rendered * @return string HTML code */ public static function table(html_table $table) { // prepare table data and populate missing properties with reasonable defaults if (!empty($table->align)) { foreach ($table->align as $key => $aa) { if ($aa) { $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages } else { $table->align[$key] = null; } } } if (!empty($table->size)) { foreach ($table->size as $key => $ss) { if ($ss) { $table->size[$key] = 'width:'. $ss .';'; } else { $table->size[$key] = null; } } } if (!empty($table->wrap)) { foreach ($table->wrap as $key => $ww) { if ($ww) { $table->wrap[$key] = 'white-space:nowrap;'; } else { $table->wrap[$key] = ''; } } } if (!empty($table->head)) { foreach ($table->head as $key => $val) { if (!isset($table->align[$key])) { $table->align[$key] = null; } if (!isset($table->size[$key])) { $table->size[$key] = null; } if (!isset($table->wrap[$key])) { $table->wrap[$key] = null; } } } if (empty($table->attributes['class'])) { $table->attributes['class'] = 'generaltable'; } if (!empty($table->tablealign)) { $table->attributes['class'] .= ' boxalign' . $table->tablealign; } // explicitly assigned properties override those defined via $table->attributes $table->attributes['class'] = trim($table->attributes['class']); $attributes = array_merge($table->attributes, array( 'id' => $table->id, 'width' => $table->width, 'summary' => $table->summary, 'cellpadding' => $table->cellpadding, 'cellspacing' => $table->cellspacing, )); $output = html_writer::start_tag('table', $attributes) . "\n"; $countcols = 0; if (!empty($table->head)) { $countcols = count($table->head); $output .= html_writer::start_tag('thead', array()) . "\n"; $output .= html_writer::start_tag('tr', array()) . "\n"; $keys = array_keys($table->head); $lastkey = end($keys); foreach ($table->head as $key => $heading) { // Convert plain string headings into html_table_cell objects if (!($heading instanceof html_table_cell)) { $headingtext = $heading; $heading = new html_table_cell(); $heading->text = $headingtext; $heading->header = true; } if ($heading->header !== false) { $heading->header = true; } if ($heading->header && empty($heading->scope)) { $heading->scope = 'col'; } $heading->attributes['class'] .= ' header c' . $key; if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) { $heading->colspan = $table->headspan[$key]; $countcols += $table->headspan[$key] - 1; } if ($key == $lastkey) { $heading->attributes['class'] .= ' lastcol'; } if (isset($table->colclasses[$key])) { $heading->attributes['class'] .= ' ' . $table->colclasses[$key]; } $heading->attributes['class'] = trim($heading->attributes['class']); $attributes = array_merge($heading->attributes, array( 'style' => $table->align[$key] . $table->size[$key] . $heading->style, 'scope' => $heading->scope, 'colspan' => $heading->colspan, )); $tagtype = 'td'; if ($heading->header === true) { $tagtype = 'th'; } $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n"; } $output .= html_writer::end_tag('tr') . "\n"; $output .= html_writer::end_tag('thead') . "\n"; if (empty($table->data)) { // For valid XHTML strict every table must contain either a valid tr // or a valid tbody... both of which must contain a valid td $output .= html_writer::start_tag('tbody', array('class' => 'empty')); $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head)))); $output .= html_writer::end_tag('tbody'); } } if (!empty($table->data)) { $oddeven = 1; $keys = array_keys($table->data); $lastrowkey = end($keys); $output .= html_writer::start_tag('tbody', array()); foreach ($table->data as $key => $row) { if (($row === 'hr') && ($countcols)) { $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols)); } else { // Convert array rows to html_table_rows and cell strings to html_table_cell objects if (!($row instanceof html_table_row)) { $newrow = new html_table_row(); foreach ($row as $cell) { if (!($cell instanceof html_table_cell)) { $cell = new html_table_cell($cell); } $newrow->cells[] = $cell; } $row = $newrow; } $oddeven = $oddeven ? 0 : 1; if (isset($table->rowclasses[$key])) { $row->attributes['class'] .= ' ' . $table->rowclasses[$key]; } $row->attributes['class'] .= ' r' . $oddeven; if ($key == $lastrowkey) { $row->attributes['class'] .= ' lastrow'; } // Explicitly assigned properties should override those defined in the attributes. $row->attributes['class'] = trim($row->attributes['class']); $trattributes = array_merge($row->attributes, array( 'id' => $row->id, 'style' => $row->style, )); $output .= html_writer::start_tag('tr', $trattributes) . "\n"; $keys2 = array_keys($row->cells); $lastkey = end($keys2); $gotlastkey = false; //flag for sanity checking foreach ($row->cells as $key => $cell) { if ($gotlastkey) { //This should never happen. Why do we have a cell after the last cell? mtrace("A cell with key ($key) was found after the last key ($lastkey)"); } if (!($cell instanceof html_table_cell)) { $mycell = new html_table_cell(); $mycell->text = $cell; $cell = $mycell; } if (($cell->header === true) && empty($cell->scope)) { $cell->scope = 'row'; } if (isset($table->colclasses[$key])) { $cell->attributes['class'] .= ' ' . $table->colclasses[$key]; } $cell->attributes['class'] .= ' cell c' . $key; if ($key == $lastkey) { $cell->attributes['class'] .= ' lastcol'; $gotlastkey = true; } $tdstyle = ''; $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : ''; $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : ''; $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : ''; $cell->attributes['class'] = trim($cell->attributes['class']); $tdattributes = array_merge($cell->attributes, array( 'style' => $tdstyle . $cell->style, 'colspan' => $cell->colspan, 'rowspan' => $cell->rowspan, 'id' => $cell->id, 'abbr' => $cell->abbr, 'scope' => $cell->scope, )); $tagtype = 'td'; if ($cell->header === true) { $tagtype = 'th'; } $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n"; } } $output .= html_writer::end_tag('tr') . "\n"; } $output .= html_writer::end_tag('tbody') . "\n"; } $output .= html_writer::end_tag('table') . "\n"; return $output; } /** * Renders form element label * * By default, the label is suffixed with a label separator defined in the * current language pack (colon by default in the English lang pack). * Adding the colon can be explicitly disabled if needed. Label separators * are put outside the label tag itself so they are not read by * screenreaders (accessibility). * * Parameter $for explicitly associates the label with a form control. When * set, the value of this attribute must be the same as the value of * the id attribute of the form control in the same document. When null, * the label being defined is associated with the control inside the label * element. * * @param string $text content of the label tag * @param string|null $for id of the element this label is associated with, null for no association * @param bool $colonize add label separator (colon) to the label text, if it is not there yet * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a') * @return string HTML of the label element */ public static function label($text, $for, $colonize = true, array $attributes=array()) { if (!is_null($for)) { $attributes = array_merge($attributes, array('for' => $for)); } $text = trim($text); $label = self::tag('label', $text, $attributes); // TODO MDL-12192 $colonize disabled for now yet // if (!empty($text) and $colonize) { // // the $text may end with the colon already, though it is bad string definition style // $colon = get_string('labelsep', 'langconfig'); // if (!empty($colon)) { // $trimmed = trim($colon); // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) { // //debugging('The label text should not end with colon or other label separator, // // please fix the string definition.', DEBUG_DEVELOPER); // } else { // $label .= $colon; // } // } // } return $label; } /** * Combines a class parameter with other attributes. Aids in code reduction * because the class parameter is very frequently used. * * If the class attribute is specified both in the attributes and in the * class parameter, the two values are combined with a space between. * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return array Attributes (or null if still none) */ private static function add_class($class = '', array $attributes = null) { if ($class !== '') { $classattribute = array('class' => $class); if ($attributes) { if (array_key_exists('class', $attributes)) { $attributes['class'] = trim($attributes['class'] . ' ' . $class); } else { $attributes = $classattribute + $attributes; } } else { $attributes = $classattribute; } } return $attributes; } /** * Creates a <div> tag. (Shortcut function.) * * @param string $content HTML content of tag * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for div */ public static function div($content, $class = '', array $attributes = null) { return self::tag('div', $content, self::add_class($class, $attributes)); } /** * Starts a <div> tag. (Shortcut function.) * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for open div tag */ public static function start_div($class = '', array $attributes = null) { return self::start_tag('div', self::add_class($class, $attributes)); } /** * Ends a <div> tag. (Shortcut function.) * * @return string HTML code for close div tag */ public static function end_div() { return self::end_tag('div'); } /** * Creates a <span> tag. (Shortcut function.) * * @param string $content HTML content of tag * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for span */ public static function span($content, $class = '', array $attributes = null) { return self::tag('span', $content, self::add_class($class, $attributes)); } /** * Starts a <span> tag. (Shortcut function.) * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for open span tag */ public static function start_span($class = '', array $attributes = null) { return self::start_tag('span', self::add_class($class, $attributes)); } /** * Ends a <span> tag. (Shortcut function.) * * @return string HTML code for close span tag */ public static function end_span() { return self::end_tag('span'); } } /** * Simple javascript output class * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class js_writer { /** * Returns javascript code calling the function * * @param string $function function name, can be complex like Y.Event.purgeElement * @param array $arguments parameters * @param int $delay execution delay in seconds * @return string JS code fragment */ public static function function_call($function, array $arguments = null, $delay=0) { if ($arguments) { $arguments = array_map('json_encode', convert_to_array($arguments)); $arguments = implode(', ', $arguments); } else { $arguments = ''; } $js = "$function($arguments);"; if ($delay) { $delay = $delay * 1000; // in miliseconds $js = "setTimeout(function() { $js }, $delay);"; } return $js . "\n"; } /** * Special function which adds Y as first argument of function call. * * @param string $function The function to call * @param array $extraarguments Any arguments to pass to it * @return string Some JS code */ public static function function_call_with_Y($function, array $extraarguments = null) { if ($extraarguments) { $extraarguments = array_map('json_encode', convert_to_array($extraarguments)); $arguments = 'Y, ' . implode(', ', $extraarguments); } else { $arguments = 'Y'; } return "$function($arguments);\n"; } /** * Returns JavaScript code to initialise a new object * * @param string $var If it is null then no var is assigned the new object. * @param string $class The class to initialise an object for. * @param array $arguments An array of args to pass to the init method. * @param array $requirements Any modules required for this class. * @param int $delay The delay before initialisation. 0 = no delay. * @return string Some JS code */ public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) { if (is_array($arguments)) { $arguments = array_map('json_encode', convert_to_array($arguments)); $arguments = implode(', ', $arguments); } if ($var === null) { $js = "new $class(Y, $arguments);"; } else if (strpos($var, '.')!==false) { $js = "$var = new $class(Y, $arguments);"; } else { $js = "var $var = new $class(Y, $arguments);"; } if ($delay) { $delay = $delay * 1000; // in miliseconds $js = "setTimeout(function() { $js }, $delay);"; } if (count($requirements) > 0) { $requirements = implode("', '", $requirements); $js = "Y.use('$requirements', function(Y){ $js });"; } return $js."\n"; } /** * Returns code setting value to variable * * @param string $name * @param mixed $value json serialised value * @param bool $usevar add var definition, ignored for nested properties * @return string JS code fragment */ public static function set_variable($name, $value, $usevar = true) { $output = ''; if ($usevar) { if (strpos($name, '.')) { $output .= ''; } else { $output .= 'var '; } } $output .= "$name = ".json_encode($value).";"; return $output; } /** * Writes event handler attaching code * * @param array|string $selector standard YUI selector for elements, may be * array or string, element id is in the form "#idvalue" * @param string $event A valid DOM event (click, mousedown, change etc.) * @param string $function The name of the function to call * @param array $arguments An optional array of argument parameters to pass to the function * @return string JS code fragment */ public static function event_handler($selector, $event, $function, array $arguments = null) { $selector = json_encode($selector); $output = "Y.on('$event', $function, $selector, null"; if (!empty($arguments)) { $output .= ', ' . json_encode($arguments); } return $output . ");\n"; } } /** * Holds all the information required to render a <table> by {@link core_renderer::table()} * * Example of usage: * $t = new html_table(); * ... // set various properties of the object $t as described below * echo html_writer::table($t); * * @copyright 2009 David Mudrak <david.mudrak@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table { /** * @var string Value to use for the id attribute of the table */ public $id = null; /** * @var array Attributes of HTML attributes for the <table> element */ public $attributes = array(); /** * @var array An array of headings. The n-th array item is used as a heading of the n-th column. * For more control over the rendering of the headers, an array of html_table_cell objects * can be passed instead of an array of strings. * * Example of usage: * $t->head = array('Student', 'Grade'); */ public $head; /** * @var array An array that can be used to make a heading span multiple columns. * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns, * the same heading is used. Therefore, {@link html_table::$head} should consist of two items. * * Example of usage: * $t->headspan = array(2,1); */ public $headspan; /** * @var array An array of column alignments. * The value is used as CSS 'text-align' property. Therefore, possible * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective * of a left-to-right (LTR) language. For RTL, the values are flipped automatically. * * Examples of usage: * $t->align = array(null, 'right'); * or * $t->align[1] = 'right'; */ public $align; /** * @var array The value is used as CSS 'size' property. * * Examples of usage: * $t->size = array('50%', '50%'); * or * $t->size[1] = '120px'; */ public $size; /** * @var array An array of wrapping information. * The only possible value is 'nowrap' that sets the * CSS property 'white-space' to the value 'nowrap' in the given column. * * Example of usage: * $t->wrap = array(null, 'nowrap'); */ public $wrap; /** * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have * $head specified, the string 'hr' (for horizontal ruler) can be used * instead of an array of cells data resulting in a divider rendered. * * Example of usage with array of arrays: * $row1 = array('Harry Potter', '76 %'); * $row2 = array('Hermione Granger', '100 %'); * $t->data = array($row1, $row2); * * Example with array of html_table_row objects: (used for more fine-grained control) * $cell1 = new html_table_cell(); * $cell1->text = 'Harry Potter'; * $cell1->colspan = 2; * $row1 = new html_table_row(); * $row1->cells[] = $cell1; * $cell2 = new html_table_cell(); * $cell2->text = 'Hermione Granger'; * $cell3 = new html_table_cell(); * $cell3->text = '100 %'; * $row2 = new html_table_row(); * $row2->cells = array($cell2, $cell3); * $t->data = array($row1, $row2); */ public $data; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Width of the table, percentage of the page preferred. */ public $width = null; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default). */ public $tablealign = null; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var int Padding on each cell, in pixels */ public $cellpadding = null; /** * @var int Spacing between cells, in pixels * @deprecated since Moodle 2.0. Styling should be in the CSS. */ public $cellspacing = null; /** * @var array Array of classes to add to particular rows, space-separated string. * Classes 'r0' or 'r1' are added automatically for every odd or even row, * respectively. Class 'lastrow' is added automatically for the last row * in the table. * * Example of usage: * $t->rowclasses[9] = 'tenth' */ public $rowclasses; /** * @var array An array of classes to add to every cell in a particular column, * space-separated string. Class 'cell' is added automatically by the renderer. * Classes 'c0' or 'c1' are added automatically for every odd or even column, * respectively. Class 'lastcol' is added automatically for all last cells * in a row. * * Example of usage: * $t->colclasses = array(null, 'grade'); */ public $colclasses; /** * @var string Description of the contents for screen readers. */ public $summary; /** * Constructor */ public function __construct() { $this->attributes['class'] = ''; } } /** * Component representing a table row. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table_row { /** * @var string Value to use for the id attribute of the row. */ public $id = null; /** * @var array Array of html_table_cell objects */ public $cells = array(); /** * @var string Value to use for the style attribute of the table row */ public $style = null; /** * @var array Attributes of additional HTML attributes for the <tr> element */ public $attributes = array(); /** * Constructor * @param array $cells */ public function __construct(array $cells=null) { $this->attributes['class'] = ''; $cells = (array)$cells; foreach ($cells as $cell) { if ($cell instanceof html_table_cell) { $this->cells[] = $cell; } else { $this->cells[] = new html_table_cell($cell); } } } } /** * Component representing a table cell. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table_cell { /** * @var string Value to use for the id attribute of the cell. */ public $id = null; /** * @var string The contents of the cell. */ public $text; /** * @var string Abbreviated version of the contents of the cell. */ public $abbr = null; /** * @var int Number of columns this cell should span. */ public $colspan = null; /** * @var int Number of rows this cell should span. */ public $rowspan = null; /** * @var string Defines a way to associate header cells and data cells in a table. */ public $scope = null; /** * @var bool Whether or not this cell is a header cell. */ public $header = null; /** * @var string Value to use for the style attribute of the table cell */ public $style = null; /** * @var array Attributes of additional HTML attributes for the <td> element */ public $attributes = array(); /** * Constructs a table cell * * @param string $text */ public function __construct($text = null) { $this->text = $text; $this->attributes['class'] = ''; } } /** * Component representing a paging bar. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class paging_bar implements renderable { /** * @var int The maximum number of pagelinks to display. */ public $maxdisplay = 18; /** * @var int The total number of entries to be pages through.. */ public $totalcount; /** * @var int The page you are currently viewing. */ public $page; /** * @var int The number of entries that should be shown per page. */ public $perpage; /** * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar, * an equals sign and the page number. * If this is a moodle_url object then the pagevar param will be replaced by * the page no, for each page. */ public $baseurl; /** * @var string This is the variable name that you use for the pagenumber in your * code (ie. 'tablepage', 'blogpage', etc) */ public $pagevar; /** * @var string A HTML link representing the "previous" page. */ public $previouslink = null; /** * @var string A HTML link representing the "next" page. */ public $nextlink = null; /** * @var string A HTML link representing the first page. */ public $firstlink = null; /** * @var string A HTML link representing the last page. */ public $lastlink = null; /** * @var array An array of strings. One of them is just a string: the current page */ public $pagelinks = array(); /** * Constructor paging_bar with only the required params. * * @param int $totalcount The total number of entries available to be paged through * @param int $page The page you are currently viewing * @param int $perpage The number of entries that should be shown per page * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added * @param string $pagevar name of page parameter that holds the page number */ public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') { $this->totalcount = $totalcount; $this->page = $page; $this->perpage = $perpage; $this->baseurl = $baseurl; $this->pagevar = $pagevar; } /** * Prepares the paging bar for output. * * This method validates the arguments set up for the paging bar and then * produces fragments of HTML to assist display later on. * * @param renderer_base $output * @param moodle_page $page * @param string $target * @throws coding_exception */ public function prepare(renderer_base $output, moodle_page $page, $target) { if (!isset($this->totalcount) || is_null($this->totalcount)) { throw new coding_exception('paging_bar requires a totalcount value.'); } if (!isset($this->page) || is_null($this->page)) { throw new coding_exception('paging_bar requires a page value.'); } if (empty($this->perpage)) { throw new coding_exception('paging_bar requires a perpage value.'); } if (empty($this->baseurl)) { throw new coding_exception('paging_bar requires a baseurl value.'); } if ($this->totalcount > $this->perpage) { $pagenum = $this->page - 1; if ($this->page > 0) { $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous')); } if ($this->perpage > 0) { $lastpage = ceil($this->totalcount / $this->perpage); } else { $lastpage = 1; } if ($this->page > round(($this->maxdisplay/3)*2)) { $currpage = $this->page - round($this->maxdisplay/3); $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first')); } else { $currpage = 0; } $displaycount = $displaypage = 0; while ($displaycount < $this->maxdisplay and $currpage < $lastpage) { $displaypage = $currpage + 1; if ($this->page == $currpage) { $this->pagelinks[] = html_writer::span($displaypage, 'current-page'); } else { $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage); $this->pagelinks[] = $pagelink; } $displaycount++; $currpage++; } if ($currpage < $lastpage) { $lastpageactual = $lastpage - 1; $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last')); } $pagenum = $this->page + 1; if ($pagenum != $displaypage) { $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next')); } } } } /** * This class represents how a block appears on a page. * * During output, each block instance is asked to return a block_contents object, * those are then passed to the $OUTPUT->block function for display. * * contents should probably be generated using a moodle_block_..._renderer. * * Other block-like things that need to appear on the page, for example the * add new block UI, are also represented as block_contents objects. * * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class block_contents { /** Used when the block cannot be collapsed **/ const NOT_HIDEABLE = 0; /** Used when the block can be collapsed but currently is not **/ const VISIBLE = 1; /** Used when the block has been collapsed **/ const HIDDEN = 2; /** * @var int Used to set $skipid. */ protected static $idcounter = 1; /** * @var int All the blocks (or things that look like blocks) printed on * a page are given a unique number that can be used to construct id="" attributes. * This is set automatically be the {@link prepare()} method. * Do not try to set it manually. */ public $skipid; /** * @var int If this is the contents of a real block, this should be set * to the block_instance.id. Otherwise this should be set to 0. */ public $blockinstanceid = 0; /** * @var int If this is a real block instance, and there is a corresponding * block_position.id for the block on this page, this should be set to that id. * Otherwise it should be 0. */ public $blockpositionid = 0; /** * @var array An array of attribute => value pairs that are put on the outer div of this * block. {@link $id} and {@link $classes} attributes should be set separately. */ public $attributes; /** * @var string The title of this block. If this came from user input, it should already * have had format_string() processing done on it. This will be output inside * <h2> tags. Please do not cause invalid XHTML. */ public $title = ''; /** * @var string The label to use when the block does not, or will not have a visible title. * You should never set this as well as title... it will just be ignored. */ public $arialabel = ''; /** * @var string HTML for the content */ public $content = ''; /** * @var array An alternative to $content, it you want a list of things with optional icons. */ public $footer = ''; /** * @var string Any small print that should appear under the block to explain * to the teacher about the block, for example 'This is a sticky block that was * added in the system context.' */ public $annotation = ''; /** * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether * the user can toggle whether this block is visible. */ public $collapsible = self::NOT_HIDEABLE; /** * Set this to true if the block is dockable. * @var bool */ public $dockable = false; /** * @var array A (possibly empty) array of editing controls. Each element of * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption). * $icon is the icon name. Fed to $OUTPUT->pix_url. */ public $controls = array(); /** * Create new instance of block content * @param array $attributes */ public function __construct(array $attributes = null) { $this->skipid = self::$idcounter; self::$idcounter += 1; if ($attributes) { // standard block $this->attributes = $attributes; } else { // simple "fake" blocks used in some modules and "Add new block" block $this->attributes = array('class'=>'block'); } } /** * Add html class to block * * @param string $class */ public function add_class($class) { $this->attributes['class'] .= ' '.$class; } } /** * This class represents a target for where a block can go when it is being moved. * * This needs to be rendered as a form with the given hidden from fields, and * clicking anywhere in the form should submit it. The form action should be * $PAGE->url. * * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class block_move_target { /** * @var moodle_url Move url */ public $url; /** * Constructor * @param moodle_url $url */ public function __construct(moodle_url $url) { $this->url = $url; } } /** * Custom menu item * * This class is used to represent one item within a custom menu that may or may * not have children. * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class custom_menu_item implements renderable { /** * @var string The text to show for the item */ protected $text; /** * @var moodle_url The link to give the icon if it has no children */ protected $url; /** * @var string A title to apply to the item. By default the text */ protected $title; /** * @var int A sort order for the item, not necessary if you order things in * the CFG var. */ protected $sort; /** * @var custom_menu_item A reference to the parent for this item or NULL if * it is a top level item */ protected $parent; /** * @var array A array in which to store children this item has. */ protected $children = array(); /** * @var int A reference to the sort var of the last child that was added */ protected $lastsort = 0; /** * Constructs the new custom menu item * * @param string $text * @param moodle_url $url A moodle url to apply as the link for this item [Optional] * @param string $title A title to apply to this item [Optional] * @param int $sort A sort or to use if we need to sort differently [Optional] * @param custom_menu_item $parent A reference to the parent custom_menu_item this child * belongs to, only if the child has a parent. [Optional] */ public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) { $this->text = $text; $this->url = $url; $this->title = $title; $this->sort = (int)$sort; $this->parent = $parent; } /** * Adds a custom menu item as a child of this node given its properties. * * @param string $text * @param moodle_url $url * @param string $title * @param int $sort * @return custom_menu_item */ public function add($text, moodle_url $url = null, $title = null, $sort = null) { $key = count($this->children); if (empty($sort)) { $sort = $this->lastsort + 1; } $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this); $this->lastsort = (int)$sort; return $this->children[$key]; } /** * Removes a custom menu item that is a child or descendant to the current menu. * * Returns true if child was found and removed. * * @param custom_menu_item $menuitem * @return bool */ public function remove_child(custom_menu_item $menuitem) { $removed = false; if (($key = array_search($menuitem, $this->children)) !== false) { unset($this->children[$key]); $this->children = array_values($this->children); $removed = true; } else { foreach ($this->children as $child) { if ($removed = $child->remove_child($menuitem)) { break; } } } return $removed; } /** * Returns the text for this item * @return string */ public function get_text() { return $this->text; } /** * Returns the url for this item * @return moodle_url */ public function get_url() { return $this->url; } /** * Returns the title for this item * @return string */ public function get_title() { return $this->title; } /** * Sorts and returns the children for this item * @return array */ public function get_children() { $this->sort(); return $this->children; } /** * Gets the sort order for this child * @return int */ public function get_sort_order() { return $this->sort; } /** * Gets the parent this child belong to * @return custom_menu_item */ public function get_parent() { return $this->parent; } /** * Sorts the children this item has */ public function sort() { usort($this->children, array('custom_menu','sort_custom_menu_items')); } /** * Returns true if this item has any children * @return bool */ public function has_children() { return (count($this->children) > 0); } /** * Sets the text for the node * @param string $text */ public function set_text($text) { $this->text = (string)$text; } /** * Sets the title for the node * @param string $title */ public function set_title($title) { $this->title = (string)$title; } /** * Sets the url for the node * @param moodle_url $url */ public function set_url(moodle_url $url) { $this->url = $url; } } /** * Custom menu class * * This class is used to operate a custom menu that can be rendered for the page. * The custom menu is built using $CFG->custommenuitems and is a structured collection * of custom_menu_item nodes that can be rendered by the core renderer. * * To configure the custom menu: * Settings: Administration > Appearance > Themes > Theme settings * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class custom_menu extends custom_menu_item { /** * @var string The language we should render for, null disables multilang support. */ protected $currentlanguage = null; /** * Creates the custom menu * * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()} * @param string $currentlanguage the current language code, null disables multilang support */ public function __construct($definition = '', $currentlanguage = null) { $this->currentlanguage = $currentlanguage; parent::__construct('root'); // create virtual root element of the menu if (!empty($definition)) { $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage)); } } /** * Overrides the children of this custom menu. Useful when getting children * from $CFG->custommenuitems * * @param array $children */ public function override_children(array $children) { $this->children = array(); foreach ($children as $child) { if ($child instanceof custom_menu_item) { $this->children[] = $child; } } } /** * Converts a string into a structured array of custom_menu_items which can * then be added to a custom menu. * * Structure: * text|url|title|langs * The number of hyphens at the start determines the depth of the item. The * languages are optional, comma separated list of languages the line is for. * * Example structure: * First level first item|http://www.moodle.com/ * -Second level first item|http://www.moodle.com/partners/ * -Second level second item|http://www.moodle.com/hq/ * --Third level first item|http://www.moodle.com/jobs/ * -Second level third item|http://www.moodle.com/development/ * First level second item|http://www.moodle.com/feedback/ * First level third item * English only|http://moodle.com|English only item|en * German only|http://moodle.de|Deutsch|de,de_du,de_kids * * * @static * @param string $text the menu items definition * @param string $language the language code, null disables multilang support * @return array */ public static function convert_text_to_menu_nodes($text, $language = null) { $root = new custom_menu(); $lastitem = $root; $lastdepth = 0; $hiddenitems = array(); $lines = explode("\n", $text); foreach ($lines as $linenumber => $line) { $line = trim($line); if (strlen($line) == 0) { continue; } // Parse item settings. $itemtext = null; $itemurl = null; $itemtitle = null; $itemvisible = true; $settings = explode('|', $line); foreach ($settings as $i => $setting) { $setting = trim($setting); if (!empty($setting)) { switch ($i) { case 0: $itemtext = ltrim($setting, '-'); $itemtitle = $itemtext; break; case 1: $itemurl = new moodle_url($setting); break; case 2: $itemtitle = $setting; break; case 3: if (!empty($language)) { $itemlanguages = array_map('trim', explode(',', $setting)); $itemvisible &= in_array($language, $itemlanguages); } break; } } } // Get depth of new item. preg_match('/^(\-*)/', $line, $match); $itemdepth = strlen($match[1]) + 1; // Find parent item for new item. while (($lastdepth - $itemdepth) >= 0) { $lastitem = $lastitem->get_parent(); $lastdepth--; } $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1); $lastdepth++; if (!$itemvisible) { $hiddenitems[] = $lastitem; } } foreach ($hiddenitems as $item) { $item->parent->remove_child($item); } return $root->get_children(); } /** * Sorts two custom menu items * * This function is designed to be used with the usort method * usort($this->children, array('custom_menu','sort_custom_menu_items')); * * @static * @param custom_menu_item $itema * @param custom_menu_item $itemb * @return int */ public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) { $itema = $itema->get_sort_order(); $itemb = $itemb->get_sort_order(); if ($itema == $itemb) { return 0; } return ($itema > $itemb) ? +1 : -1; } } /** * Stores one tab * * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core */ class tabobject implements renderable { /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */ var $id; /** @var moodle_url|string link */ var $link; /** @var string text on the tab */ var $text; /** @var string title under the link, by defaul equals to text */ var $title; /** @var bool whether to display a link under the tab name when it's selected */ var $linkedwhenselected = false; /** @var bool whether the tab is inactive */ var $inactive = false; /** @var bool indicates that this tab's child is selected */ var $activated = false; /** @var bool indicates that this tab is selected */ var $selected = false; /** @var array stores children tabobjects */ var $subtree = array(); /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */ var $level = 1; /** * Constructor * * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs * @param string|moodle_url $link * @param string $text text on the tab * @param string $title title under the link, by defaul equals to text * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected */ public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) { $this->id = $id; $this->link = $link; $this->text = $text; $this->title = $title ? $title : $text; $this->linkedwhenselected = $linkedwhenselected; } /** * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated * * @param string $selected the id of the selected tab (whatever row it's on), * if null marks all tabs as unselected * @return bool whether this tab is selected or contains selected tab in its subtree */ protected function set_selected($selected) { if ((string)$selected === (string)$this->id) { $this->selected = true; // This tab is selected. No need to travel through subtree. return true; } foreach ($this->subtree as $subitem) { if ($subitem->set_selected($selected)) { // This tab has child that is selected. Mark it as activated. No need to check other children. $this->activated = true; return true; } } return false; } /** * Travels through tree and finds a tab with specified id * * @param string $id * @return tabtree|null */ public function find($id) { if ((string)$this->id === (string)$id) { return $this; } foreach ($this->subtree as $tab) { if ($obj = $tab->find($id)) { return $obj; } } return null; } /** * Allows to mark each tab's level in the tree before rendering. * * @param int $level */ protected function set_level($level) { $this->level = $level; foreach ($this->subtree as $tab) { $tab->set_level($level + 1); } } } /** * Stores tabs list * * Example how to print a single line tabs: * $rows = array( * new tabobject(...), * new tabobject(...) * ); * echo $OUTPUT->tabtree($rows, $selectedid); * * Multiple row tabs may not look good on some devices but if you want to use them * you can specify ->subtree for the active tabobject. * * @copyright 2013 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.5 * @package core * @category output */ class tabtree extends tabobject { /** * Constuctor * * It is highly recommended to call constructor when list of tabs is already * populated, this way you ensure that selected and inactive tabs are located * and attribute level is set correctly. * * @param array $tabs array of tabs, each of them may have it's own ->subtree * @param string|null $selected which tab to mark as selected, all parent tabs will * automatically be marked as activated * @param array|string|null $inactive list of ids of inactive tabs, regardless of * their level. Note that you can as weel specify tabobject::$inactive for separate instances */ public function __construct($tabs, $selected = null, $inactive = null) { $this->subtree = $tabs; if ($selected !== null) { $this->set_selected($selected); } if ($inactive !== null) { if (is_array($inactive)) { foreach ($inactive as $id) { if ($tab = $this->find($id)) { $tab->inactive = true; } } } else if ($tab = $this->find($inactive)) { $tab->inactive = true; } } $this->set_level(0); } } /** * An action menu. * * This action menu component takes a series of primary and secondary actions. * The primary actions are displayed permanently and the secondary attributes are displayed within a drop * down menu. * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu implements renderable { /** * Top right alignment. */ const TL = 1; /** * Top right alignment. */ const TR = 2; /** * Top right alignment. */ const BL = 3; /** * Top right alignment. */ const BR = 4; /** * The instance number. This is unique to this instance of the action menu. * @var int */ protected $instance = 0; /** * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions. * @var array */ protected $primaryactions = array(); /** * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions. * @var array */ protected $secondaryactions = array(); /** * An array of attributes added to the container of the action menu. * Initialised with defaults during construction. * @var array */ public $attributes = array(); /** * An array of attributes added to the container of the primary actions. * Initialised with defaults during construction. * @var array */ public $attributesprimary = array(); /** * An array of attributes added to the container of the secondary actions. * Initialised with defaults during construction. * @var array */ public $attributessecondary = array(); /** * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu. * @var array */ public $actiontext = null; /** * An icon to use for the toggling the secondary menu (dropdown). * @var actionicon */ public $actionicon; /** * Any text to use for the toggling the secondary menu (dropdown). * @var menutrigger */ public $menutrigger = ''; /** * Place the action menu before all other actions. * @var prioritise */ public $prioritise = false; /** * Constructs the action menu with the given items. * * @param array $actions An array of actions. */ public function __construct(array $actions = array()) { static $initialised = 0; $this->instance = $initialised; $initialised++; $this->attributes = array( 'id' => 'action-menu-'.$this->instance, 'class' => 'moodle-actionmenu', 'data-enhance' => 'moodle-core-actionmenu' ); $this->attributesprimary = array( 'id' => 'action-menu-'.$this->instance.'-menubar', 'class' => 'menubar', 'role' => 'menubar' ); $this->attributessecondary = array( 'id' => 'action-menu-'.$this->instance.'-menu', 'class' => 'menu', 'data-rel' => 'menu-content', 'aria-labelledby' => 'action-menu-toggle-'.$this->instance, 'role' => 'menu' ); $this->set_alignment(self::TR, self::BR); foreach ($actions as $action) { $this->add($action); } } public function set_menu_trigger($trigger) { $this->menutrigger = $trigger; } /** * Initialises JS required fore the action menu. * The JS is only required once as it manages all action menu's on the page. * * @param moodle_page $page */ public function initialise_js(moodle_page $page) { static $initialised = false; if (!$initialised) { $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init'); $initialised = true; } } /** * Adds an action to this action menu. * * @param action_menu_link|pix_icon|string $action */ public function add($action) { if ($action instanceof action_link) { if ($action->primary) { $this->add_primary_action($action); } else { $this->add_secondary_action($action); } } else if ($action instanceof pix_icon) { $this->add_primary_action($action); } else { $this->add_secondary_action($action); } } /** * Adds a primary action to the action menu. * * @param action_menu_link|action_link|pix_icon|string $action */ public function add_primary_action($action) { if ($action instanceof action_link || $action instanceof pix_icon) { $action->attributes['role'] = 'menuitem'; if ($action instanceof action_menu_link) { $action->actionmenu = $this; } } $this->primaryactions[] = $action; } /** * Adds a secondary action to the action menu. * * @param action_link|pix_icon|string $action */ public function add_secondary_action($action) { if ($action instanceof action_link || $action instanceof pix_icon) { $action->attributes['role'] = 'menuitem'; if ($action instanceof action_menu_link) { $action->actionmenu = $this; } } $this->secondaryactions[] = $action; } /** * Returns the primary actions ready to be rendered. * * @param core_renderer $output The renderer to use for getting icons. * @return array */ public function get_primary_actions(core_renderer $output = null) { global $OUTPUT; if ($output === null) { $output = $OUTPUT; } $pixicon = $this->actionicon; $linkclasses = array('toggle-display'); $title = ''; if (!empty($this->menutrigger)) { $pixicon = '<b class="caret"></b>'; $linkclasses[] = 'textmenu'; } else { $title = new lang_string('actions', 'moodle'); $this->actionicon = new pix_icon( 't/edit_menu', '', 'moodle', array('class' => 'iconsmall actionmenu', 'title' => '') ); $pixicon = $this->actionicon; } if ($pixicon instanceof renderable) { $pixicon = $output->render($pixicon); if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) { $title = $pixicon->attributes['alt']; } } $string = ''; if ($this->actiontext) { $string = $this->actiontext; } $actions = $this->primaryactions; $attributes = array( 'class' => implode(' ', $linkclasses), 'title' => $title, 'id' => 'action-menu-toggle-'.$this->instance, 'role' => 'menuitem' ); $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes); if ($this->prioritise) { array_unshift($actions, $link); } else { $actions[] = $link; } return $actions; } /** * Returns the secondary actions ready to be rendered. * @return array */ public function get_secondary_actions() { return $this->secondaryactions; } /** * Sets the selector that should be used to find the owning node of this menu. * @param string $selector A CSS/YUI selector to identify the owner of the menu. */ public function set_owner_selector($selector) { $this->attributes['data-owner'] = $selector; } /** * Sets the alignment of the dialogue in relation to button used to toggle it. * * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. */ public function set_alignment($dialogue, $button) { if (isset($this->attributessecondary['data-align'])) { // We've already got one set, lets remove the old class so as to avoid troubles. $class = $this->attributessecondary['class']; $search = 'align-'.$this->attributessecondary['data-align']; $this->attributessecondary['class'] = str_replace($search, '', $class); } $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button); $this->attributessecondary['data-align'] = $align; $this->attributessecondary['class'] .= ' align-'.$align; } /** * Returns a string to describe the alignment. * * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. * @return string */ protected function get_align_string($align) { switch ($align) { case self::TL : return 'tl'; case self::TR : return 'tr'; case self::BL : return 'bl'; case self::BR : return 'br'; default : return 'tl'; } } /** * Sets a constraint for the dialogue. * * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the * element the constraint identifies. * * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to. */ public function set_constraint($ancestorselector) { $this->attributessecondary['data-constraint'] = $ancestorselector; } /** * If you call this method the action menu will be displayed but will not be enhanced. * * By not displaying the menu enhanced all items will be displayed in a single row. */ public function do_not_enhance() { unset($this->attributes['data-enhance']); } /** * Returns true if this action menu will be enhanced. * * @return bool */ public function will_be_enhanced() { return isset($this->attributes['data-enhance']); } /** * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space. * * This property can be useful when the action menu is displayed within a parent element that is either floated * or relatively positioned. * In that situation the width of the menu is determined by the width of the parent element which may not be large * enough for the menu items without them wrapping. * This disables the wrapping so that the menu takes on the width of the longest item. * * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true. */ public function set_nowrap_on_items($value = true) { $class = 'nowrap-items'; if (!empty($this->attributes['class'])) { $pos = strpos($this->attributes['class'], $class); if ($value === true && $pos === false) { // The value is true and the class has not been set yet. Add it. $this->attributes['class'] .= ' '.$class; } else if ($value === false && $pos !== false) { // The value is false and the class has been set. Remove it. $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class)); } } else if ($value) { // The value is true and the class has not been set yet. Add it. $this->attributes['class'] = $class; } } } /** * An action menu filler * * @package core * @category output * @copyright 2013 Andrew Nicols * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_filler extends action_link implements renderable { /** * True if this is a primary action. False if not. * @var bool */ public $primary = true; /** * Constructs the object. */ public function __construct() { } } /** * An action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link extends action_link implements renderable { /** * True if this is a primary action. False if not. * @var bool */ public $primary = true; /** * The action menu this link has been added to. * @var action_menu */ public $actionmenu = null; /** * Constructs the object. * * @param moodle_url $url The URL for the action. * @param pix_icon $icon The icon to represent the action. * @param string $text The text to represent the action. * @param bool $primary Whether this is a primary action or not. * @param array $attributes Any attribtues associated with the action. */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) { parent::__construct($url, $text, null, $attributes, $icon); $this->primary = (bool)$primary; $this->add_class('menu-action'); $this->attributes['role'] = 'menuitem'; } } /** * A primary action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link_primary extends action_menu_link { /** * Constructs the object. * * @param moodle_url $url * @param pix_icon $icon * @param string $text * @param array $attributes */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) { parent::__construct($url, $icon, $text, true, $attributes); } } /** * A secondary action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link_secondary extends action_menu_link { /** * Constructs the object. * * @param moodle_url $url * @param pix_icon $icon * @param string $text * @param array $attributes */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) { parent::__construct($url, $icon, $text, false, $attributes); } }
VNageswararao/lms28
lib/outputcomponents.php
PHP
gpl-3.0
115,993
/// Copyright (c) 2008-2021 Emil Dotchevski and Reverge Studios, Inc. /// Distributed under the Boost Software License, Version 1.0. (See accompanying /// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/qvm/gen/vec_mat_operations2.hpp>
rneiss/PocketTorah
ios/Pods/Flipper-Boost-iOSX/boost/qvm/vec_mat_operations2.hpp
C++
gpl-3.0
276
"use strict"; tutao.provide('tutao.entity.base.PersistenceResourcePostReturn'); /** * @constructor * @param {Object=} data The json data to store in this entity. */ tutao.entity.base.PersistenceResourcePostReturn = function(data) { if (data) { this.updateData(data); } else { this.__format = "0"; this._generatedId = null; this._permissionListId = null; } this._entityHelper = new tutao.entity.EntityHelper(this); this.prototype = tutao.entity.base.PersistenceResourcePostReturn.prototype; }; /** * Updates the data of this entity. * @param {Object=} data The json data to store in this entity. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.updateData = function(data) { this.__format = data._format; this._generatedId = data.generatedId; this._permissionListId = data.permissionListId; }; /** * The version of the model this type belongs to. * @const */ tutao.entity.base.PersistenceResourcePostReturn.MODEL_VERSION = '1'; /** * The encrypted flag. * @const */ tutao.entity.base.PersistenceResourcePostReturn.prototype.ENCRYPTED = false; /** * Provides the data of this instances as an object that can be converted to json. * @return {Object} The json object. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.toJsonData = function() { return { _format: this.__format, generatedId: this._generatedId, permissionListId: this._permissionListId }; }; /** * The id of the PersistenceResourcePostReturn type. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.TYPE_ID = 0; /** * The id of the generatedId attribute. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.GENERATEDID_ATTRIBUTE_ID = 2; /** * The id of the permissionListId attribute. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.PERMISSIONLISTID_ATTRIBUTE_ID = 3; /** * Sets the format of this PersistenceResourcePostReturn. * @param {string} format The format of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setFormat = function(format) { this.__format = format; return this; }; /** * Provides the format of this PersistenceResourcePostReturn. * @return {string} The format of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getFormat = function() { return this.__format; }; /** * Sets the generatedId of this PersistenceResourcePostReturn. * @param {string} generatedId The generatedId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setGeneratedId = function(generatedId) { this._generatedId = generatedId; return this; }; /** * Provides the generatedId of this PersistenceResourcePostReturn. * @return {string} The generatedId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getGeneratedId = function() { return this._generatedId; }; /** * Sets the permissionListId of this PersistenceResourcePostReturn. * @param {string} permissionListId The permissionListId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setPermissionListId = function(permissionListId) { this._permissionListId = permissionListId; return this; }; /** * Provides the permissionListId of this PersistenceResourcePostReturn. * @return {string} The permissionListId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getPermissionListId = function() { return this._permissionListId; }; /** * Provides the entity helper of this entity. * @return {tutao.entity.EntityHelper} The entity helper. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getEntityHelper = function() { return this._entityHelper; };
msoftware/tutanota-1
web/js/generated/entity/base/PersistenceResourcePostReturn.js
JavaScript
gpl-3.0
3,838
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.event.terraingen; import java.util.Random; import net.minecraft.block.BlockSapling; import net.minecraft.block.state.IBlockState; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Cancelable; import net.minecraftforge.fml.common.eventhandler.Event.HasResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.world.WorldEvent; /** * SaplingGrowTreeEvent is fired when a sapling grows into a tree.<br> * This event is fired during sapling growth in * {@link BlockSapling#generateTree(World, BlockPos, IBlockState, Random)}.<br> * <br> * {@link #pos} contains the coordinates of the growing sapling. <br> * {@link #rand} contains an instance of Random for use. <br> * <br> * This event is not {@link Cancelable}.<br> * <br> * This event has a result. {@link HasResult} <br> * This result determines if the sapling is allowed to grow. <br> * <br> * This event is fired on the {@link MinecraftForge#TERRAIN_GEN_BUS}.<br> **/ @HasResult public class SaplingGrowTreeEvent extends WorldEvent { private final BlockPos pos; private final Random rand; public SaplingGrowTreeEvent(World world, Random rand, BlockPos pos) { super(world); this.rand = rand; this.pos = pos; } public BlockPos getPos() { return pos; } public Random getRand() { return rand; } }
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraftforge/event/terraingen/SaplingGrowTreeEvent.java
Java
gpl-3.0
2,229
# -*- coding: utf-8 -*- # Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, add_months, cint, nowdate, getdate from frappe.model.document import Document from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import get_fixed_asset_account from erpnext.accounts.doctype.asset.depreciation \ import get_disposal_account_and_cost_center, get_depreciation_accounts class Asset(Document): def validate(self): self.status = self.get_status() self.validate_item() self.set_missing_values() self.validate_asset_values() self.make_depreciation_schedule() self.set_accumulated_depreciation() if self.get("schedules"): self.validate_expected_value_after_useful_life() # Validate depreciation related accounts get_depreciation_accounts(self) def on_submit(self): self.set_status() def on_cancel(self): self.validate_cancellation() self.delete_depreciation_entries() self.set_status() def validate_item(self): item = frappe.db.get_value("Item", self.item_code, ["is_fixed_asset", "is_stock_item", "disabled"], as_dict=1) if not item: frappe.throw(_("Item {0} does not exist").format(self.item_code)) elif item.disabled: frappe.throw(_("Item {0} has been disabled").format(self.item_code)) elif not item.is_fixed_asset: frappe.throw(_("Item {0} must be a Fixed Asset Item").format(self.item_code)) elif item.is_stock_item: frappe.throw(_("Item {0} must be a non-stock item").format(self.item_code)) def set_missing_values(self): if self.item_code: item_details = get_item_details(self.item_code) for field, value in item_details.items(): if not self.get(field): self.set(field, value) self.value_after_depreciation = (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation)) def validate_asset_values(self): if flt(self.expected_value_after_useful_life) >= flt(self.gross_purchase_amount): frappe.throw(_("Expected Value After Useful Life must be less than Gross Purchase Amount")) if not flt(self.gross_purchase_amount): frappe.throw(_("Gross Purchase Amount is mandatory"), frappe.MandatoryError) if not self.is_existing_asset: self.opening_accumulated_depreciation = 0 self.number_of_depreciations_booked = 0 if not self.next_depreciation_date: frappe.throw(_("Next Depreciation Date is mandatory for new asset")) else: depreciable_amount = flt(self.gross_purchase_amount) - flt(self.expected_value_after_useful_life) if flt(self.opening_accumulated_depreciation) > depreciable_amount: frappe.throw(_("Opening Accumulated Depreciation must be less than equal to {0}") .format(depreciable_amount)) if self.opening_accumulated_depreciation: if not self.number_of_depreciations_booked: frappe.throw(_("Please set Number of Depreciations Booked")) else: self.number_of_depreciations_booked = 0 if cint(self.number_of_depreciations_booked) > cint(self.total_number_of_depreciations): frappe.throw(_("Number of Depreciations Booked cannot be greater than Total Number of Depreciations")) if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(nowdate()): frappe.msgprint(_("Next Depreciation Date is entered as past date"), title=_('Warning'), indicator='red') if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(self.purchase_date): frappe.throw(_("Next Depreciation Date cannot be before Purchase Date")) if (flt(self.value_after_depreciation) > flt(self.expected_value_after_useful_life) and not self.next_depreciation_date): frappe.throw(_("Please set Next Depreciation Date")) def make_depreciation_schedule(self): if self.depreciation_method != 'Manual': self.schedules = [] if not self.get("schedules") and self.next_depreciation_date: value_after_depreciation = flt(self.value_after_depreciation) number_of_pending_depreciations = cint(self.total_number_of_depreciations) - \ cint(self.number_of_depreciations_booked) if number_of_pending_depreciations: for n in xrange(number_of_pending_depreciations): schedule_date = add_months(self.next_depreciation_date, n * cint(self.frequency_of_depreciation)) depreciation_amount = self.get_depreciation_amount(value_after_depreciation) value_after_depreciation -= flt(depreciation_amount) self.append("schedules", { "schedule_date": schedule_date, "depreciation_amount": depreciation_amount }) def set_accumulated_depreciation(self): accumulated_depreciation = flt(self.opening_accumulated_depreciation) value_after_depreciation = flt(self.value_after_depreciation) for i, d in enumerate(self.get("schedules")): depreciation_amount = flt(d.depreciation_amount, d.precision("depreciation_amount")) value_after_depreciation -= flt(depreciation_amount) if i==len(self.get("schedules"))-1 and self.depreciation_method == "Straight Line": depreciation_amount += flt(value_after_depreciation - flt(self.expected_value_after_useful_life), d.precision("depreciation_amount")) d.depreciation_amount = depreciation_amount accumulated_depreciation += d.depreciation_amount d.accumulated_depreciation_amount = flt(accumulated_depreciation, d.precision("accumulated_depreciation_amount")) def get_depreciation_amount(self, depreciable_value): if self.depreciation_method in ("Straight Line", "Manual"): depreciation_amount = (flt(self.value_after_depreciation) - flt(self.expected_value_after_useful_life)) / (cint(self.total_number_of_depreciations) - cint(self.number_of_depreciations_booked)) else: factor = 200.0 / self.total_number_of_depreciations depreciation_amount = flt(depreciable_value * factor / 100, 0) value_after_depreciation = flt(depreciable_value) - depreciation_amount if value_after_depreciation < flt(self.expected_value_after_useful_life): depreciation_amount = flt(depreciable_value) - flt(self.expected_value_after_useful_life) return depreciation_amount def validate_expected_value_after_useful_life(self): accumulated_depreciation_after_full_schedule = \ max([d.accumulated_depreciation_amount for d in self.get("schedules")]) asset_value_after_full_schedule = (flt(self.gross_purchase_amount) - flt(accumulated_depreciation_after_full_schedule)) if self.expected_value_after_useful_life < asset_value_after_full_schedule: frappe.throw(_("Expected value after useful life must be greater than or equal to {0}") .format(asset_value_after_full_schedule)) def validate_cancellation(self): if self.status not in ("Submitted", "Partially Depreciated", "Fully Depreciated"): frappe.throw(_("Asset cannot be cancelled, as it is already {0}").format(self.status)) if self.purchase_invoice: frappe.throw(_("Please cancel Purchase Invoice {0} first").format(self.purchase_invoice)) def delete_depreciation_entries(self): for d in self.get("schedules"): if d.journal_entry: frappe.get_doc("Journal Entry", d.journal_entry).cancel() d.db_set("journal_entry", None) self.db_set("value_after_depreciation", (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation))) def set_status(self, status=None): '''Get and update status''' if not status: status = self.get_status() self.db_set("status", status) def get_status(self): '''Returns status based on whether it is draft, submitted, scrapped or depreciated''' if self.docstatus == 0: status = "Draft" elif self.docstatus == 1: status = "Submitted" if self.journal_entry_for_scrap: status = "Scrapped" elif flt(self.value_after_depreciation) <= flt(self.expected_value_after_useful_life): status = "Fully Depreciated" elif flt(self.value_after_depreciation) < flt(self.gross_purchase_amount): status = 'Partially Depreciated' elif self.docstatus == 2: status = "Cancelled" return status @frappe.whitelist() def make_purchase_invoice(asset, item_code, gross_purchase_amount, company, posting_date): pi = frappe.new_doc("Purchase Invoice") pi.company = company pi.currency = frappe.db.get_value("Company", company, "default_currency") pi.set_posting_time = 1 pi.posting_date = posting_date pi.append("items", { "item_code": item_code, "is_fixed_asset": 1, "asset": asset, "expense_account": get_fixed_asset_account(asset), "qty": 1, "price_list_rate": gross_purchase_amount, "rate": gross_purchase_amount }) pi.set_missing_values() return pi @frappe.whitelist() def make_sales_invoice(asset, item_code, company): si = frappe.new_doc("Sales Invoice") si.company = company si.currency = frappe.db.get_value("Company", company, "default_currency") disposal_account, depreciation_cost_center = get_disposal_account_and_cost_center(company) si.append("items", { "item_code": item_code, "is_fixed_asset": 1, "asset": asset, "income_account": disposal_account, "cost_center": depreciation_cost_center, "qty": 1 }) si.set_missing_values() return si @frappe.whitelist() def transfer_asset(args): import json args = json.loads(args) movement_entry = frappe.new_doc("Asset Movement") movement_entry.update(args) movement_entry.insert() movement_entry.submit() frappe.db.commit() frappe.msgprint(_("Asset Movement record {0} created").format("<a href='#Form/Asset Movement/{0}'>{0}</a>".format(movement_entry.name))) @frappe.whitelist() def get_item_details(item_code): asset_category = frappe.db.get_value("Item", item_code, "asset_category") if not asset_category: frappe.throw(_("Please enter Asset Category in Item {0}").format(item_code)) ret = frappe.db.get_value("Asset Category", asset_category, ["depreciation_method", "total_number_of_depreciations", "frequency_of_depreciation"], as_dict=1) ret.update({ "asset_category": asset_category }) return ret
emakis/erpnext
erpnext/accounts/doctype/asset/asset.py
Python
gpl-3.0
10,030
# encoding: utf-8 class Laby::Content::Base < Cms::Content end
tao-k/zomeki
app/models/laby/content/base.rb
Ruby
gpl-3.0
64
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit8a8b7c48f14663b8905d3aebf4678cc4::getLoader();
oliverds/openclassifieds2
oc/vendor/pusher/autoload.php
PHP
gpl-3.0
183
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # This is a virtual module that is entirely implemented as an action plugin and runs on the controller from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: fetch short_description: Fetch files from remote nodes description: - This module works like M(copy), but in reverse. - It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname. - Files that already exist at I(dest) will be overwritten if they are different than the I(src). - This module is also supported for Windows targets. version_added: '0.2' options: src: description: - The file on the remote system to fetch. - This I(must) be a file, not a directory. - Recursive fetching may be supported in a later release. required: yes dest: description: - A directory to save the file into. - For example, if the I(dest) directory is C(/backup) a I(src) file named C(/etc/profile) on host C(host.example.com), would be saved into C(/backup/host.example.com/etc/profile). The host name is based on the inventory name. required: yes fail_on_missing: version_added: '1.1' description: - When set to C(yes), the task will fail if the remote file cannot be read for any reason. - Prior to Ansible 2.5, setting this would only fail if the source file was missing. - The default was changed to C(yes) in Ansible 2.5. type: bool default: yes validate_checksum: version_added: '1.4' description: - Verify that the source and destination checksums match after the files are fetched. type: bool default: yes flat: version_added: '1.2' description: - Allows you to override the default behavior of appending hostname/path/to/file to the destination. - If C(dest) ends with '/', it will use the basename of the source file, similar to the copy module. - This can be useful if working with a single host, or if retrieving files that are uniquely named per host. - If using multiple hosts with the same filename, the file will be overwritten for each host. type: bool default: no notes: - When running fetch with C(become), the M(slurp) module will also be used to fetch the contents of the file for determining the remote checksum. This effectively doubles the transfer size, and depending on the file size can consume all available memory on the remote or local hosts causing a C(MemoryError). Due to this it is advisable to run this module without C(become) whenever possible. - Prior to Ansible 2.5 this module would not fail if reading the remote file was impossible unless C(fail_on_missing) was set. - In Ansible 2.5 or later, playbook authors are encouraged to use C(fail_when) or C(ignore_errors) to get this ability. They may also explicitly set C(fail_on_missing) to C(no) to get the non-failing behaviour. - This module is also supported for Windows targets. seealso: - module: copy - module: slurp author: - Ansible Core Team - Michael DeHaan ''' EXAMPLES = r''' - name: Store file into /tmp/fetched/host.example.com/tmp/somefile fetch: src: /tmp/somefile dest: /tmp/fetched - name: Specifying a path directly fetch: src: /tmp/somefile dest: /tmp/prefix-{{ inventory_hostname }} flat: yes - name: Specifying a destination path fetch: src: /tmp/uniquefile dest: /tmp/special/ flat: yes - name: Storing in a path relative to the playbook fetch: src: /tmp/uniquefile dest: special/prefix-{{ inventory_hostname }} flat: yes '''
indrajitr/ansible
lib/ansible/modules/fetch.py
Python
gpl-3.0
3,790
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import smtplib import sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from mo_logs import Log from mo_dots import listwrap from mo_dots import coalesce from mo_kwargs import override class Emailer: @override def __init__( self, from_address, to_address, host, username, password, subject="catchy title", port=465, use_ssl=1, kwargs=None ): self.settings = kwargs self.server = None def __enter__(self): if self.server is not None: Log.error("Got a problem") if self.settings.use_ssl: self.server = smtplib.SMTP_SSL(self.settings.host, self.settings.port) else: self.server = smtplib.SMTP(self.settings.host, self.settings.port) if self.settings.username and self.settings.password: self.server.login(self.settings.username, self.settings.password) return self def __exit__(self, type, value, traceback): try: self.server.quit() except Exception as e: Log.warning("Problem with smtp server quit(), ignoring problem", e) self.server = None def send_email(self, from_address=None, to_address=None, subject=None, text_data=None, html_data=None ): """Sends an email. from_addr is an email address; to_addrs is a list of email adresses. Addresses can be plain (e.g. "jsmith@example.com") or with real names (e.g. "John Smith <jsmith@example.com>"). text_data and html_data are both strings. You can specify one or both. If you specify both, the email will be sent as a MIME multipart alternative, i.e., the recipient will see the HTML content if his viewer supports it; otherwise he'll see the text content. """ settings = self.settings from_address = coalesce(from_address, settings["from"], settings.from_address) to_address = listwrap(coalesce(to_address, settings.to_address, settings.to_addrs)) if not from_address or not to_address: raise Exception("Both from_addr and to_addrs must be specified") if not text_data and not html_data: raise Exception("Must specify either text_data or html_data") if not html_data: msg = MIMEText(text_data) elif not text_data: msg = MIMEText(html_data, 'html') else: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text_data, 'plain')) msg.attach(MIMEText(html_data, 'html')) msg['Subject'] = coalesce(subject, settings.subject) msg['From'] = from_address msg['To'] = ', '.join(to_address) if self.server: # CALL AS PART OF A SMTP SESSION self.server.sendmail(from_address, to_address, msg.as_string()) else: # CALL AS STAND-ALONE with self: self.server.sendmail(from_address, to_address, msg.as_string()) if sys.hexversion < 0x020603f0: # versions earlier than 2.6.3 have a bug in smtplib when sending over SSL: # http://bugs.python.org/issue4066 # Unfortunately the stock version of Python in Snow Leopard is 2.6.1, so # we patch it here to avoid having to install an updated Python version. import socket import ssl def _get_socket_fixed(self, host, port, timeout): if self.debuglevel > 0: print>> sys.stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) self.file = smtplib.SSLFakeFile(new_socket) return new_socket smtplib.SMTP_SSL._get_socket = _get_socket_fixed
klahnakoski/Bugzilla-ETL
vendor/pyLibrary/env/emailer.py
Python
mpl-2.0
4,306
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AddField( model_name='catalogintegration', name='service_username', field=models.CharField(default=u'lms_catalog_service_user', help_text='Username created for Course Catalog Integration, e.g. lms_catalog_service_user.', max_length=100), ), ]
edx-solutions/edx-platform
openedx/core/djangoapps/catalog/migrations/0002_catalogintegration_username.py
Python
agpl-3.0
503
from __future__ import unicode_literals def execute(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'Administrator', 'permlevel': 1, 'read': 1, 'write': 1 }, ] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
gangadhar-kadam/mtn-erpnext
patches/may_2012/std_pf_readonly.py
Python
agpl-3.0
718
<?php /** * When appropriate, displays a plugin upgrade message "inline" within the plugin * admin screen. * * This is drawn from the Upgrade Notice section of the plugin readme.txt file (ie, * the one belonging to the current stable accessible via WP SVN - at least by * default). */ class Tribe__Admin__Notice__Plugin_Upgrade_Notice { /** * Currently installed version of the plugin * * @var string */ protected $current_version = ''; /** * The plugin path as it is within the plugins directory, ie * "some-plugin/main-file.php". * * @var string */ protected $plugin_path = ''; /** * Contains the plugin upgrade notice (empty if none are available). * * @var string */ protected $upgrade_notice = ''; /** * Test for and display any plugin upgrade messages (if any are available) inline * beside the plugin listing itself. * * The optional third param is the object which actually checks to see if there * are any upgrade notices worth displaying. If not provided, an object of the * default type will be created (which connects to WP SVN). * * @param string $current_version * @param string $plugin_path (ie "plugin-dir/main-file.php") */ public function __construct( $current_version, $plugin_path ) { $this->current_version = $current_version; $this->plugin_path = $plugin_path; add_action( "in_plugin_update_message-$plugin_path", array( $this, 'maybe_run' ) ); } /** * Test if there is a plugin upgrade notice and displays it if so. * * Expects to fire during "in_plugin_update_message-{plugin_path}", therefore * this should only run if WordPress has detected that an upgrade is indeed * available. */ public function maybe_run() { $this->test_for_upgrade_notice(); if ( $this->upgrade_notice ) { $this->display_message(); } } /** * Tests to see if an upgrade notice is available. */ protected function test_for_upgrade_notice() { $cache_key = $this->cache_key(); $this->upgrade_notice = get_transient( $cache_key ); if ( false === $this->upgrade_notice ) { $this->discover_upgrade_notice(); } set_transient( $cache_key, $this->upgrade_notice, $this->cache_expiration() ); } /** * Returns a cache key unique to the current plugin path and version, that * still fits within the 45-char limit of regular WP transient keys. * * @return string */ protected function cache_key() { return 'tribe_plugin_upgrade_notice-' . hash( 'crc32b', $this->plugin_path . $this->current_version ); } /** * Returns the period of time (in seconds) for which to cache plugin upgrade messages. * * @return int */ protected function cache_expiration() { /** * Number of seconds to cache plugin upgrade messages for. * * Defaults to one day, which provides a decent balance between efficiency savings * and allowing for the possibility that some upgrade messages may be changed or * rescinded. * * @var int $cache_expiration */ return (int) apply_filters( 'tribe_plugin_upgrade_notice_expiration', DAY_IN_SECONDS, $this->plugin_path ); } /** * Looks at the current stable plugin readme.txt and parses to try and find the first * available upgrade notice relating to a plugin version higher than this one. * * By default, WP SVN is the source. */ protected function discover_upgrade_notice() { /** * The URL for the current plugin readme.txt file. * * @var string $url * @var string $plugin_path */ $readme_url = apply_filters( 'tribe_plugin_upgrade_readme_url', $this->form_wp_svn_readme_url(), $this->plugin_path ); if ( ! empty( $readme_url ) ) { $response = wp_safe_remote_get( $readme_url ); } if ( ! empty( $response ) && ! is_wp_error( $response ) ) { $readme = $response['body']; } if ( ! empty( $readme ) ) { $this->parse_for_upgrade_notice( $readme ); $this->format_upgrade_notice(); } /** * The upgrade notice for the current plugin (may be empty). * * @var string $upgrade_notice * @var string $plugin_path */ return apply_filters( 'tribe_plugin_upgrade_notice', $this->upgrade_notice, $this->plugin_path ); } /** * Forms the expected URL to the trunk readme.txt file as it is on WP SVN * or an empty string if for any reason it cannot be determined. * * @return string */ protected function form_wp_svn_readme_url() { $parts = explode( '/', $this->plugin_path ); $slug = empty( $parts[0] ) ? '' : $parts[0]; return esc_url( "https://plugins.svn.wordpress.org/$slug/trunk/readme.txt" ); } /** * Given a standard Markdown-format WP readme.txt file, finds the first upgrade * notice (if any) for a version higher than $this->current_version. * * @param string $readme * @return string */ protected function parse_for_upgrade_notice( $readme ) { $in_upgrade_notice = false; $in_version_notice = false; $readme_lines = explode( "\n", $readme ); foreach ( $readme_lines as $line ) { // Once we leave the Upgrade Notice section (ie, we encounter a new section header), bail if ( $in_upgrade_notice && 0 === strpos( $line, '==' ) ) { break; } // Look out for the start of the Upgrade Notice section if ( ! $in_upgrade_notice && preg_match( '/^==\s*Upgrade\s+Notice\s*==/i', $line ) ) { $in_upgrade_notice = true; } // Also test to see if we have left the version specific note (ie, we encounter a new sub heading or header) if ( $in_upgrade_notice && $in_version_notice && 0 === strpos( $line, '=' ) ) { break; } // Look out for the first applicable version-specific note within the Upgrade Notice section if ( $in_upgrade_notice && ! $in_version_notice && preg_match( '/^=\s*\[?([0-9\.]{3,})\]?\s*=/', $line, $matches ) ) { // Is this a higher version than currently installed? if ( version_compare( $matches[1], $this->current_version, '>' ) ) { $in_version_notice = true; } } // Copy the details of the upgrade notice for the first higher version we find if ( $in_upgrade_notice && $in_version_notice ) { $this->upgrade_notice .= $line . "\n"; } } } /** * Convert the plugin version header and any links from Markdown to HTML. */ protected function format_upgrade_notice() { // Convert [links](http://...) to <a href="..."> tags $this->upgrade_notice = preg_replace( '/\[([^\]]*)\]\(([^\)]*)\)/', '<a href="${2}">${1}</a>', $this->upgrade_notice ); // Convert =4.0= headings to <h4 class="version">4.0</h4> tags $this->upgrade_notice = preg_replace( '/=\s*([a-zA-Z0-9\.]{3,})\s*=/', '<h4 class="version">${1}</h4>', $this->upgrade_notice ); } /** * Render the actual upgrade notice. * * Please note if plugin-specific styling is required for the message, you can * use an ID generated by WordPress for one of the message's parent elements * which takes the form "{plugin_name}-update". Example: * * #the-events-calendar-update .tribe-plugin-update-message { ... } */ public function display_message() { $notice = wp_kses_post( $this->upgrade_notice ); echo "<div class='tribe-plugin-update-message'> $notice </div>"; } }
akvo/akvo-sites-zz-template
code/wp-content/plugins/the-events-calendar/common/src/Tribe/Admin/Notice/Plugin_Upgrade_Notice.php
PHP
agpl-3.0
7,190
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo; /** * Linked to core.clinical.EpworthSleepAssessment business object (ID: 1003100055). */ public class EpworthSleepAssessmentVo extends ims.core.clinical.vo.EpworthSleepAssessmentRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public EpworthSleepAssessmentVo() { } public EpworthSleepAssessmentVo(Integer id, int version) { super(id, version); } public EpworthSleepAssessmentVo(ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean = null; if(map != null) bean = (ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CHANCEOFSLEEP")) return getChanceOfSleep(); if(fieldName.equals("SLEEPSCORE")) return getSleepScore(); return super.getFieldValueByFieldName(fieldName); } public boolean getChanceOfSleepIsNotNull() { return this.chanceofsleep != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep getChanceOfSleep() { return this.chanceofsleep; } public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep value) { this.isValidated = false; this.chanceofsleep = value; } public boolean getSleepScoreIsNotNull() { return this.sleepscore != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore() { return this.sleepscore; } public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value) { this.isValidated = false; this.sleepscore = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; EpworthSleepAssessmentVo clone = new EpworthSleepAssessmentVo(this.id, this.version); if(this.chanceofsleep == null) clone.chanceofsleep = null; else clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep)this.chanceofsleep.clone(); if(this.sleepscore == null) clone.sleepscore = null; else clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(EpworthSleepAssessmentVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A EpworthSleepAssessmentVo object cannot be compared an Object of type " + obj.getClass().getName()); } EpworthSleepAssessmentVo compareObj = (EpworthSleepAssessmentVo)obj; int retVal = 0; if (retVal == 0) { if(this.getID_EpworthSleepAssessment() == null && compareObj.getID_EpworthSleepAssessment() != null) return -1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() == null) return 1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() != null) retVal = this.getID_EpworthSleepAssessment().compareTo(compareObj.getID_EpworthSleepAssessment()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.chanceofsleep != null) count++; if(this.sleepscore != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep chanceofsleep; protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/EpworthSleepAssessmentVo.java
Java
agpl-3.0
7,901
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.beans; public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean { public MRSATreatmentVoBean() { } public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public ims.nursing.vo.MRSATreatmentVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.MRSATreatmentVo vo = null; if(map != null) vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this); if(vo == null) { vo = new ims.nursing.vo.MRSATreatmentVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getStartDate() { return this.startdate; } public void setStartDate(ims.framework.utils.beans.DateBean value) { this.startdate = value; } public ims.framework.utils.beans.DateBean getRescreenDate() { return this.rescreendate; } public void setRescreenDate(ims.framework.utils.beans.DateBean value) { this.rescreendate = value; } public Integer getTreatmentNumber() { return this.treatmentnumber; } public void setTreatmentNumber(Integer value) { this.treatmentnumber = value; } public ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] getTreatmentDetails() { return this.treatmentdetails; } public void setTreatmentDetails(ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] value) { this.treatmentdetails = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean startdate; private ims.framework.utils.beans.DateBean rescreendate; private Integer treatmentnumber; private ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] treatmentdetails; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/beans/MRSATreatmentVoBean.java
Java
agpl-3.0
4,677
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo; /** * Linked to nursing.assessment.Transfers business object (ID: 1015100016). */ public class Transfers extends ims.nursing.assessment.vo.TransfersRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public Transfers() { } public Transfers(Integer id, int version) { super(id, version); } public Transfers(ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.TransfersBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.TransfersBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.TransfersBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PATIENTTRANSFERS")) return getPatientTransfers(); if(fieldName.equals("ASSISTANCEREQUIRED")) return getAssistanceRequired(); return super.getFieldValueByFieldName(fieldName); } public boolean getPatientTransfersIsNotNull() { return this.patienttransfers != null; } public ims.nursing.vo.lookups.Transfers getPatientTransfers() { return this.patienttransfers; } public void setPatientTransfers(ims.nursing.vo.lookups.Transfers value) { this.isValidated = false; this.patienttransfers = value; } public boolean getAssistanceRequiredIsNotNull() { return this.assistancerequired != null; } public ims.nursing.vo.lookups.Ability getAssistanceRequired() { return this.assistancerequired; } public void setAssistanceRequired(ims.nursing.vo.lookups.Ability value) { this.isValidated = false; this.assistancerequired = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; Transfers clone = new Transfers(this.id, this.version); if(this.patienttransfers == null) clone.patienttransfers = null; else clone.patienttransfers = (ims.nursing.vo.lookups.Transfers)this.patienttransfers.clone(); if(this.assistancerequired == null) clone.assistancerequired = null; else clone.assistancerequired = (ims.nursing.vo.lookups.Ability)this.assistancerequired.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(Transfers.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A Transfers object cannot be compared an Object of type " + obj.getClass().getName()); } Transfers compareObj = (Transfers)obj; int retVal = 0; if (retVal == 0) { if(this.getID_Transfers() == null && compareObj.getID_Transfers() != null) return -1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() == null) return 1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() != null) retVal = this.getID_Transfers().compareTo(compareObj.getID_Transfers()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patienttransfers != null) count++; if(this.assistancerequired != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.nursing.vo.lookups.Transfers patienttransfers; protected ims.nursing.vo.lookups.Ability assistancerequired; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/Transfers.java
Java
agpl-3.0
7,494
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; /** * Linked to RefMan.CatsReferral business object (ID: 1004100035). */ public class CatsReferralForSessionManagementVo extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public CatsReferralForSessionManagementVo() { } public CatsReferralForSessionManagementVo(Integer id, int version) { super(id, version); } public CatsReferralForSessionManagementVo(ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(map); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean = null; if(map != null) bean = (ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("REFERRALDETAILS")) return getReferralDetails(); if(fieldName.equals("CURRENTSTATUS")) return getCurrentStatus(); return super.getFieldValueByFieldName(fieldName); } public boolean getReferralDetailsIsNotNull() { return this.referraldetails != null; } public ims.RefMan.vo.ReferralLetterForSessionManagementVo getReferralDetails() { return this.referraldetails; } public void setReferralDetails(ims.RefMan.vo.ReferralLetterForSessionManagementVo value) { this.isValidated = false; this.referraldetails = value; } public boolean getCurrentStatusIsNotNull() { return this.currentstatus != null; } public ims.RefMan.vo.CatsReferralStatusLiteVo getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.RefMan.vo.CatsReferralStatusLiteVo value) { this.isValidated = false; this.currentstatus = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; CatsReferralForSessionManagementVo clone = new CatsReferralForSessionManagementVo(this.id, this.version); if(this.referraldetails == null) clone.referraldetails = null; else clone.referraldetails = (ims.RefMan.vo.ReferralLetterForSessionManagementVo)this.referraldetails.clone(); if(this.currentstatus == null) clone.currentstatus = null; else clone.currentstatus = (ims.RefMan.vo.CatsReferralStatusLiteVo)this.currentstatus.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(CatsReferralForSessionManagementVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A CatsReferralForSessionManagementVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((CatsReferralForSessionManagementVo)obj).getBoId() == null) return -1; return this.id.compareTo(((CatsReferralForSessionManagementVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.referraldetails != null) count++; if(this.currentstatus != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.RefMan.vo.ReferralLetterForSessionManagementVo referraldetails; protected ims.RefMan.vo.CatsReferralStatusLiteVo currentstatus; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/CatsReferralForSessionManagementVo.java
Java
agpl-3.0
5,952
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Class for defining the badge associated with creating a new note */ class CreateNoteGameBadgeRules extends GameBadgeRules { public static $valuesIndexedByGrade = array( 1 => 1, 2 => 10, 3 => 25, 4 => 50, 5 => 75, 6 => 100, 7 => 125, 8 => 150, 9 => 175, 10 => 200, 11 => 225, 12 => 250, 13 => 300 ); public static function getPassiveDisplayLabel($value) { return Zurmo::t('NotesModule', '{n} NotesModuleSingularLabel created|{n} NotesModulePluralLabel created', array_merge(array($value), LabelUtil::getTranslationParamsForAllModules())); } /** * @param array $userPointsByType * @param array $userScoresByType * @return int|string */ public static function badgeGradeUserShouldHaveByPointsAndScores($userPointsByType, $userScoresByType) { assert('is_array($userPointsByType)'); assert('is_array($userScoresByType)'); if (isset($userScoresByType['CreateNote'])) { return static::getBadgeGradeByValue((int)$userScoresByType['CreateNote']->value); } return 0; } } ?>
raymondlamwu/zurmotest
app/protected/modules/notes/rules/badges/CreateNoteGameBadgeRules.php
PHP
agpl-3.0
3,520
// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #include "SMESH_ControlsDef.hxx" #include "SMDS_BallElement.hxx" #include "SMDS_Iterator.hxx" #include "SMDS_Mesh.hxx" #include "SMDS_MeshElement.hxx" #include "SMDS_MeshNode.hxx" #include "SMDS_QuadraticEdge.hxx" #include "SMDS_QuadraticFaceOfNodes.hxx" #include "SMDS_VolumeTool.hxx" #include "SMESHDS_GroupBase.hxx" #include "SMESHDS_GroupOnFilter.hxx" #include "SMESHDS_Mesh.hxx" #include "SMESH_MeshAlgos.hxx" #include "SMESH_OctreeNode.hxx" #include <Basics_Utils.hxx> #include <BRepAdaptor_Surface.hxx> #include <BRepClass_FaceClassifier.hxx> #include <BRep_Tool.hxx> #include <Geom_CylindricalSurface.hxx> #include <Geom_Plane.hxx> #include <Geom_Surface.hxx> #include <Precision.hxx> #include <TColStd_MapIteratorOfMapOfInteger.hxx> #include <TColStd_MapOfInteger.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <TColgp_Array1OfXYZ.hxx> #include <TopAbs.hxx> #include <TopExp.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Iterator.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Vertex.hxx> #include <gp_Ax3.hxx> #include <gp_Cylinder.hxx> #include <gp_Dir.hxx> #include <gp_Pln.hxx> #include <gp_Pnt.hxx> #include <gp_Vec.hxx> #include <gp_XYZ.hxx> #include <vtkMeshQuality.h> #include <set> #include <limits> /* AUXILIARY METHODS */ namespace { const double theEps = 1e-100; const double theInf = 1e+100; inline gp_XYZ gpXYZ(const SMDS_MeshNode* aNode ) { return gp_XYZ(aNode->X(), aNode->Y(), aNode->Z() ); } inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec v1( P1 - P2 ), v2( P3 - P2 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 ); } inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec aVec1( P2 - P1 ); gp_Vec aVec2( P3 - P1 ); return ( aVec1 ^ aVec2 ).Magnitude() * 0.5; } inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 ) { return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() ); } inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 ) { double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) ); return aDist; } int getNbMultiConnection( const SMDS_Mesh* theMesh, const int theId ) { if ( theMesh == 0 ) return 0; const SMDS_MeshElement* anEdge = theMesh->FindElement( theId ); if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge/* || anEdge->NbNodes() != 2 */) return 0; // for each pair of nodes in anEdge (there are 2 pairs in a quadratic edge) // count elements containing both nodes of the pair. // Note that there may be such cases for a quadratic edge (a horizontal line): // // Case 1 Case 2 // | | | | | // | | | | | // +-----+------+ +-----+------+ // | | | | // | | | | // result sould be 2 in both cases // int aResult0 = 0, aResult1 = 0; // last node, it is a medium one in a quadratic edge const SMDS_MeshNode* aLastNode = anEdge->GetNode( anEdge->NbNodes() - 1 ); const SMDS_MeshNode* aNode0 = anEdge->GetNode( 0 ); const SMDS_MeshNode* aNode1 = anEdge->GetNode( 1 ); if ( aNode1 == aLastNode ) aNode1 = 0; SMDS_ElemIteratorPtr anElemIter = aLastNode->GetInverseElementIterator(); while( anElemIter->more() ) { const SMDS_MeshElement* anElem = anElemIter->next(); if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) { SMDS_ElemIteratorPtr anIter = anElem->nodesIterator(); while ( anIter->more() ) { if ( const SMDS_MeshElement* anElemNode = anIter->next() ) { if ( anElemNode == aNode0 ) { aResult0++; if ( !aNode1 ) break; // not a quadratic edge } else if ( anElemNode == aNode1 ) aResult1++; } } } } int aResult = std::max ( aResult0, aResult1 ); return aResult; } gp_XYZ getNormale( const SMDS_MeshFace* theFace, bool* ok=0 ) { int aNbNode = theFace->NbNodes(); gp_XYZ q1 = gpXYZ( theFace->GetNode(1)) - gpXYZ( theFace->GetNode(0)); gp_XYZ q2 = gpXYZ( theFace->GetNode(2)) - gpXYZ( theFace->GetNode(0)); gp_XYZ n = q1 ^ q2; if ( aNbNode > 3 ) { gp_XYZ q3 = gpXYZ( theFace->GetNode(3)) - gpXYZ( theFace->GetNode(0)); n += q2 ^ q3; } double len = n.Modulus(); bool zeroLen = ( len <= numeric_limits<double>::min()); if ( !zeroLen ) n /= len; if (ok) *ok = !zeroLen; return n; } } using namespace SMESH::Controls; /* * FUNCTORS */ //================================================================================ /* Class : NumericalFunctor Description : Base class for numerical functors */ //================================================================================ NumericalFunctor::NumericalFunctor(): myMesh(NULL) { myPrecision = -1; } void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool NumericalFunctor::GetPoints(const int theId, TSequenceOfXYZ& theRes ) const { theRes.clear(); if ( myMesh == 0 ) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || anElem->GetType() != this->GetType() ) return false; return GetPoints( anElem, theRes ); } bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem, TSequenceOfXYZ& theRes ) { theRes.clear(); if ( anElem == 0 ) return false; theRes.reserve( anElem->NbNodes() ); theRes.setElement( anElem ); // Get nodes of the element SMDS_ElemIteratorPtr anIter; if ( anElem->IsQuadratic() ) { switch ( anElem->GetType() ) { case SMDSAbs_Edge: anIter = dynamic_cast<const SMDS_VtkEdge*> (anElem)->interlacedNodesElemIterator(); break; case SMDSAbs_Face: anIter = dynamic_cast<const SMDS_VtkFace*> (anElem)->interlacedNodesElemIterator(); break; default: anIter = anElem->nodesIterator(); } } else { anIter = anElem->nodesIterator(); } if ( anIter ) { double xyz[3]; while( anIter->more() ) { if ( const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( anIter->next() )) { aNode->GetXYZ( xyz ); theRes.push_back( gp_XYZ( xyz[0], xyz[1], xyz[2] )); } } } return true; } long NumericalFunctor::GetPrecision() const { return myPrecision; } void NumericalFunctor::SetPrecision( const long thePrecision ) { myPrecision = thePrecision; myPrecisionValue = pow( 10., (double)( myPrecision ) ); } double NumericalFunctor::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); TSequenceOfXYZ P; if ( GetPoints( theId, P )) // elem type is checked here aVal = Round( GetValue( P )); return aVal; } double NumericalFunctor::Round( const double & aVal ) { return ( myPrecision >= 0 ) ? floor( aVal * myPrecisionValue + 0.5 ) / myPrecisionValue : aVal; } //================================================================================ /*! * \brief Return histogram of functor values * \param nbIntervals - number of intervals * \param nbEvents - number of mesh elements having values within i-th interval * \param funValues - boundaries of intervals * \param elements - elements to check vulue of; empty list means "of all" * \param minmax - boundaries of diapason of values to divide into intervals */ //================================================================================ void NumericalFunctor::GetHistogram(int nbIntervals, std::vector<int>& nbEvents, std::vector<double>& funValues, const vector<int>& elements, const double* minmax, const bool isLogarithmic) { if ( nbIntervals < 1 || !myMesh || !myMesh->GetMeshInfo().NbElements( GetType() )) return; nbEvents.resize( nbIntervals, 0 ); funValues.resize( nbIntervals+1 ); // get all values sorted std::multiset< double > values; if ( elements.empty() ) { SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator( GetType() ); while ( elemIt->more() ) values.insert( GetValue( elemIt->next()->GetID() )); } else { vector<int>::const_iterator id = elements.begin(); for ( ; id != elements.end(); ++id ) values.insert( GetValue( *id )); } if ( minmax ) { funValues[0] = minmax[0]; funValues[nbIntervals] = minmax[1]; } else { funValues[0] = *values.begin(); funValues[nbIntervals] = *values.rbegin(); } // case nbIntervals == 1 if ( nbIntervals == 1 ) { nbEvents[0] = values.size(); return; } // case of 1 value if (funValues.front() == funValues.back()) { nbEvents.resize( 1 ); nbEvents[0] = values.size(); funValues[1] = funValues.back(); funValues.resize( 2 ); } // generic case std::multiset< double >::iterator min = values.begin(), max; for ( int i = 0; i < nbIntervals; ++i ) { // find end value of i-th interval double r = (i+1) / double(nbIntervals); if (isLogarithmic && funValues.front() > 1e-07 && funValues.back() > 1e-07) { double logmin = log10(funValues.front()); double lval = logmin + r * (log10(funValues.back()) - logmin); funValues[i+1] = pow(10.0, lval); } else { funValues[i+1] = funValues.front() * (1-r) + funValues.back() * r; } // count values in the i-th interval if there are any if ( min != values.end() && *min <= funValues[i+1] ) { // find the first value out of the interval max = values.upper_bound( funValues[i+1] ); // max is greater than funValues[i+1], or end() nbEvents[i] = std::distance( min, max ); min = max; } } // add values larger than minmax[1] nbEvents.back() += std::distance( min, values.end() ); } //======================================================================= /* Class : Volume Description : Functor calculating volume of a 3D element */ //================================================================================ double Volume::GetValue( long theElementId ) { if ( theElementId && myMesh ) { SMDS_VolumeTool aVolumeTool; if ( aVolumeTool.Set( myMesh->FindElement( theElementId ))) return aVolumeTool.GetSize(); } return 0; } double Volume::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType Volume::GetType() const { return SMDSAbs_Volume; } //======================================================================= /* Class : MaxElementLength2D Description : Functor calculating maximum length of 2D element */ //================================================================================ double MaxElementLength2D::GetValue( const TSequenceOfXYZ& P ) { if(P.size() == 0) return 0.; double aVal = 0; int len = P.size(); if( len == 3 ) { // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 4 ) { // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 3 )); double D2 = getDistance(P( 2 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } else if( len == 6 ) { // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 8 || len == 9 ) { // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 5 )); double D2 = getDistance(P( 3 ),P( 7 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } // Diagonals are undefined for concave polygons // else if ( P.getElementEntity() == SMDSEntity_Quad_Polygon && P.size() > 2 ) // quad polygon // { // // sides // aVal = getDistance( P( 1 ), P( P.size() )) + getDistance( P( P.size() ), P( P.size()-1 )); // for ( size_t i = 1; i < P.size()-1; i += 2 ) // { // double L = getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 )); // aVal = Max( aVal, L ); // } // // diagonals // for ( int i = P.size()-5; i > 0; i -= 2 ) // for ( int j = i + 4; j < P.size() + i - 2; i += 2 ) // { // double D = getDistance( P( i ), P( j )); // aVal = Max( aVal, D ); // } // } // { // polygons // } if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } double MaxElementLength2D::GetValue( long theElementId ) { TSequenceOfXYZ P; return GetPoints( theElementId, P ) ? GetValue(P) : 0.0; } double MaxElementLength2D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength2D::GetType() const { return SMDSAbs_Face; } //======================================================================= /* Class : MaxElementLength3D Description : Functor calculating maximum length of 3D element */ //================================================================================ double MaxElementLength3D::GetValue( long theElementId ) { TSequenceOfXYZ P; if( GetPoints( theElementId, P ) ) { double aVal = 0; const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId ); SMDSAbs_ElementType aType = aElem->GetType(); int len = P.size(); switch( aType ) { case SMDSAbs_Volume: if( len == 4 ) { // tetras double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 5 ) { // pyramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 6 ) { // pentas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 8 ) { // hexas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len == 12 ) { // hexagonal prism for ( int i1 = 1; i1 < 12; ++i1 ) for ( int i2 = i1+1; i1 <= 12; ++i1 ) aVal = Max( aVal, getDistance(P( i1 ),P( i2 ))); break; } else if( len == 10 ) { // quadratic tetras double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 13 ) { // quadratic pyramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 15 ) { // quadratic pentas double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 20 || len == 27 ) { // quadratic hexas double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len > 1 && aElem->IsPoly() ) { // polys // get the maximum distance between all pairs of nodes for( int i = 1; i <= len; i++ ) { for( int j = 1; j <= len; j++ ) { if( j > i ) { // optimization of the loop double D = getDistance( P(i), P(j) ); aVal = Max( aVal, D ); } } } } } if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double MaxElementLength3D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength3D::GetType() const { return SMDSAbs_Volume; } //======================================================================= /* Class : MinimumAngle Description : Functor for calculation of minimum angle */ //================================================================================ double MinimumAngle::GetValue( const TSequenceOfXYZ& P ) { double aMin; if (P.size() <3) return 0.; aMin = getAngle(P( P.size() ), P( 1 ), P( 2 )); aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 ))); for ( int i = 2; i < P.size(); i++ ) { double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) ); aMin = Min(aMin,A0); } return aMin * 180.0 / M_PI; } double MinimumAngle::GetBadRate( double Value, int nbNodes ) const { //const double aBestAngle = PI / nbNodes; const double aBestAngle = 180.0 - ( 360.0 / double(nbNodes) ); return ( fabs( aBestAngle - Value )); } SMDSAbs_ElementType MinimumAngle::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : AspectRatio Description : Functor for calculating aspect ratio */ //================================================================================ double AspectRatio::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_QUAD ) { // issue 21723 vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::QuadAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio::GetValue( const TSequenceOfXYZ& P ) { // According to "Mesh quality control" by Nadir Bouhamau referring to // Pascal Jean Frey and Paul-Louis George. Maillages, applications aux elements finis. // Hermes Science publications, Paris 1999 ISBN 2-7462-0024-4 // PAL10872 int nbNodes = P.size(); if ( nbNodes < 3 ) return 0; // Compute aspect ratio if ( nbNodes == 3 ) { // Compute lengths of the sides std::vector< double > aLen (nbNodes); for ( int i = 0; i < nbNodes - 1; i++ ) aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) ); aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) ); // Q = alfa * h * p / S, where // // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if ( nbNodes == 6 ) { // quadratic triangles // Compute lengths of the sides std::vector< double > aLen (3); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(1) ); // Q = alfa * h * p / S, where // // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P(1), P(3), P(5) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if( nbNodes == 4 ) { // quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(2) ); aLen[1] = getDistance( P(2), P(3) ); aLen[2] = getDistance( P(3), P(4) ); aLen[3] = getDistance( P(4), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(3) ); aDia[1] = getDistance( P(2), P(4) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(2), P(3) ); anArea[1] = getArea( P(1), P(2), P(4) ); anArea[2] = getArea( P(1), P(3), P(4) ); anArea[3] = getArea( P(2), P(3), P(4) ); // Q = alpha * L * C1 / C2, where // // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } else if( nbNodes == 8 || nbNodes == 9 ) { // nbNodes==8 - quadratic quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(7) ); aLen[3] = getDistance( P(7), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(5) ); aDia[1] = getDistance( P(3), P(7) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(3), P(5) ); anArea[1] = getArea( P(1), P(3), P(7) ); anArea[2] = getArea( P(1), P(5), P(7) ); anArea[3] = getArea( P(3), P(5), P(7) ); // Q = alpha * L * C1 / C2, where // // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } return 0; } double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // < 1.0 = very bad, zero area // 1.0 = good // infinity = bad return ( Value < 0.9 ) ? 1000 : Value / 1000.; } SMDSAbs_ElementType AspectRatio::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : AspectRatio3D Description : Functor for calculating aspect ratio */ //================================================================================ namespace{ inline double getHalfPerimeter(double theTria[3]){ return (theTria[0] + theTria[1] + theTria[2])/2.0; } inline double getArea(double theHalfPerim, double theTria[3]){ return sqrt(theHalfPerim* (theHalfPerim-theTria[0])* (theHalfPerim-theTria[1])* (theHalfPerim-theTria[2])); } inline double getVolume(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = 4.0*a2*b2*d2; double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2); double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2); return sqrt(P-Q+R)/12.0; } inline double getVolume2(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = a2*e2*(b2+c2+d2+f2-a2-e2); double Q = b2*f2*(a2+c2+d2+e2-b2-f2); double R = c2*d2*(a2+b2+e2+f2-c2-d2); double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2; return sqrt(P+Q+R-S)/12.0; } inline double getVolume(const TSequenceOfXYZ& P){ gp_Vec aVec1( P( 2 ) - P( 1 ) ); gp_Vec aVec2( P( 3 ) - P( 1 ) ); gp_Vec aVec3( P( 4 ) - P( 1 ) ); gp_Vec anAreaVec( aVec1 ^ aVec2 ); return fabs(aVec3 * anAreaVec) / 6.0; } inline double getMaxHeight(double theLen[6]) { double aHeight = std::max(theLen[0],theLen[1]); aHeight = std::max(aHeight,theLen[2]); aHeight = std::max(aHeight,theLen[3]); aHeight = std::max(aHeight,theLen[4]); aHeight = std::max(aHeight,theLen[5]); return aHeight; } } double AspectRatio3D::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_TETRA ) { // Action from CoTech | ACTION 31.3: // EURIWARE BO: Homogenize the formulas used to calculate the Controls in SMESH to fit with // those of ParaView. The library used by ParaView for those calculations can be reused in SMESH. vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::TetAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio3D::GetValue( const TSequenceOfXYZ& P ) { double aQuality = 0.0; if(myCurrElement->IsPoly()) return aQuality; int nbNodes = P.size(); if(myCurrElement->IsQuadratic()) { if(nbNodes==10) nbNodes=4; // quadratic tetrahedron else if(nbNodes==13) nbNodes=5; // quadratic pyramid else if(nbNodes==15) nbNodes=6; // quadratic pentahedron else if(nbNodes==20) nbNodes=8; // quadratic hexahedron else if(nbNodes==27) nbNodes=8; // quadratic hexahedron else return aQuality; } switch(nbNodes) { case 4:{ double aLen[6] = { getDistance(P( 1 ),P( 2 )), // a getDistance(P( 2 ),P( 3 )), // b getDistance(P( 3 ),P( 1 )), // c getDistance(P( 2 ),P( 4 )), // d getDistance(P( 3 ),P( 4 )), // e getDistance(P( 1 ),P( 4 )) // f }; double aTria[4][3] = { {aLen[0],aLen[1],aLen[2]}, // abc {aLen[0],aLen[3],aLen[5]}, // adf {aLen[1],aLen[3],aLen[4]}, // bde {aLen[2],aLen[4],aLen[5]} // cef }; double aSumArea = 0.0; double aHalfPerimeter = getHalfPerimeter(aTria[0]); double anArea = getArea(aHalfPerimeter,aTria[0]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[1]); anArea = getArea(aHalfPerimeter,aTria[1]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[2]); anArea = getArea(aHalfPerimeter,aTria[2]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[3]); anArea = getArea(aHalfPerimeter,aTria[3]); aSumArea += anArea; double aVolume = getVolume(P); //double aVolume = getVolume(aLen); double aHeight = getMaxHeight(aLen); static double aCoeff = sqrt(2.0)/12.0; if ( aVolume > DBL_MIN ) aQuality = aCoeff*aHeight*aSumArea/aVolume; break; } case 5:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 6:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 8:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 12: { gp_XYZ aXYZ[8] = {P( 1 ),P( 2 ),P( 4 ),P( 5 ),P( 7 ),P( 8 ),P( 10 ),P( 11 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 2 ),P( 3 ),P( 5 ),P( 6 ),P( 8 ),P( 9 ),P( 11 ),P( 12 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 3 ),P( 4 ),P( 6 ),P( 1 ),P( 9 ),P( 10 ),P( 12 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } break; } // switch(nbNodes) if ( nbNodes > 4 ) { // avaluate aspect ratio of quadranle faces AspectRatio aspect2D; SMDS_VolumeTool::VolumeType type = SMDS_VolumeTool::GetType( nbNodes ); int nbFaces = SMDS_VolumeTool::NbFaces( type ); TSequenceOfXYZ points(4); for ( int i = 0; i < nbFaces; ++i ) { // loop on faces of a volume if ( SMDS_VolumeTool::NbFaceNodes( type, i ) != 4 ) continue; const int* pInd = SMDS_VolumeTool::GetFaceNodesIndices( type, i, true ); for ( int p = 0; p < 4; ++p ) // loop on nodes of a quadranle face points( p + 1 ) = P( pInd[ p ] + 1 ); aQuality = std::max( aQuality, aspect2D.GetValue( points )); } } return aQuality; } double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // 1.0 = good // infinity = bad return Value / 1000.; } SMDSAbs_ElementType AspectRatio3D::GetType() const { return SMDSAbs_Volume; } //================================================================================ /* Class : Warping Description : Functor for calculating warping */ //================================================================================ double Warping::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0; gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4.; double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G ); double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G ); double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G ); double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G ); double val = Max( Max( A1, A2 ), Max( A3, A4 ) ); const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } double Warping::ComputeA( const gp_XYZ& thePnt1, const gp_XYZ& thePnt2, const gp_XYZ& thePnt3, const gp_XYZ& theG ) const { double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) ); double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) ); double L = Min( aLen1, aLen2 ) * 0.5; if ( L < theEps ) return theInf; gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG; gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG; gp_XYZ N = GI.Crossed( GJ ); if ( N.Modulus() < gp::Resolution() ) return M_PI / 2; N.Normalize(); double H = ( thePnt2 - theG ).Dot( N ); return asin( fabs( H / L ) ) * 180. / M_PI; } double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const { // the warp is in the range [0.0,PI/2] // 0.0 = good (no warp) // PI/2 = bad (face pliee) return Value; } SMDSAbs_ElementType Warping::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Taper Description : Functor for calculating taper */ //================================================================================ double Taper::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0.; // Compute taper double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) ); double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) ); double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) ); double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) ); double JA = 0.25 * ( J1 + J2 + J3 + J4 ); if ( JA <= theEps ) return theInf; double T1 = fabs( ( J1 - JA ) / JA ); double T2 = fabs( ( J2 - JA ) / JA ); double T3 = fabs( ( J3 - JA ) / JA ); double T4 = fabs( ( J4 - JA ) / JA ); double val = Max( Max( T1, T2 ), Max( T3, T4 ) ); const double eps = 0.01; return val < eps ? 0. : val; } double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const { // the taper is in the range [0.0,1.0] // 0.0 = good (no taper) // 1.0 = bad (les cotes opposes sont allignes) return Value; } SMDSAbs_ElementType Taper::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Skew Description : Functor for calculating skew in degrees */ //================================================================================ static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 ) { gp_XYZ p12 = ( p2 + p1 ) / 2.; gp_XYZ p23 = ( p3 + p2 ) / 2.; gp_XYZ p31 = ( p3 + p1 ) / 2.; gp_Vec v1( p31 - p2 ), v2( p12 - p23 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0. : v1.Angle( v2 ); } double Skew::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 3 && P.size() != 4 ) return 0.; // Compute skew const double PI2 = M_PI / 2.; if ( P.size() == 3 ) { double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) ); double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) ); double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) ); return Max( A0, Max( A1, A2 ) ) * 180. / M_PI; } else { gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2.; gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2.; gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2.; gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2.; gp_Vec v1( p34 - p12 ), v2( p23 - p41 ); double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution() ? 0. : fabs( PI2 - v1.Angle( v2 ) ); double val = A * 180. / M_PI; const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } } double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const { // the skew is in the range [0.0,PI/2]. // 0.0 = good // PI/2 = bad return Value; } SMDSAbs_ElementType Skew::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Area Description : Functor for calculating area */ //================================================================================ double Area::GetValue( const TSequenceOfXYZ& P ) { double val = 0.0; if ( P.size() > 2 ) { gp_Vec aVec1( P(2) - P(1) ); gp_Vec aVec2( P(3) - P(1) ); gp_Vec SumVec = aVec1 ^ aVec2; for (int i=4; i<=P.size(); i++) { gp_Vec aVec1( P(i-1) - P(1) ); gp_Vec aVec2( P(i) - P(1) ); gp_Vec tmp = aVec1 ^ aVec2; SumVec.Add(tmp); } val = SumVec.Magnitude() * 0.5; } return val; } double Area::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Area::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Length Description : Functor for calculating length of edge */ //================================================================================ double Length::GetValue( const TSequenceOfXYZ& P ) { switch ( P.size() ) { case 2: return getDistance( P( 1 ), P( 2 ) ); case 3: return getDistance( P( 1 ), P( 2 ) ) + getDistance( P( 2 ), P( 3 ) ); default: return 0.; } } double Length::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType Length::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : Length2D Description : Functor for calculating minimal length of edge */ //================================================================================ double Length2D::GetValue( long theElementId ) { TSequenceOfXYZ P; if ( GetPoints( theElementId, P )) { double aVal = 0; int len = P.size(); SMDSAbs_EntityType aType = P.getElementEntity(); switch (aType) { case SMDSEntity_Edge: if (len == 2) aVal = getDistance( P( 1 ), P( 2 ) ); break; case SMDSEntity_Quad_Edge: if (len == 3) // quadratic edge aVal = getDistance(P( 1 ),P( 3 )) + getDistance(P( 3 ),P( 2 )); break; case SMDSEntity_Triangle: if (len == 3){ // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case SMDSEntity_Quadrangle: if (len == 4){ // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case SMDSEntity_Quad_Triangle: case SMDSEntity_BiQuad_Triangle: if (len >= 6){ // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case SMDSEntity_Quad_Quadrangle: case SMDSEntity_BiQuad_Quadrangle: if (len >= 8){ // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case SMDSEntity_Tetra: if (len == 4){ // tetrahedra double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case SMDSEntity_Pyramid: if (len == 5){ // piramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case SMDSEntity_Penta: if (len == 6) { // pentaidres double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case SMDSEntity_Hexa: if (len == 8){ // hexahedron double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case SMDSEntity_Quad_Tetra: if (len == 10){ // quadratic tetraidrs double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case SMDSEntity_Quad_Pyramid: if (len == 13){ // quadratic piramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case SMDSEntity_Quad_Penta: if (len == 15){ // quadratic pentaidres double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case SMDSEntity_Quad_Hexa: case SMDSEntity_TriQuad_Hexa: if (len >= 20) { // quadratic hexaider double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case SMDSEntity_Polygon: if ( len > 1 ) { aVal = getDistance( P(1), P( P.size() )); for ( size_t i = 1; i < P.size(); ++i ) aVal = Min( aVal, getDistance( P( i ), P( i+1 ))); } break; #ifndef VTK_NO_QUAD_POLY case SMDSEntity_Quad_Polygon: if ( len > 2 ) { aVal = getDistance( P(1), P( P.size() )) + getDistance( P(P.size()), P( P.size()-1 )); for ( size_t i = 1; i < P.size()-1; i += 2 ) aVal = Min( aVal, getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 ))); } break; #endif case SMDSEntity_Hexagonal_Prism: if (len == 12) { // hexagonal prism double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 1 )); double L7 = getDistance(P( 7 ), P( 8 )); double L8 = getDistance(P( 8 ), P( 9 )); double L9 = getDistance(P( 9 ), P( 10 )); double L10= getDistance(P( 10 ),P( 11 )); double L11= getDistance(P( 11 ),P( 12 )); double L12= getDistance(P( 12 ),P( 7 )); double L13 = getDistance(P( 1 ),P( 7 )); double L14 = getDistance(P( 2 ),P( 8 )); double L15 = getDistance(P( 3 ),P( 9 )); double L16 = getDistance(P( 4 ),P( 10 )); double L17 = getDistance(P( 5 ),P( 11 )); double L18 = getDistance(P( 6 ),P( 12 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal, Min(Min(Min(L7,L8),Min(L9,L10)),Min(L11,L12))); aVal = Min(aVal, Min(Min(Min(L13,L14),Min(L15,L16)),Min(L17,L18))); } break; case SMDSEntity_Polyhedra: { } break; default: return 0; } if (aVal < 0 ) { return 0.; } if ( myPrecision >= 0 ) { double prec = pow( 10., (double)( myPrecision ) ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Length2D::GetType() const { return SMDSAbs_Face; } Length2D::Value::Value(double theLength,long thePntId1, long thePntId2): myLength(theLength) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool Length2D::Value::operator<(const Length2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void Length2D::GetValues(TValues& theValues) { TValues aValues; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); if(anElem->IsQuadratic()) { const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(anElem); // use special nodes iterator SMDS_ElemIteratorPtr anIter = F->interlacedNodesElemIterator(); long aNodeId[4]; gp_Pnt P[4]; double aLength; const SMDS_MeshElement* aNode; if(anIter->more()){ aNode = anIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; anIter->more(); ){ const SMDS_MeshNode* N1 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[2] = gp_Pnt(N1->X(),N1->Y(),N1->Z()); aNodeId[2] = N1->GetID(); aLength = P[1].Distance(P[2]); if(!anIter->more()) break; const SMDS_MeshNode* N2 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[3] = gp_Pnt(N2->X(),N2->Y(),N2->Z()); aNodeId[3] = N2->GetID(); aLength += P[2].Distance(P[3]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[3]); P[1] = P[3]; aNodeId[1] = aNodeId[3]; theValues.insert(aValue1); theValues.insert(aValue2); } aLength += P[2].Distance(P[0]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[0]); theValues.insert(aValue1); theValues.insert(aValue2); } else { SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator(); long aNodeId[2]; gp_Pnt P[3]; double aLength; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; long anId = aNode->GetID(); P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aLength = P[1].Distance(P[2]); Value aValue(aLength,aNodeId[1],anId); aNodeId[1] = anId; P[1] = P[2]; theValues.insert(aValue); } aLength = P[0].Distance(P[1]); Value aValue(aLength,aNodeId[0],aNodeId[1]); theValues.insert(aValue); } } } //================================================================================ /* Class : MultiConnection Description : Functor for calculating number of faces conneted to the edge */ //================================================================================ double MultiConnection::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection::GetValue( long theId ) { return getNbMultiConnection( myMesh, theId ); } double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : MultiConnection2D Description : Functor for calculating number of faces conneted to the edge */ //================================================================================ double MultiConnection2D::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection2D::GetValue( long theElementId ) { int aResult = 0; const SMDS_MeshElement* aFaceElem = myMesh->FindElement(theElementId); SMDSAbs_ElementType aType = aFaceElem->GetType(); switch (aType) { case SMDSAbs_Face: { int i = 0, len = aFaceElem->NbNodes(); SMDS_ElemIteratorPtr anIter = aFaceElem->nodesIterator(); if (!anIter) break; const SMDS_MeshNode *aNode, *aNode0; TColStd_MapOfInteger aMap, aMapPrev; for (i = 0; i <= len; i++) { aMapPrev = aMap; aMap.Clear(); int aNb = 0; if (anIter->more()) { aNode = (SMDS_MeshNode*)anIter->next(); } else { if (i == len) aNode = aNode0; else break; } if (!aNode) break; if (i == 0) aNode0 = aNode; SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator(); while (anElemIter->more()) { const SMDS_MeshElement* anElem = anElemIter->next(); if (anElem != 0 && anElem->GetType() == SMDSAbs_Face) { int anId = anElem->GetID(); aMap.Add(anId); if (aMapPrev.Contains(anId)) { aNb++; } } } aResult = Max(aResult, aNb); } } break; default: aResult = 0; } return aResult; } double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection2D::GetType() const { return SMDSAbs_Face; } MultiConnection2D::Value::Value(long thePntId1, long thePntId2) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void MultiConnection2D::GetValues(MValues& theValues) { if ( !myMesh ) return; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); SMDS_ElemIteratorPtr aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = dynamic_cast<const SMDS_VtkFace*> (anElem)->interlacedNodesElemIterator(); else aNodesIter = anElem->nodesIterator(); long aNodeId[3]; //int aNbConnects=0; const SMDS_MeshNode* aNode0; const SMDS_MeshNode* aNode1; const SMDS_MeshNode* aNode2; if(aNodesIter->more()){ aNode0 = (SMDS_MeshNode*) aNodesIter->next(); aNode1 = aNode0; const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1; aNodeId[0] = aNodeId[1] = aNodes->GetID(); } for(; aNodesIter->more(); ) { aNode2 = (SMDS_MeshNode*) aNodesIter->next(); long anId = aNode2->GetID(); aNodeId[2] = anId; Value aValue(aNodeId[1],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()){ aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; aNodeId[1] = aNodeId[2]; aNode1 = aNode2; } Value aValue(aNodeId[0],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()) { aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; } } //================================================================================ /* Class : BallDiameter Description : Functor returning diameter of a ball element */ //================================================================================ double BallDiameter::GetValue( long theId ) { double diameter = 0; if ( const SMDS_BallElement* ball = dynamic_cast<const SMDS_BallElement*>( myMesh->FindElement( theId ))) { diameter = ball->GetDiameter(); } return diameter; } double BallDiameter::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType BallDiameter::GetType() const { return SMDSAbs_Ball; } /* PREDICATES */ //================================================================================ /* Class : BadOrientedVolume Description : Predicate bad oriented volumes */ //================================================================================ BadOrientedVolume::BadOrientedVolume() { myMesh = 0; } void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool BadOrientedVolume::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; SMDS_VolumeTool vTool( myMesh->FindElement( theId )); return !vTool.IsForward(); } SMDSAbs_ElementType BadOrientedVolume::GetType() const { return SMDSAbs_Volume; } /* Class : BareBorderVolume */ bool BareBorderVolume::IsSatisfy(long theElementId ) { SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( myTool.IsFreeFace( iF )) { const SMDS_MeshNode** n = myTool.GetFaceNodes(iF); vector< const SMDS_MeshNode*> nodes( n, n+myTool.NbFaceNodes(iF)); if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false)) return true; } } return false; } //================================================================================ /* Class : BareBorderFace */ //================================================================================ bool BareBorderFace::IsSatisfy(long theElementId ) { bool ok = false; if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) { if ( face->GetType() == SMDSAbs_Face ) { int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN && !ok; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( !isShared ) { const int iQuad = face->IsQuadratic(); myLinkNodes.resize( 2 + iQuad); myLinkNodes[0] = n1; myLinkNodes[1] = n2; if ( iQuad ) myLinkNodes[2] = face->GetNode( i+nbN ); ok = !myMesh->FindElement( myLinkNodes, SMDSAbs_Edge, /*noMedium=*/false); } } } } return ok; } //================================================================================ /* Class : OverConstrainedVolume */ //================================================================================ bool OverConstrainedVolume::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { int nbSharedFaces = 0; for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( !myTool.IsFreeFace( iF ) && ++nbSharedFaces > 1 ) break; return ( nbSharedFaces == 1 ); } return false; } //================================================================================ /* Class : OverConstrainedFace */ //================================================================================ bool OverConstrainedFace::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) if ( face->GetType() == SMDSAbs_Face ) { int nbSharedBorders = 0; int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( isShared && ++nbSharedBorders > 1 ) break; } return ( nbSharedBorders == 1 ); } return false; } //================================================================================ /* Class : CoincidentNodes Description : Predicate of Coincident nodes */ //================================================================================ CoincidentNodes::CoincidentNodes() { myToler = 1e-5; } bool CoincidentNodes::IsSatisfy( long theElementId ) { return myCoincidentIDs.Contains( theElementId ); } SMDSAbs_ElementType CoincidentNodes::GetType() const { return SMDSAbs_Node; } void CoincidentNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { TIDSortedNodeSet nodesToCheck; SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true); while ( nIt->more() ) nodesToCheck.insert( nodesToCheck.end(), nIt->next() ); list< list< const SMDS_MeshNode*> > nodeGroups; SMESH_OctreeNode::FindCoincidentNodes ( nodesToCheck, &nodeGroups, myToler ); myCoincidentIDs.Clear(); list< list< const SMDS_MeshNode*> >::iterator groupIt = nodeGroups.begin(); for ( ; groupIt != nodeGroups.end(); ++groupIt ) { list< const SMDS_MeshNode*>& coincNodes = *groupIt; list< const SMDS_MeshNode*>::iterator n = coincNodes.begin(); for ( ; n != coincNodes.end(); ++n ) myCoincidentIDs.Add( (*n)->GetID() ); } } } //================================================================================ /* Class : CoincidentElements Description : Predicate of Coincident Elements Note : This class is suitable only for visualization of Coincident Elements */ //================================================================================ CoincidentElements::CoincidentElements() { myMesh = 0; } void CoincidentElements::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool CoincidentElements::IsSatisfy( long theElementId ) { if ( !myMesh ) return false; if ( const SMDS_MeshElement* e = myMesh->FindElement( theElementId )) { if ( e->GetType() != GetType() ) return false; set< const SMDS_MeshNode* > elemNodes( e->begin_nodes(), e->end_nodes() ); const int nbNodes = e->NbNodes(); SMDS_ElemIteratorPtr invIt = (*elemNodes.begin())->GetInverseElementIterator( GetType() ); while ( invIt->more() ) { const SMDS_MeshElement* e2 = invIt->next(); if ( e2 == e || e2->NbNodes() != nbNodes ) continue; bool sameNodes = true; for ( size_t i = 0; i < elemNodes.size() && sameNodes; ++i ) sameNodes = ( elemNodes.count( e2->GetNode( i ))); if ( sameNodes ) return true; } } return false; } SMDSAbs_ElementType CoincidentElements1D::GetType() const { return SMDSAbs_Edge; } SMDSAbs_ElementType CoincidentElements2D::GetType() const { return SMDSAbs_Face; } SMDSAbs_ElementType CoincidentElements3D::GetType() const { return SMDSAbs_Volume; } //================================================================================ /* Class : FreeBorders Description : Predicate for free borders */ //================================================================================ FreeBorders::FreeBorders() { myMesh = 0; } void FreeBorders::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeBorders::IsSatisfy( long theId ) { return getNbMultiConnection( myMesh, theId ) == 1; } SMDSAbs_ElementType FreeBorders::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : FreeEdges Description : Predicate for free Edges */ //================================================================================ FreeEdges::FreeEdges() { myMesh = 0; } void FreeEdges::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId ) { TColStd_MapOfInteger aMap; for ( int i = 0; i < 2; i++ ) { SMDS_ElemIteratorPtr anElemIter = theNodes[ i ]->GetInverseElementIterator(SMDSAbs_Face); while( anElemIter->more() ) { if ( const SMDS_MeshElement* anElem = anElemIter->next()) { const int anId = anElem->GetID(); if ( anId != theFaceId && !aMap.Add( anId )) return false; } } } return true; } bool FreeEdges::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 ) return false; SMDS_NodeIteratorPtr anIter = aFace->interlacedNodesIterator(); if ( !anIter ) return false; int i = 0, nbNodes = aFace->NbNodes(); std::vector <const SMDS_MeshNode*> aNodes( nbNodes+1 ); while( anIter->more() ) if ( ! ( aNodes[ i++ ] = anIter->next() )) return false; aNodes[ nbNodes ] = aNodes[ 0 ]; for ( i = 0; i < nbNodes; i++ ) if ( IsFreeEdge( &aNodes[ i ], theId ) ) return true; return false; } SMDSAbs_ElementType FreeEdges::GetType() const { return SMDSAbs_Face; } FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2): myElemId(theElemId) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{ if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } inline void UpdateBorders(const FreeEdges::Border& theBorder, FreeEdges::TBorders& theRegistry, FreeEdges::TBorders& theContainer) { if(theRegistry.find(theBorder) == theRegistry.end()){ theRegistry.insert(theBorder); theContainer.insert(theBorder); }else{ theContainer.erase(theBorder); } } void FreeEdges::GetBoreders(TBorders& theBorders) { TBorders aRegistry; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); long anElemId = anElem->GetID(); SMDS_ElemIteratorPtr aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = static_cast<const SMDS_VtkFace*>(anElem)-> interlacedNodesElemIterator(); else aNodesIter = anElem->nodesIterator(); long aNodeId[2]; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); aNodeId[0] = aNodeId[1] = aNode->GetID(); } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); long anId = aNode->GetID(); Border aBorder(anElemId,aNodeId[1],anId); aNodeId[1] = anId; UpdateBorders(aBorder,aRegistry,theBorders); } Border aBorder(anElemId,aNodeId[0],aNodeId[1]); UpdateBorders(aBorder,aRegistry,theBorders); } } //================================================================================ /* Class : FreeNodes Description : Predicate for free nodes */ //================================================================================ FreeNodes::FreeNodes() { myMesh = 0; } void FreeNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeNodes::IsSatisfy( long theNodeId ) { const SMDS_MeshNode* aNode = myMesh->FindNode( theNodeId ); if (!aNode) return false; return (aNode->NbInverseElements() < 1); } SMDSAbs_ElementType FreeNodes::GetType() const { return SMDSAbs_Node; } //================================================================================ /* Class : FreeFaces Description : Predicate for free faces */ //================================================================================ FreeFaces::FreeFaces() { myMesh = 0; } void FreeFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeFaces::IsSatisfy( long theId ) { if (!myMesh) return false; // check that faces nodes refers to less than two common volumes const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( !aFace || aFace->GetType() != SMDSAbs_Face ) return false; int nbNode = aFace->NbNodes(); // collect volumes to check that number of volumes with count equal nbNode not less than 2 typedef map< SMDS_MeshElement*, int > TMapOfVolume; // map of volume counters typedef map< SMDS_MeshElement*, int >::iterator TItrMapOfVolume; // iterator TMapOfVolume mapOfVol; SMDS_ElemIteratorPtr nodeItr = aFace->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(nodeItr->next()); if ( !aNode ) continue; SMDS_ElemIteratorPtr volItr = aNode->GetInverseElementIterator(SMDSAbs_Volume); while ( volItr->more() ) { SMDS_MeshElement* aVol = (SMDS_MeshElement*)volItr->next(); TItrMapOfVolume itr = mapOfVol.insert(make_pair(aVol, 0)).first; (*itr).second++; } } int nbVol = 0; TItrMapOfVolume volItr = mapOfVol.begin(); TItrMapOfVolume volEnd = mapOfVol.end(); for ( ; volItr != volEnd; ++volItr ) if ( (*volItr).second >= nbNode ) nbVol++; // face is not free if number of volumes constructed on thier nodes more than one return (nbVol < 2); } SMDSAbs_ElementType FreeFaces::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : LinearOrQuadratic Description : Predicate to verify whether a mesh element is linear */ //================================================================================ LinearOrQuadratic::LinearOrQuadratic() { myMesh = 0; } void LinearOrQuadratic::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool LinearOrQuadratic::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || (myType != SMDSAbs_All && anElem->GetType() != myType) ) return false; return (!anElem->IsQuadratic()); } void LinearOrQuadratic::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType LinearOrQuadratic::GetType() const { return myType; } //================================================================================ /* Class : GroupColor Description : Functor for check color of group to whic mesh element belongs to */ //================================================================================ GroupColor::GroupColor() { } bool GroupColor::IsSatisfy( long theId ) { return myIDs.count( theId ); } void GroupColor::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType GroupColor::GetType() const { return myType; } static bool isEqual( const Quantity_Color& theColor1, const Quantity_Color& theColor2 ) { // tolerance to compare colors const double tol = 5*1e-3; return ( fabs( theColor1.Red() - theColor2.Red() ) < tol && fabs( theColor1.Green() - theColor2.Green() ) < tol && fabs( theColor1.Blue() - theColor2.Blue() ) < tol ); } void GroupColor::SetMesh( const SMDS_Mesh* theMesh ) { myIDs.clear(); const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh); if ( !aMesh ) return; int nbGrp = aMesh->GetNbGroups(); if ( !nbGrp ) return; // iterates on groups and find necessary elements ids const std::set<SMESHDS_GroupBase*>& aGroups = aMesh->GetGroups(); set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin(); for (; GrIt != aGroups.end(); GrIt++) { SMESHDS_GroupBase* aGrp = (*GrIt); if ( !aGrp ) continue; // check type and color of group if ( !isEqual( myColor, aGrp->GetColor() )) continue; // IPAL52867 (prevent infinite recursion via GroupOnFilter) if ( SMESHDS_GroupOnFilter * gof = dynamic_cast< SMESHDS_GroupOnFilter* >( aGrp )) if ( gof->GetPredicate().get() == this ) continue; SMDSAbs_ElementType aGrpElType = (SMDSAbs_ElementType)aGrp->GetType(); if ( myType == aGrpElType || (myType == SMDSAbs_All && aGrpElType != SMDSAbs_Node) ) { // add elements IDS into control int aSize = aGrp->Extent(); for (int i = 0; i < aSize; i++) myIDs.insert( aGrp->GetID(i+1) ); } } } void GroupColor::SetColorStr( const TCollection_AsciiString& theStr ) { Kernel_Utils::Localizer loc; TCollection_AsciiString aStr = theStr; aStr.RemoveAll( ' ' ); aStr.RemoveAll( '\t' ); for ( int aPos = aStr.Search( ";;" ); aPos != -1; aPos = aStr.Search( ";;" ) ) aStr.Remove( aPos, 2 ); Standard_Real clr[3]; clr[0] = clr[1] = clr[2] = 0.; for ( int i = 0; i < 3; i++ ) { TCollection_AsciiString tmpStr = aStr.Token( ";", i+1 ); if ( !tmpStr.IsEmpty() && tmpStr.IsRealValue() ) clr[i] = tmpStr.RealValue(); } myColor = Quantity_Color( clr[0], clr[1], clr[2], Quantity_TOC_RGB ); } //======================================================================= // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" //======================================================================= void GroupColor::GetColorStr( TCollection_AsciiString& theResStr ) const { theResStr.Clear(); theResStr += TCollection_AsciiString( myColor.Red() ); theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Green() ); theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Blue() ); } //================================================================================ /* Class : ElemGeomType Description : Predicate to check element geometry type */ //================================================================================ ElemGeomType::ElemGeomType() { myMesh = 0; myType = SMDSAbs_All; myGeomType = SMDSGeom_TRIANGLE; } void ElemGeomType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemGeomType::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem ) return false; const SMDSAbs_ElementType anElemType = anElem->GetType(); if ( myType != SMDSAbs_All && anElemType != myType ) return false; bool isOk = ( anElem->GetGeomType() == myGeomType ); return isOk; } void ElemGeomType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemGeomType::GetType() const { return myType; } void ElemGeomType::SetGeomType( SMDSAbs_GeometryType theType ) { myGeomType = theType; } SMDSAbs_GeometryType ElemGeomType::GetGeomType() const { return myGeomType; } //================================================================================ /* Class : ElemEntityType Description : Predicate to check element entity type */ //================================================================================ ElemEntityType::ElemEntityType(): myMesh( 0 ), myType( SMDSAbs_All ), myEntityType( SMDSEntity_0D ) { } void ElemEntityType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemEntityType::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) return myMesh->FindNode( theId ); const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); return ( anElem && myEntityType == anElem->GetEntityType() ); } void ElemEntityType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemEntityType::GetType() const { return myType; } void ElemEntityType::SetElemEntityType( SMDSAbs_EntityType theEntityType ) { myEntityType = theEntityType; } SMDSAbs_EntityType ElemEntityType::GetElemEntityType() const { return myEntityType; } //================================================================================ /*! * \brief Class ConnectedElements */ //================================================================================ ConnectedElements::ConnectedElements(): myNodeID(0), myType( SMDSAbs_All ), myOkIDsReady( false ) {} SMDSAbs_ElementType ConnectedElements::GetType() const { return myType; } int ConnectedElements::GetNode() const { return myXYZ.empty() ? myNodeID : 0; } // myNodeID can be found by myXYZ std::vector<double> ConnectedElements::GetPoint() const { return myXYZ; } void ConnectedElements::clearOkIDs() { myOkIDsReady = false; myOkIDs.clear(); } void ConnectedElements::SetType( SMDSAbs_ElementType theType ) { if ( myType != theType || myMeshModifTracer.IsMeshModified() ) clearOkIDs(); myType = theType; } void ConnectedElements::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { clearOkIDs(); if ( !myXYZ.empty() ) SetPoint( myXYZ[0], myXYZ[1], myXYZ[2] ); // find a node near myXYZ it in a new mesh } } void ConnectedElements::SetNode( int nodeID ) { myNodeID = nodeID; myXYZ.clear(); bool isSameDomain = false; if ( myOkIDsReady && myMeshModifTracer.GetMesh() && !myMeshModifTracer.IsMeshModified() ) if ( const SMDS_MeshNode* n = myMeshModifTracer.GetMesh()->FindNode( myNodeID )) { SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator( myType ); while ( !isSameDomain && eIt->more() ) isSameDomain = IsSatisfy( eIt->next()->GetID() ); } if ( !isSameDomain ) clearOkIDs(); } void ConnectedElements::SetPoint( double x, double y, double z ) { myXYZ.resize(3); myXYZ[0] = x; myXYZ[1] = y; myXYZ[2] = z; myNodeID = 0; bool isSameDomain = false; // find myNodeID by myXYZ if possible if ( myMeshModifTracer.GetMesh() ) { auto_ptr<SMESH_ElementSearcher> searcher ( SMESH_MeshAlgos::GetElementSearcher( (SMDS_Mesh&) *myMeshModifTracer.GetMesh() )); vector< const SMDS_MeshElement* > foundElems; searcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_All, foundElems ); if ( !foundElems.empty() ) { myNodeID = foundElems[0]->GetNode(0)->GetID(); if ( myOkIDsReady && !myMeshModifTracer.IsMeshModified() ) isSameDomain = IsSatisfy( foundElems[0]->GetID() ); } } if ( !isSameDomain ) clearOkIDs(); } bool ConnectedElements::IsSatisfy( long theElementId ) { // Here we do NOT check if the mesh has changed, we do it in Set...() only!!! if ( !myOkIDsReady ) { if ( !myMeshModifTracer.GetMesh() ) return false; const SMDS_MeshNode* node0 = myMeshModifTracer.GetMesh()->FindNode( myNodeID ); if ( !node0 ) return false; list< const SMDS_MeshNode* > nodeQueue( 1, node0 ); std::set< int > checkedNodeIDs; // algo: // foreach node in nodeQueue: // foreach element sharing a node: // add ID of an element of myType to myOkIDs; // push all element nodes absent from checkedNodeIDs to nodeQueue; while ( !nodeQueue.empty() ) { const SMDS_MeshNode* node = nodeQueue.front(); nodeQueue.pop_front(); // loop on elements sharing the node SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(); while ( eIt->more() ) { // keep elements of myType const SMDS_MeshElement* element = eIt->next(); if ( element->GetType() == myType ) myOkIDs.insert( myOkIDs.end(), element->GetID() ); // enqueue nodes of the element SMDS_ElemIteratorPtr nIt = element->nodesIterator(); while ( nIt->more() ) { const SMDS_MeshNode* n = static_cast< const SMDS_MeshNode* >( nIt->next() ); if ( checkedNodeIDs.insert( n->GetID() ).second ) nodeQueue.push_back( n ); } } } if ( myType == SMDSAbs_Node ) std::swap( myOkIDs, checkedNodeIDs ); size_t totalNbElems = myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType ); if ( myOkIDs.size() == totalNbElems ) myOkIDs.clear(); myOkIDsReady = true; } return myOkIDs.empty() ? true : myOkIDs.count( theElementId ); } //================================================================================ /*! * \brief Class CoplanarFaces */ //================================================================================ CoplanarFaces::CoplanarFaces() : myFaceID(0), myToler(0) { } void CoplanarFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { // Build a set of coplanar face ids myCoplanarIDs.clear(); if ( !myMeshModifTracer.GetMesh() || !myFaceID || !myToler ) return; const SMDS_MeshElement* face = myMeshModifTracer.GetMesh()->FindElement( myFaceID ); if ( !face || face->GetType() != SMDSAbs_Face ) return; bool normOK; gp_Vec myNorm = getNormale( static_cast<const SMDS_MeshFace*>(face), &normOK ); if (!normOK) return; const double radianTol = myToler * M_PI / 180.; std::set< SMESH_TLink > checkedLinks; std::list< pair< const SMDS_MeshElement*, gp_Vec > > faceQueue; faceQueue.push_back( make_pair( face, myNorm )); while ( !faceQueue.empty() ) { face = faceQueue.front().first; myNorm = faceQueue.front().second; faceQueue.pop_front(); for ( int i = 0, nbN = face->NbCornerNodes(); i < nbN; ++i ) { const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode(( i+1 )%nbN); if ( !checkedLinks.insert( SMESH_TLink( n1, n2 )).second ) continue; SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator(SMDSAbs_Face); while ( fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); if ( f->GetNodeIndex( n2 ) > -1 ) { gp_Vec norm = getNormale( static_cast<const SMDS_MeshFace*>(f), &normOK ); if (!normOK || myNorm.Angle( norm ) <= radianTol) { myCoplanarIDs.insert( f->GetID() ); faceQueue.push_back( make_pair( f, norm )); } } } } } } } bool CoplanarFaces::IsSatisfy( long theElementId ) { return myCoplanarIDs.count( theElementId ); } /* *Class : RangeOfIds *Description : Predicate for Range of Ids. * Range may be specified with two ways. * 1. Using AddToRange method * 2. With SetRangeStr method. Parameter of this method is a string * like as "1,2,3,50-60,63,67,70-" */ //======================================================================= // name : RangeOfIds // Purpose : Constructor //======================================================================= RangeOfIds::RangeOfIds() { myMesh = 0; myType = SMDSAbs_All; } //======================================================================= // name : SetMesh // Purpose : Set mesh //======================================================================= void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } //======================================================================= // name : AddToRange // Purpose : Add ID to the range //======================================================================= bool RangeOfIds::AddToRange( long theEntityId ) { myIds.Add( theEntityId ); return true; } //======================================================================= // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" //======================================================================= void RangeOfIds::GetRangeStr( TCollection_AsciiString& theResStr ) { theResStr.Clear(); TColStd_SequenceOfInteger anIntSeq; TColStd_SequenceOfAsciiString aStrSeq; TColStd_MapIteratorOfMapOfInteger anIter( myIds ); for ( ; anIter.More(); anIter.Next() ) { int anId = anIter.Key(); TCollection_AsciiString aStr( anId ); anIntSeq.Append( anId ); aStrSeq.Append( aStr ); } for ( int i = 1, n = myMin.Length(); i <= n; i++ ) { int aMinId = myMin( i ); int aMaxId = myMax( i ); TCollection_AsciiString aStr; if ( aMinId != IntegerFirst() ) aStr += aMinId; aStr += "-"; if ( aMaxId != IntegerLast() ) aStr += aMaxId; // find position of the string in result sequence and insert string in it if ( anIntSeq.Length() == 0 ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else { if ( aMinId < anIntSeq.First() ) { anIntSeq.Prepend( aMinId ); aStrSeq.Prepend( aStr ); } else if ( aMinId > anIntSeq.Last() ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ ) if ( aMinId < anIntSeq( j ) ) { anIntSeq.InsertBefore( j, aMinId ); aStrSeq.InsertBefore( j, aStr ); break; } } } if ( aStrSeq.Length() == 0 ) return; theResStr = aStrSeq( 1 ); for ( int j = 2, k = aStrSeq.Length(); j <= k; j++ ) { theResStr += ","; theResStr += aStrSeq( j ); } } //======================================================================= // name : SetRangeStr // Purpose : Define range with string // Example of entry string: "1,2,3,50-60,63,67,70-" //======================================================================= bool RangeOfIds::SetRangeStr( const TCollection_AsciiString& theStr ) { myMin.Clear(); myMax.Clear(); myIds.Clear(); TCollection_AsciiString aStr = theStr; //aStr.RemoveAll( ' ' ); //aStr.RemoveAll( '\t' ); for ( int i = 1; i <= aStr.Length(); ++i ) if ( isspace( aStr.Value( i ))) aStr.SetValue( i, ','); for ( int aPos = aStr.Search( ",," ); aPos != -1; aPos = aStr.Search( ",," ) ) aStr.Remove( aPos, 1 ); TCollection_AsciiString tmpStr = aStr.Token( ",", 1 ); int i = 1; while ( tmpStr != "" ) { tmpStr = aStr.Token( ",", i++ ); int aPos = tmpStr.Search( '-' ); if ( aPos == -1 ) { if ( tmpStr.IsIntegerValue() ) myIds.Add( tmpStr.IntegerValue() ); else return false; } else { TCollection_AsciiString aMaxStr = tmpStr.Split( aPos ); TCollection_AsciiString aMinStr = tmpStr; while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' ); while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' ); if ( (!aMinStr.IsEmpty() && !aMinStr.IsIntegerValue()) || (!aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue()) ) return false; myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() ); myMax.Append( aMaxStr.IsEmpty() ? IntegerLast() : aMaxStr.IntegerValue() ); } } return true; } //======================================================================= // name : GetType // Purpose : Get type of supported entities //======================================================================= SMDSAbs_ElementType RangeOfIds::GetType() const { return myType; } //======================================================================= // name : SetType // Purpose : Set type of supported entities //======================================================================= void RangeOfIds::SetType( SMDSAbs_ElementType theType ) { myType = theType; } //======================================================================= // name : IsSatisfy // Purpose : Verify whether entity satisfies to this rpedicate //======================================================================= bool RangeOfIds::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) { if ( myMesh->FindNode( theId ) == 0 ) return false; } else { const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( anElem == 0 || (myType != anElem->GetType() && myType != SMDSAbs_All )) return false; } if ( myIds.Contains( theId ) ) return true; for ( int i = 1, n = myMin.Length(); i <= n; i++ ) if ( theId >= myMin( i ) && theId <= myMax( i ) ) return true; return false; } /* Class : Comparator Description : Base class for comparators */ Comparator::Comparator(): myMargin(0) {} Comparator::~Comparator() {} void Comparator::SetMesh( const SMDS_Mesh* theMesh ) { if ( myFunctor ) myFunctor->SetMesh( theMesh ); } void Comparator::SetMargin( double theValue ) { myMargin = theValue; } void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct ) { myFunctor = theFunct; } SMDSAbs_ElementType Comparator::GetType() const { return myFunctor ? myFunctor->GetType() : SMDSAbs_All; } double Comparator::GetMargin() { return myMargin; } /* Class : LessThan Description : Comparator "<" */ bool LessThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) < myMargin; } /* Class : MoreThan Description : Comparator ">" */ bool MoreThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) > myMargin; } /* Class : EqualTo Description : Comparator "=" */ EqualTo::EqualTo(): myToler(Precision::Confusion()) {} bool EqualTo::IsSatisfy( long theId ) { return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler; } void EqualTo::SetTolerance( double theToler ) { myToler = theToler; } double EqualTo::GetTolerance() { return myToler; } /* Class : LogicalNOT Description : Logical NOT predicate */ LogicalNOT::LogicalNOT() {} LogicalNOT::~LogicalNOT() {} bool LogicalNOT::IsSatisfy( long theId ) { return myPredicate && !myPredicate->IsSatisfy( theId ); } void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate ) myPredicate->SetMesh( theMesh ); } void LogicalNOT::SetPredicate( PredicatePtr thePred ) { myPredicate = thePred; } SMDSAbs_ElementType LogicalNOT::GetType() const { return myPredicate ? myPredicate->GetType() : SMDSAbs_All; } /* Class : LogicalBinary Description : Base class for binary logical predicate */ LogicalBinary::LogicalBinary() {} LogicalBinary::~LogicalBinary() {} void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate1 ) myPredicate1->SetMesh( theMesh ); if ( myPredicate2 ) myPredicate2->SetMesh( theMesh ); } void LogicalBinary::SetPredicate1( PredicatePtr thePredicate ) { myPredicate1 = thePredicate; } void LogicalBinary::SetPredicate2( PredicatePtr thePredicate ) { myPredicate2 = thePredicate; } SMDSAbs_ElementType LogicalBinary::GetType() const { if ( !myPredicate1 || !myPredicate2 ) return SMDSAbs_All; SMDSAbs_ElementType aType1 = myPredicate1->GetType(); SMDSAbs_ElementType aType2 = myPredicate2->GetType(); return aType1 == aType2 ? aType1 : SMDSAbs_All; } /* Class : LogicalAND Description : Logical AND */ bool LogicalAND::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && myPredicate1->IsSatisfy( theId ) && myPredicate2->IsSatisfy( theId ); } /* Class : LogicalOR Description : Logical OR */ bool LogicalOR::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && (myPredicate1->IsSatisfy( theId ) || myPredicate2->IsSatisfy( theId )); } /* FILTER */ // #ifdef WITH_TBB // #include <tbb/parallel_for.h> // #include <tbb/enumerable_thread_specific.h> // namespace Parallel // { // typedef tbb::enumerable_thread_specific< TIdSequence > TIdSeq; // struct Predicate // { // const SMDS_Mesh* myMesh; // PredicatePtr myPredicate; // TIdSeq & myOKIds; // Predicate( const SMDS_Mesh* m, PredicatePtr p, TIdSeq & ids ): // myMesh(m), myPredicate(p->Duplicate()), myOKIds(ids) {} // void operator() ( const tbb::blocked_range<size_t>& r ) const // { // for ( size_t i = r.begin(); i != r.end(); ++i ) // if ( myPredicate->IsSatisfy( i )) // myOKIds.local().push_back(); // } // } // } // #endif Filter::Filter() {} Filter::~Filter() {} void Filter::SetPredicate( PredicatePtr thePredicate ) { myPredicate = thePredicate; } void Filter::GetElementsId( const SMDS_Mesh* theMesh, PredicatePtr thePredicate, TIdSequence& theSequence ) { theSequence.clear(); if ( !theMesh || !thePredicate ) return; thePredicate->SetMesh( theMesh ); SMDS_ElemIteratorPtr elemIt = theMesh->elementsIterator( thePredicate->GetType() ); if ( elemIt ) { while ( elemIt->more() ) { const SMDS_MeshElement* anElem = elemIt->next(); long anId = anElem->GetID(); if ( thePredicate->IsSatisfy( anId ) ) theSequence.push_back( anId ); } } } void Filter::GetElementsId( const SMDS_Mesh* theMesh, Filter::TIdSequence& theSequence ) { GetElementsId(theMesh,myPredicate,theSequence); } /* ManifoldPart */ typedef std::set<SMDS_MeshFace*> TMapOfFacePtr; /* Internal class Link */ ManifoldPart::Link::Link( SMDS_MeshNode* theNode1, SMDS_MeshNode* theNode2 ) { myNode1 = theNode1; myNode2 = theNode2; } ManifoldPart::Link::~Link() { myNode1 = 0; myNode2 = 0; } bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const { if ( myNode1 == theLink.myNode1 && myNode2 == theLink.myNode2 ) return true; else if ( myNode1 == theLink.myNode2 && myNode2 == theLink.myNode1 ) return true; else return false; } bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const { if(myNode1 < x.myNode1) return true; if(myNode1 == x.myNode1) if(myNode2 < x.myNode2) return true; return false; } bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1, const ManifoldPart::Link& theLink2 ) { return theLink1.IsEqual( theLink2 ); } ManifoldPart::ManifoldPart() { myMesh = 0; myAngToler = Precision::Angular(); myIsOnlyManifold = true; } ManifoldPart::~ManifoldPart() { myMesh = 0; } void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; process(); } SMDSAbs_ElementType ManifoldPart::GetType() const { return SMDSAbs_Face; } bool ManifoldPart::IsSatisfy( long theElementId ) { return myMapIds.Contains( theElementId ); } void ManifoldPart::SetAngleTolerance( const double theAngToler ) { myAngToler = theAngToler; } double ManifoldPart::GetAngleTolerance() const { return myAngToler; } void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly ) { myIsOnlyManifold = theIsOnly; } void ManifoldPart::SetStartElem( const long theStartId ) { myStartElemId = theStartId; } bool ManifoldPart::process() { myMapIds.Clear(); myMapBadGeomIds.Clear(); myAllFacePtr.clear(); myAllFacePtrIntDMap.clear(); if ( !myMesh ) return false; // collect all faces into own map SMDS_FaceIteratorPtr anFaceItr = myMesh->facesIterator(); for (; anFaceItr->more(); ) { SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next(); myAllFacePtr.push_back( aFacePtr ); myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1; } SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId ); if ( !aStartFace ) return false; // the map of non manifold links and bad geometry TMapOfLink aMapOfNonManifold; TColStd_MapOfInteger aMapOfTreated; // begin cycle on faces from start index and run on vector till the end // and from begin to start index to cover whole vector const int aStartIndx = myAllFacePtrIntDMap[aStartFace]; bool isStartTreat = false; for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ ) { if ( fi == aStartIndx ) isStartTreat = true; // as result next time when fi will be equal to aStartIndx SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ]; if ( aMapOfTreated.Contains( aFacePtr->GetID() ) ) continue; aMapOfTreated.Add( aFacePtr->GetID() ); TColStd_MapOfInteger aResFaces; if ( !findConnected( myAllFacePtrIntDMap, aFacePtr, aMapOfNonManifold, aResFaces ) ) continue; TColStd_MapIteratorOfMapOfInteger anItr( aResFaces ); for ( ; anItr.More(); anItr.Next() ) { int aFaceId = anItr.Key(); aMapOfTreated.Add( aFaceId ); myMapIds.Add( aFaceId ); } if ( fi == ( myAllFacePtr.size() - 1 ) ) fi = 0; } // end run on vector of faces return !myMapIds.IsEmpty(); } static void getLinks( const SMDS_MeshFace* theFace, ManifoldPart::TVectorOfLink& theLinks ) { int aNbNode = theFace->NbNodes(); SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator(); int i = 1; SMDS_MeshNode* aNode = 0; for ( ; aNodeItr->more() && i <= aNbNode; ) { SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next(); if ( i == 1 ) aNode = aN1; i++; SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next(); i++; ManifoldPart::Link aLink( aN1, aN2 ); theLinks.push_back( aLink ); } } bool ManifoldPart::findConnected ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt, SMDS_MeshFace* theStartFace, ManifoldPart::TMapOfLink& theNonManifold, TColStd_MapOfInteger& theResFaces ) { theResFaces.Clear(); if ( !theAllFacePtrInt.size() ) return false; if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theStartFace->GetID() ); return false; } ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip; ManifoldPart::TVectorOfLink aSeqOfBoundary; theResFaces.Add( theStartFace->GetID() ); ManifoldPart::TDataMapOfLinkFacePtr aDMapLinkFace; expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, theStartFace ); bool isDone = false; while ( !isDone && aMapOfBoundary.size() != 0 ) { bool isToReset = false; ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin(); for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aLink = *pLink; if ( aMapToSkip.find( aLink ) != aMapToSkip.end() ) continue; // each link could be treated only once aMapToSkip.insert( aLink ); ManifoldPart::TVectorOfFacePtr aFaces; // find next if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; else { getFacesByLink( aLink, aFaces ); // filter the element to keep only indicated elements ManifoldPart::TVectorOfFacePtr aFiltered; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aFace = *pFace; if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() ) aFiltered.push_back( aFace ); } aFaces = aFiltered; if ( aFaces.size() < 2 ) // no neihgbour faces continue; else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case { theNonManifold.insert( aLink ); continue; } } // compare normal with normals of neighbor element SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ]; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aNextFace = *pFace; if ( aPrevFace == aNextFace ) continue; int anNextFaceID = aNextFace->GetID(); if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) ) // should not be with non manifold restriction. probably bad topology continue; // check if face was treated and skipped if ( myMapBadGeomIds.Contains( anNextFaceID ) || !isInPlane( aPrevFace, aNextFace ) ) continue; // add new element to connected and extend the boundaries. theResFaces.Add( anNextFaceID ); expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, aNextFace ); isToReset = true; } } isDone = !isToReset; } return !theResFaces.IsEmpty(); } bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1, const SMDS_MeshFace* theFace2 ) { gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) ); gp_XYZ aNorm2XYZ = getNormale( theFace2 ); if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theFace2->GetID() ); return false; } if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) ) return true; return false; } void ManifoldPart::expandBoundary ( ManifoldPart::TMapOfLink& theMapOfBoundary, ManifoldPart::TVectorOfLink& theSeqOfBoundary, ManifoldPart::TDataMapOfLinkFacePtr& theDMapLinkFacePtr, ManifoldPart::TMapOfLink& theNonManifold, SMDS_MeshFace* theNextFace ) const { ManifoldPart::TVectorOfLink aLinks; getLinks( theNextFace, aLinks ); int aNbLink = (int)aLinks.size(); for ( int i = 0; i < aNbLink; i++ ) { ManifoldPart::Link aLink = aLinks[ i ]; if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() ) { if ( myIsOnlyManifold ) { // remove from boundary theMapOfBoundary.erase( aLink ); ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin(); for ( ; pLink != theSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aBoundLink = *pLink; if ( aBoundLink.IsEqual( aLink ) ) { theSeqOfBoundary.erase( pLink ); break; } } } } else { theMapOfBoundary.insert( aLink ); theSeqOfBoundary.push_back( aLink ); theDMapLinkFacePtr[ aLink ] = theNextFace; } } } void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink, ManifoldPart::TVectorOfFacePtr& theFaces ) const { std::set<SMDS_MeshCell *> aSetOfFaces; // take all faces that shared first node SMDS_ElemIteratorPtr anItr = theLink.myNode1->facesIterator(); for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( !aFace ) continue; aSetOfFaces.insert( aFace ); } // take all faces that shared second node anItr = theLink.myNode2->facesIterator(); // find the common part of two sets for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( aSetOfFaces.count( aFace ) ) theFaces.push_back( aFace ); } } /* Class : BelongToMeshGroup Description : Verify whether a mesh element is included into a mesh group */ BelongToMeshGroup::BelongToMeshGroup(): myGroup( 0 ) { } void BelongToMeshGroup::SetGroup( SMESHDS_GroupBase* g ) { myGroup = g; } void BelongToMeshGroup::SetStoreName( const std::string& sn ) { myStoreName = sn; } void BelongToMeshGroup::SetMesh( const SMDS_Mesh* theMesh ) { if ( myGroup && myGroup->GetMesh() != theMesh ) { myGroup = 0; } if ( !myGroup && !myStoreName.empty() ) { if ( const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh)) { const std::set<SMESHDS_GroupBase*>& grps = aMesh->GetGroups(); std::set<SMESHDS_GroupBase*>::const_iterator g = grps.begin(); for ( ; g != grps.end() && !myGroup; ++g ) if ( *g && myStoreName == (*g)->GetStoreName() ) myGroup = *g; } } if ( myGroup ) { myGroup->IsEmpty(); // make GroupOnFilter update its predicate } } bool BelongToMeshGroup::IsSatisfy( long theElementId ) { return myGroup ? myGroup->Contains( theElementId ) : false; } SMDSAbs_ElementType BelongToMeshGroup::GetType() const { return myGroup ? myGroup->GetType() : SMDSAbs_All; } /* ElementsOnSurface */ ElementsOnSurface::ElementsOnSurface() { myIds.Clear(); myType = SMDSAbs_All; mySurf.Nullify(); myToler = Precision::Confusion(); myUseBoundaries = false; } ElementsOnSurface::~ElementsOnSurface() { } void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) process(); } bool ElementsOnSurface::IsSatisfy( long theElementId ) { return myIds.Contains( theElementId ); } SMDSAbs_ElementType ElementsOnSurface::GetType() const { return myType; } void ElementsOnSurface::SetTolerance( const double theToler ) { if ( myToler != theToler ) myIds.Clear(); myToler = theToler; } double ElementsOnSurface::GetTolerance() const { return myToler; } void ElementsOnSurface::SetUseBoundaries( bool theUse ) { if ( myUseBoundaries != theUse ) { myUseBoundaries = theUse; SetSurface( mySurf, myType ); } } void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType ) { myIds.Clear(); myType = theType; mySurf.Nullify(); if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE ) return; mySurf = TopoDS::Face( theShape ); BRepAdaptor_Surface SA( mySurf, myUseBoundaries ); Standard_Real u1 = SA.FirstUParameter(), u2 = SA.LastUParameter(), v1 = SA.FirstVParameter(), v2 = SA.LastVParameter(); Handle(Geom_Surface) surf = BRep_Tool::Surface( mySurf ); myProjector.Init( surf, u1,u2, v1,v2 ); process(); } void ElementsOnSurface::process() { myIds.Clear(); if ( mySurf.IsNull() ) return; if ( !myMeshModifTracer.GetMesh() ) return; myIds.ReSize( myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType )); SMDS_ElemIteratorPtr anIter = myMeshModifTracer.GetMesh()->elementsIterator( myType ); for(; anIter->more(); ) process( anIter->next() ); } void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr ) { SMDS_ElemIteratorPtr aNodeItr = theElemPtr->nodesIterator(); bool isSatisfy = true; for ( ; aNodeItr->more(); ) { SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next(); if ( !isOnSurface( aNode ) ) { isSatisfy = false; break; } } if ( isSatisfy ) myIds.Add( theElemPtr->GetID() ); } bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode ) { if ( mySurf.IsNull() ) return false; gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() ); // double aToler2 = myToler * myToler; // if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane))) // { // gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln(); // if ( aPln.SquareDistance( aPnt ) > aToler2 ) // return false; // } // else if ( mySurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) // { // gp_Cylinder aCyl = Handle(Geom_CylindricalSurface)::DownCast(mySurf)->Cylinder(); // double aRad = aCyl.Radius(); // gp_Ax3 anAxis = aCyl.Position(); // gp_XYZ aLoc = aCyl.Location().XYZ(); // double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 ) // return false; // } // else // return false; myProjector.Perform( aPnt ); bool isOn = ( myProjector.IsDone() && myProjector.LowerDistance() <= myToler ); return isOn; } /* ElementsOnShape */ ElementsOnShape::ElementsOnShape() : //myMesh(0), myType(SMDSAbs_All), myToler(Precision::Confusion()), myAllNodesFlag(false) { } ElementsOnShape::~ElementsOnShape() { clearClassifiers(); } SMDSAbs_ElementType ElementsOnShape::GetType() const { return myType; } void ElementsOnShape::SetTolerance (const double theToler) { if (myToler != theToler) { myToler = theToler; SetShape(myShape, myType); } } double ElementsOnShape::GetTolerance() const { return myToler; } void ElementsOnShape::SetAllNodes (bool theAllNodes) { myAllNodesFlag = theAllNodes; } void ElementsOnShape::SetMesh (const SMDS_Mesh* theMesh) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) { size_t nbNodes = theMesh ? theMesh->NbNodes() : 0; if ( myNodeIsChecked.size() == nbNodes ) { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } else { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); myNodeIsChecked.resize( nbNodes, false ); myNodeIsOut.resize( nbNodes ); } } } bool ElementsOnShape::getNodeIsOut( const SMDS_MeshNode* n, bool& isOut ) { if ( n->GetID() >= (int) myNodeIsChecked.size() || !myNodeIsChecked[ n->GetID() ]) return false; isOut = myNodeIsOut[ n->GetID() ]; return true; } void ElementsOnShape::setNodeIsOut( const SMDS_MeshNode* n, bool isOut ) { if ( n->GetID() < (int) myNodeIsChecked.size() ) { myNodeIsChecked[ n->GetID() ] = true; myNodeIsOut [ n->GetID() ] = isOut; } } void ElementsOnShape::SetShape (const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType) { myType = theType; myShape = theShape; if ( myShape.IsNull() ) return; TopTools_IndexedMapOfShape shapesMap; TopAbs_ShapeEnum shapeTypes[4] = { TopAbs_SOLID, TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX }; TopExp_Explorer sub; for ( int i = 0; i < 4; ++i ) { if ( shapesMap.IsEmpty() ) for ( sub.Init( myShape, shapeTypes[i] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); if ( i > 0 ) for ( sub.Init( myShape, shapeTypes[i], shapeTypes[i-1] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); } clearClassifiers(); myClassifiers.resize( shapesMap.Extent() ); for ( int i = 0; i < shapesMap.Extent(); ++i ) myClassifiers[ i ] = new TClassifier( shapesMap( i+1 ), myToler ); if ( theType == SMDSAbs_Node ) { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); } else { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } } void ElementsOnShape::clearClassifiers() { for ( size_t i = 0; i < myClassifiers.size(); ++i ) delete myClassifiers[ i ]; myClassifiers.clear(); } bool ElementsOnShape::IsSatisfy (long elemId) { const SMDS_Mesh* mesh = myMeshModifTracer.GetMesh(); const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ? mesh->FindNode( elemId ) : mesh->FindElement( elemId )); if ( !elem || myClassifiers.empty() ) return false; bool isSatisfy = myAllNodesFlag, isNodeOut; gp_XYZ centerXYZ (0, 0, 0); SMDS_ElemIteratorPtr aNodeItr = elem->nodesIterator(); while (aNodeItr->more() && (isSatisfy == myAllNodesFlag)) { SMESH_TNodeXYZ aPnt( aNodeItr->next() ); centerXYZ += aPnt; isNodeOut = true; if ( !getNodeIsOut( aPnt._node, isNodeOut )) { for ( size_t i = 0; i < myClassifiers.size() && isNodeOut; ++i ) isNodeOut = myClassifiers[i]->IsOut( aPnt ); setNodeIsOut( aPnt._node, isNodeOut ); } isSatisfy = !isNodeOut; } // Check the center point for volumes MantisBug 0020168 if (isSatisfy && myAllNodesFlag && myClassifiers[0]->ShapeType() == TopAbs_SOLID) { centerXYZ /= elem->NbNodes(); isSatisfy = false; for ( size_t i = 0; i < myClassifiers.size() && !isSatisfy; ++i ) isSatisfy = ! myClassifiers[i]->IsOut( centerXYZ ); } return isSatisfy; } TopAbs_ShapeEnum ElementsOnShape::TClassifier::ShapeType() const { return myShape.ShapeType(); } bool ElementsOnShape::TClassifier::IsOut(const gp_Pnt& p) { return (this->*myIsOutFun)( p ); } void ElementsOnShape::TClassifier::Init (const TopoDS_Shape& theShape, double theTol) { myShape = theShape; myTol = theTol; switch ( myShape.ShapeType() ) { case TopAbs_SOLID: { if ( isBox( theShape )) { myIsOutFun = & ElementsOnShape::TClassifier::isOutOfBox; } else { mySolidClfr.Load(theShape); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfSolid; } break; } case TopAbs_FACE: { Standard_Real u1,u2,v1,v2; Handle(Geom_Surface) surf = BRep_Tool::Surface( TopoDS::Face( theShape )); surf->Bounds( u1,u2,v1,v2 ); myProjFace.Init(surf, u1,u2, v1,v2, myTol ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfFace; break; } case TopAbs_EDGE: { Standard_Real u1, u2; Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge(theShape), u1, u2); myProjEdge.Init(curve, u1, u2); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfEdge; break; } case TopAbs_VERTEX:{ myVertexXYZ = BRep_Tool::Pnt( TopoDS::Vertex( theShape ) ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfVertex; break; } default: throw SALOME_Exception("Programmer error in usage of ElementsOnShape::TClassifier"); } } bool ElementsOnShape::TClassifier::isOutOfSolid (const gp_Pnt& p) { mySolidClfr.Perform( p, myTol ); return ( mySolidClfr.State() != TopAbs_IN && mySolidClfr.State() != TopAbs_ON ); } bool ElementsOnShape::TClassifier::isOutOfBox (const gp_Pnt& p) { return myBox.IsOut( p.XYZ() ); } bool ElementsOnShape::TClassifier::isOutOfFace (const gp_Pnt& p) { myProjFace.Perform( p ); if ( myProjFace.IsDone() && myProjFace.LowerDistance() <= myTol ) { // check relatively to the face Quantity_Parameter u, v; myProjFace.LowerDistanceParameters(u, v); gp_Pnt2d aProjPnt (u, v); BRepClass_FaceClassifier aClsf ( TopoDS::Face( myShape ), aProjPnt, myTol ); if ( aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON ) return false; } return true; } bool ElementsOnShape::TClassifier::isOutOfEdge (const gp_Pnt& p) { myProjEdge.Perform( p ); return ! ( myProjEdge.NbPoints() > 0 && myProjEdge.LowerDistance() <= myTol ); } bool ElementsOnShape::TClassifier::isOutOfVertex(const gp_Pnt& p) { return ( myVertexXYZ.Distance( p ) > myTol ); } bool ElementsOnShape::TClassifier::isBox (const TopoDS_Shape& theShape) { TopTools_IndexedMapOfShape vMap; TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap ); if ( vMap.Extent() != 8 ) return false; myBox.Clear(); for ( int i = 1; i <= 8; ++i ) myBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))).XYZ() ); gp_XYZ pMin = myBox.CornerMin(), pMax = myBox.CornerMax(); for ( int i = 1; i <= 8; ++i ) { gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))); for ( int iC = 1; iC <= 3; ++ iC ) { double d1 = Abs( pMin.Coord( iC ) - p.Coord( iC )); double d2 = Abs( pMax.Coord( iC ) - p.Coord( iC )); if ( Min( d1, d2 ) > myTol ) return false; } } myBox.Enlarge( myTol ); return true; } /* Class : BelongToGeom Description : Predicate for verifying whether entity belongs to specified geometrical support */ BelongToGeom::BelongToGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void BelongToGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void BelongToGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } static bool IsSubShape (const TopTools_IndexedMapOfShape& theMap, const TopoDS_Shape& theShape) { if (theMap.Contains(theShape)) return true; if (theShape.ShapeType() == TopAbs_COMPOUND || theShape.ShapeType() == TopAbs_COMPSOLID) { TopoDS_Iterator anIt (theShape, Standard_True, Standard_True); for (; anIt.More(); anIt.Next()) { if (!IsSubShape(theMap, anIt.Value())) { return false; } } return true; } return false; } void BelongToGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { TopTools_IndexedMapOfShape aMap; TopExp::MapShapes(aMainShape, aMap); myIsSubshape = IsSubShape(aMap, myShape); } //if (!myIsSubshape) // to be always ready to check an element not bound to geometry { myElementsOnShapePtr.reset(new ElementsOnShape()); myElementsOnShapePtr->SetTolerance(myTolerance); myElementsOnShapePtr->SetAllNodes(true); // "belong", while false means "lays on" myElementsOnShapePtr->SetMesh(myMeshDS); myElementsOnShapePtr->SetShape(myShape, myType); } } static bool IsContains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum = TopAbs_SHAPE ) { TopExp_Explorer anExp( theShape,theFindShapeEnum,theAvoidShapeEnum ); while( anExp.More() ) { const TopoDS_Shape& aShape = anExp.Current(); if( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape ) ){ if( aSubMesh->Contains( theElem ) ) return true; } anExp.Next(); } return false; } bool BelongToGeom::IsSatisfy (long theId) { if (myMeshDS == 0 || myShape.IsNull()) return false; if (!myIsSubshape) { return myElementsOnShapePtr->IsSatisfy(theId); } // Case of submesh if (myType == SMDSAbs_Node) { if( const SMDS_MeshNode* aNode = myMeshDS->FindNode( theId ) ) { if ( aNode->getshapeId() < 1 ) return myElementsOnShapePtr->IsSatisfy(theId); const SMDS_PositionPtr& aPosition = aNode->GetPosition(); SMDS_TypeOfPosition aTypeOfPosition = aPosition->GetTypeOfPosition(); switch( aTypeOfPosition ) { case SMDS_TOP_VERTEX : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_VERTEX )); case SMDS_TOP_EDGE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_EDGE )); case SMDS_TOP_FACE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_FACE )); case SMDS_TOP_3DSPACE: return ( IsContains( myMeshDS,myShape,aNode,TopAbs_SOLID ) || IsContains( myMeshDS,myShape,aNode,TopAbs_SHELL )); } } } else { if ( const SMDS_MeshElement* anElem = myMeshDS->FindElement( theId )) { if ( anElem->getshapeId() < 1 ) return myElementsOnShapePtr->IsSatisfy(theId); if( myType == SMDSAbs_All ) { return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_FACE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } else if( myType == anElem->GetType() ) { switch( myType ) { case SMDSAbs_Edge : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE )); case SMDSAbs_Face : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_FACE )); case SMDSAbs_Volume: return ( IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } } } } return false; } void BelongToGeom::SetType (SMDSAbs_ElementType theType) { myType = theType; init(); } SMDSAbs_ElementType BelongToGeom::GetType() const { return myType; } TopoDS_Shape BelongToGeom::GetShape() { return myShape; } const SMESHDS_Mesh* BelongToGeom::GetMeshDS() const { return myMeshDS; } void BelongToGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double BelongToGeom::GetTolerance() { return myTolerance; } /* Class : LyingOnGeom Description : Predicate for verifying whether entiy lying or partially lying on specified geometrical support */ LyingOnGeom::LyingOnGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void LyingOnGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void LyingOnGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } void LyingOnGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { myIsSubshape = myMeshDS->IsGroupOfSubShapes( myShape ); } if (myIsSubshape) { TopTools_IndexedMapOfShape shapes; TopExp::MapShapes( myShape, shapes ); mySubShapesIDs.Clear(); for ( int i = 1; i <= shapes.Extent(); ++i ) { int subID = myMeshDS->ShapeToIndex( shapes( i )); if ( subID > 0 ) mySubShapesIDs.Add( subID ); } } else { myElementsOnShapePtr.reset(new ElementsOnShape()); myElementsOnShapePtr->SetTolerance(myTolerance); myElementsOnShapePtr->SetAllNodes(false); // lays on, while true means "belong" myElementsOnShapePtr->SetMesh(myMeshDS); myElementsOnShapePtr->SetShape(myShape, myType); } } bool LyingOnGeom::IsSatisfy( long theId ) { if ( myMeshDS == 0 || myShape.IsNull() ) return false; if (!myIsSubshape) { return myElementsOnShapePtr->IsSatisfy(theId); } // Case of sub-mesh const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ) ? myMeshDS->FindNode( theId ) : myMeshDS->FindElement( theId ); if ( mySubShapesIDs.Contains( elem->getshapeId() )) return true; if ( elem->GetType() != SMDSAbs_Node ) { SMDS_ElemIteratorPtr nodeItr = elem->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshElement* aNode = nodeItr->next(); if ( mySubShapesIDs.Contains( aNode->getshapeId() )) return true; } } return false; } void LyingOnGeom::SetType( SMDSAbs_ElementType theType ) { myType = theType; init(); } SMDSAbs_ElementType LyingOnGeom::GetType() const { return myType; } TopoDS_Shape LyingOnGeom::GetShape() { return myShape; } const SMESHDS_Mesh* LyingOnGeom::GetMeshDS() const { return myMeshDS; } void LyingOnGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double LyingOnGeom::GetTolerance() { return myTolerance; } bool LyingOnGeom::Contains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum ) { // if (IsContains(theMeshDS, theShape, theElem, theFindShapeEnum, theAvoidShapeEnum)) // return true; // TopTools_MapOfShape aSubShapes; // TopExp_Explorer exp( theShape, theFindShapeEnum, theAvoidShapeEnum ); // for ( ; exp.More(); exp.Next() ) // { // const TopoDS_Shape& aShape = exp.Current(); // if ( !aSubShapes.Add( aShape )) continue; // if ( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape )) // { // if ( aSubMesh->Contains( theElem )) // return true; // SMDS_ElemIteratorPtr nodeItr = theElem->nodesIterator(); // while ( nodeItr->more() ) // { // const SMDS_MeshElement* aNode = nodeItr->next(); // if ( aSubMesh->Contains( aNode )) // return true; // } // } // } return false; } TSequenceOfXYZ::TSequenceOfXYZ(): myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n) : myArray(n), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n, const gp_XYZ& t) : myArray(n,t), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(const TSequenceOfXYZ& theSequenceOfXYZ) : myArray(theSequenceOfXYZ.myArray), myElem(theSequenceOfXYZ.myElem) {} template <class InputIterator> TSequenceOfXYZ::TSequenceOfXYZ(InputIterator theBegin, InputIterator theEnd): myArray(theBegin,theEnd), myElem(0) {} TSequenceOfXYZ::~TSequenceOfXYZ() {} TSequenceOfXYZ& TSequenceOfXYZ::operator=(const TSequenceOfXYZ& theSequenceOfXYZ) { myArray = theSequenceOfXYZ.myArray; myElem = theSequenceOfXYZ.myElem; return *this; } gp_XYZ& TSequenceOfXYZ::operator()(size_type n) { return myArray[n-1]; } const gp_XYZ& TSequenceOfXYZ::operator()(size_type n) const { return myArray[n-1]; } void TSequenceOfXYZ::clear() { myArray.clear(); } void TSequenceOfXYZ::reserve(size_type n) { myArray.reserve(n); } void TSequenceOfXYZ::push_back(const gp_XYZ& v) { myArray.push_back(v); } TSequenceOfXYZ::size_type TSequenceOfXYZ::size() const { return myArray.size(); } SMDSAbs_EntityType TSequenceOfXYZ::getElementEntity() const { return myElem ? myElem->GetEntityType() : SMDSEntity_Last; } TMeshModifTracer::TMeshModifTracer(): myMeshModifTime(0), myMesh(0) { } void TMeshModifTracer::SetMesh( const SMDS_Mesh* theMesh ) { if ( theMesh != myMesh ) myMeshModifTime = 0; myMesh = theMesh; } bool TMeshModifTracer::IsMeshModified() { bool modified = false; if ( myMesh ) { modified = ( myMeshModifTime != myMesh->GetMTime() ); myMeshModifTime = myMesh->GetMTime(); } return modified; }
timthelion/FreeCAD
src/3rdParty/salomesmesh/src/Controls/SMESH_Controls.cpp
C++
lgpl-2.1
138,589
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "ASTPath.h" #include <AST.h> #include <TranslationUnit.h> #ifdef DEBUG_AST_PATH # include <QDebug> # include <typeinfo> #endif // DEBUG_AST_PATH using namespace CPlusPlus; QList<AST *> ASTPath::operator()(int line, int column) { _nodes.clear(); _line = line; _column = column; if (_doc) { if (TranslationUnit *unit = _doc->translationUnit()) accept(unit->ast()); } return _nodes; } #ifdef DEBUG_AST_PATH void ASTPath::dump(const QList<AST *> nodes) { qDebug() << "ASTPath dump," << nodes.size() << "nodes:"; for (int i = 0; i < nodes.size(); ++i) qDebug() << qPrintable(QString(i + 1, QLatin1Char('-'))) << typeid(*nodes.at(i)).name(); } #endif // DEBUG_AST_PATH bool ASTPath::preVisit(AST *ast) { unsigned firstToken = ast->firstToken(); unsigned lastToken = ast->lastToken(); if (firstToken > 0) { if (lastToken <= firstToken) return false; unsigned startLine, startColumn; getTokenStartPosition(firstToken, &startLine, &startColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { unsigned endLine, endColumn; getTokenEndPosition(lastToken - 1, &endLine, &endColumn); if (_line < endLine || (_line == endLine && _column <= endColumn)) { _nodes.append(ast); return true; } } } return false; }
ostash/qt-creator-i18n-uk
src/libs/cplusplus/ASTPath.cpp
C++
lgpl-2.1
2,743
//Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduce ) { Array.prototype.reduce = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = 0, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k < len && ! k in t ) k++; if ( k >= len ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k++ ]; } for ( ; k < len ; k++ ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduceRight ) { Array.prototype.reduceRight = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = len - 1, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k >= 0 && ! k in t ) k--; if ( k < 0 ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k-- ]; } for ( ; k >= 0 ; k-- ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(<span style="line-height: normal;">thisArg</span><span style="line-height: normal;">, val, i, t))</span> res.push(val); } } return res; }; } //Version-IE: < 9 if (!Array.prototype.every) { Array.prototype.every = function (callbackfn, thisArg) { "use strict"; var T, k; if (this == null) { throw new TypeError("this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the this // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== "function") { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let testResult be the result of calling the Call internal method // of callbackfn with T as the this value and argument list // containing kValue, k, and O. var testResult = callbackfn.call(T, kValue, k, O); // iii. If ToBoolean(testResult) is false, return false. if (!testResult) { return false; } } k++; } return true; }; } //Version-IE: < 9 if (!Array.prototype.some) { Array.prototype.some = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) return true; } return false; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.com/#x15.4.4.19 //Version-IE: < 9 if (!Array.prototype.map) { Array.prototype.map = function (callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array( len) where Array is // the standard built-in constructor with that name and len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal method of callback // with T as the this value and argument list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true}, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty( A, k, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.com/#x15.4.4.18 //Version-IE: < 9 if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and // argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; }
OCamlPro-Henry/js_of_ocaml
runtime/polyfill/array.js
JavaScript
lgpl-2.1
9,421
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Devices/Sim/SimDigital.h> namespace gadget { /** Default Constructor */ SimDigital::SimDigital() { vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::SimDigital()\n"<< vprDEBUG_FLUSH; } /** Destructor */ SimDigital::~SimDigital() { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::~SimDigital()\n"<< vprDEBUG_FLUSH; } std::string SimDigital::getElementType() { return "simulated_digital_device"; } bool SimDigital::config(jccl::ConfigElementPtr element) { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::config()\n"<< vprDEBUG_FLUSH; if (! (Input::config(element) && Digital::config(element) && SimInput::config(element)) ) { return false; } std::vector<jccl::ConfigElementPtr> key_list; int key_count = element->getNum("key_pair"); for ( int i = 0; i < key_count; ++i ) { key_list.push_back(element->getProperty<jccl::ConfigElementPtr>("key_pair", i)); } mSimKeys = readKeyList(key_list); return true; } /** * Updates the state of the digital data vector. * * @note Digital is on when key is held down. * When key is release, digital goes to off state. */ void SimDigital::updateData() { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::updateData()\n"<< vprDEBUG_FLUSH; std::vector<DigitalData> digital_data_sample(mSimKeys.size()); // The digital data that makes up the sample // -- Update digital data --- // for (unsigned int i = 0; i < mSimKeys.size(); ++i) { // Set the time for the digital data to the KeyboardMouse timestamp digital_data_sample[i].setTime(mKeyboardMouse->getTimeStamp()); // ON if keys pressed, OFF otherwise. digital_data_sample[i] = checkKeyPair(mSimKeys[i]) ? DigitalState::ON : DigitalState::OFF; } // Add a sample addDigitalSample(digital_data_sample); swapDigitalBuffers(); } } // End of gadget namespace
vrjuggler/vrjuggler
modules/gadgeteer/gadget/Devices/Sim/SimDigital.cpp
C++
lgpl-2.1
3,184
/* * Copyright 2014-present Open Networking Foundation * * 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 org.onosproject.store.serializers; import org.onosproject.net.ConnectPoint; import org.onosproject.net.LinkKey; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** * Kryo Serializer for {@link LinkKey}. */ public class LinkKeySerializer extends Serializer<LinkKey> { /** * Creates {@link LinkKey} serializer instance. */ public LinkKeySerializer() { // non-null, immutable super(false, true); } @Override public void write(Kryo kryo, Output output, LinkKey object) { kryo.writeClassAndObject(output, object.src()); kryo.writeClassAndObject(output, object.dst()); } @Override public LinkKey read(Kryo kryo, Input input, Class<LinkKey> type) { ConnectPoint src = (ConnectPoint) kryo.readClassAndObject(input); ConnectPoint dst = (ConnectPoint) kryo.readClassAndObject(input); return LinkKey.linkKey(src, dst); } }
opennetworkinglab/onos
core/store/serializers/src/main/java/org/onosproject/store/serializers/LinkKeySerializer.java
Java
apache-2.0
1,671
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * If x is -Infinity and y>0 and y is an odd integer, Math.pow(x,y) is -Infinity * * @path ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js * @description Checking if Math.pow(x,y) equals to -Infinity, where x is -Infinity and y>0 */ // CHECK#1 x = -Infinity; y = new Array(); y[0] = 1; y[1] = 111; y[2] = 111111; ynum = 3; for (i = 0; i < ynum; i++) { if (Math.pow(x,y[i]) !== -Infinity) { $ERROR("#1: Math.pow(" + x + ", " + y[i] + ") !== -Infinity"); } }
popravich/typescript
tests/Fidelity/test262/suite/ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js
JavaScript
apache-2.0
604
var fs = require('fs') var path = require('path') var resolve = path.resolve var osenv = require('osenv') var mkdirp = require('mkdirp') var rimraf = require('rimraf') var test = require('tap').test var npm = require('../../lib/npm') var common = require('../common-tap') var chain = require('slide').chain var mockPath = resolve(__dirname, 'install-shrinkwrapped') var parentPath = resolve(mockPath, 'parent') var parentNodeModulesPath = path.join(parentPath, 'node_modules') var outdatedNodeModulesPath = resolve(mockPath, 'node-modules-backup') var childPath = resolve(mockPath, 'child.git') var gitDaemon var gitDaemonPID var git var parentPackageJSON = JSON.stringify({ name: 'parent', version: '0.1.0' }) var childPackageJSON = JSON.stringify({ name: 'child', version: '0.1.0' }) test('setup', function (t) { cleanup() setup(function (err, result) { t.ifError(err, 'git started up successfully') if (!err) { gitDaemon = result[result.length - 2] gitDaemonPID = result[result.length - 1] } t.end() }) }) test('shrinkwrapped git dependency got updated', function (t) { t.comment('test for https://github.com/npm/npm/issues/12718') // Prepare the child package git repo with two commits prepareChildAndGetRefs(function (refs) { chain([ // Install & shrinkwrap child package's first commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[0]]], // Backup node_modules with the first commit [fs.rename, parentNodeModulesPath, outdatedNodeModulesPath], // Install & shrinkwrap child package's second commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[1]]], // Restore node_modules with the first commit [rimraf, parentNodeModulesPath], [fs.rename, outdatedNodeModulesPath, parentNodeModulesPath], // Update node_modules [npm.commands.install, []] ], function () { var childPackageJSON = require(path.join(parentNodeModulesPath, 'child', 'package.json')) t.equal( childPackageJSON._resolved, 'git://localhost:1234/child.git#' + refs[1], "Child package wasn't updated" ) t.end() }) }) }) test('clean', function (t) { gitDaemon.on('close', function () { cleanup() t.end() }) process.kill(gitDaemonPID) }) function setup (cb) { // Setup parent package mkdirp.sync(parentPath) fs.writeFileSync(resolve(parentPath, 'package.json'), parentPackageJSON) process.chdir(parentPath) // Setup child mkdirp.sync(childPath) fs.writeFileSync(resolve(childPath, 'package.json'), childPackageJSON) // Setup npm and then git npm.load({ registry: common.registry, loglevel: 'silent', save: true // Always install packages with --save }, function () { // It's important to initialize git after npm because it uses config initializeGit(cb) }) } function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(mockPath) rimraf.sync(common['npm_config_cache']) } function prepareChildAndGetRefs (cb) { var opts = { cwd: childPath, env: { PATH: process.env.PATH } } chain([ [fs.writeFile, path.join(childPath, 'README.md'), ''], git.chainableExec(['add', 'README.md'], opts), git.chainableExec(['commit', '-m', 'Add README'], opts), git.chainableExec(['log', '--pretty=format:"%H"', '-2'], opts) ], function () { var gitLogStdout = arguments[arguments.length - 1] var refs = gitLogStdout[gitLogStdout.length - 1].split('\n').map(function (ref) { return ref.match(/^"(.+)"$/)[1] }).reverse() // Reverse refs order: last, first -> first, last cb(refs) }) } function initializeGit (cb) { git = require('../../lib/utils/git') common.makeGitRepo({ path: childPath, commands: [startGitDaemon] }, cb) } function startGitDaemon (cb) { var daemon = git.spawn( [ 'daemon', '--verbose', '--listen=localhost', '--export-all', '--base-path=' + mockPath, // Path to the dir that contains child.git '--reuseaddr', '--port=1234' ], { cwd: parentPath, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] } ) daemon.stderr.on('data', function findChild (c) { var cpid = c.toString().match(/^\[(\d+)\]/) if (cpid[1]) { this.removeListener('data', findChild) cb(null, [daemon, cpid[1]]) } }) }
mrtequino/JSW
nodejs/pos-server/node_modules/npm/test/tap/install-shrinkwrapped-git.js
JavaScript
apache-2.0
4,407
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Messaging; using System.Transactions; using Common.Logging; using Spring.Transaction; namespace Spring.Messaging.Listener { /// <summary> /// A MessageListenerContainer that uses distributed (DTC) based transactions. Exceptions are /// handled by instances of <see cref="IDistributedTransactionExceptionHandler"/>. /// </summary> /// <remarks> /// <para> /// Starts a DTC based transaction before receiving the message. The transaction is /// automaticaly promoted to 2PC to avoid the default behaivor of transactional promotion. /// Database and messaging operations will commit or rollback together. /// </para> /// <para> /// If you only want local message based transactions use the /// <see cref="TransactionalMessageListenerContainer"/>. With some simple programming /// you may also achieve 'exactly once' processing using the /// <see cref="TransactionalMessageListenerContainer"/>. /// </para> /// <para> /// Poison messages can be detected and sent to another queue using Spring's /// <see cref="SendToQueueDistributedTransactionExceptionHandler"/>. /// </para> /// </remarks> public class DistributedTxMessageListenerContainer : AbstractTransactionalMessageListenerContainer { #region Logging Definition private static readonly ILog LOG = LogManager.GetLogger(typeof (DistributedTxMessageListenerContainer)); #endregion private IDistributedTransactionExceptionHandler distributedTransactionExceptionHandler; /// <summary> /// Gets or sets the distributed transaction exception handler. /// </summary> /// <value>The distributed transaction exception handler.</value> public IDistributedTransactionExceptionHandler DistributedTransactionExceptionHandler { get { return distributedTransactionExceptionHandler; } set { distributedTransactionExceptionHandler = value; } } /// <summary> /// Set the transaction name to be the spring object name. /// Call base class Initialize() functionality. /// </summary> public override void Initialize() { // Use object name as default transaction name. if (TransactionDefinition.Name == null) { TransactionDefinition.Name = ObjectName; } // Proceed with superclass initialization. base.Initialize(); } /// <summary> /// Does the receive and execute using TxPlatformTransactionManager. Starts a distributed /// transaction before calling Receive. /// </summary> /// <param name="mq">The message queue.</param> /// <param name="status">The transactional status.</param> /// <returns> /// true if should continue peeking, false otherwise. /// </returns> protected override bool DoReceiveAndExecuteUsingPlatformTransactionManager(MessageQueue mq, ITransactionStatus status) { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Executing DoReceiveAndExecuteUsingTxScopeTransactionManager"); } #endregion Logging //We are sure to be talking to a second resource manager, so avoid going through //the promotable transaction and force a distributed transaction right from the start. TransactionInterop.GetTransmitterPropagationToken(System.Transactions.Transaction.Current); Message message; try { message = mq.Receive(TimeSpan.Zero, MessageQueueTransactionType.Automatic); } catch (MessageQueueException ex) { if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout) { //expected to occur occasionally #region Logging if (LOG.IsTraceEnabled) { LOG.Trace( "MessageQueueErrorCode.IOTimeout: No message available to receive. May have been processed by another thread."); } #endregion status.SetRollbackOnly(); return false; // no more peeking unless this is the last listener thread } else { // A real issue in receiving the message lock (messageQueueMonitor) { mq.Close(); MessageQueue.ClearConnectionCache(); } throw; // will cause rollback in surrounding platform transaction manager and log exception } } if (message == null) { #region Logging if (LOG.IsTraceEnabled) { LOG.Trace("Message recieved is null from Queue = [" + mq.Path + "]"); } #endregion status.SetRollbackOnly(); return false; // no more peeking unless this is the last listener thread } try { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Received message [" + message.Id + "] on queue [" + mq.Path + "]"); } #endregion MessageReceived(message); if (DistributedTransactionExceptionHandler != null) { if (DistributedTransactionExceptionHandler.IsPoisonMessage(message)) { DistributedTransactionExceptionHandler.HandlePoisonMessage(message); return true; // will remove from queue and continue receive loop. } } DoExecuteListener(message); } catch (Exception ex) { HandleDistributedTransactionListenerException(ex, message); throw; // will rollback and keep message on the queue. } finally { message.Dispose(); } return true; } /// <summary> /// Handles the distributed transaction listener exception by calling the /// <see cref="IDistributedTransactionExceptionHandler"/> if not null. /// </summary> /// <param name="exception">The exception.</param> /// <param name="message">The message.</param> protected virtual void HandleDistributedTransactionListenerException(Exception exception, Message message) { IDistributedTransactionExceptionHandler exceptionHandler = DistributedTransactionExceptionHandler; if (exceptionHandler != null) { exceptionHandler.OnException(exception, message); } } } }
yonglehou/spring-net
src/Spring/Spring.Messaging/Messaging/Listener/DistributedTxMessageListenerContainer.cs
C#
apache-2.0
8,103
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using FluentAssertions.Collections; using FluentAssertions.Common; using FluentAssertions.Equivalency; using FluentAssertions.Numeric; using FluentAssertions.Primitives; using FluentAssertions.Types; namespace FluentAssertions { /// <summary> /// Contains extension methods for custom assertions in unit tests. /// </summary> [DebuggerNonUserCode] internal static class InternalAssertionExtensions { /// <summary> /// Invokes the specified action on an subject so that you can chain it with any of the ShouldThrow or ShouldNotThrow /// overloads. /// </summary> public static Action Invoking<T>(this T subject, Action<T> action) { return () => action(subject); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> public static Action Enumerating(this Func<IEnumerable> enumerable) { return () => ForceEnumeration(enumerable); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> public static Action Enumerating<T>(this Func<IEnumerable<T>> enumerable) { return () => ForceEnumeration(() => (IEnumerable)enumerable()); } private static void ForceEnumeration(Func<IEnumerable> enumerable) { foreach (object item in enumerable()) { // Do nothing } } /// <summary> /// Returns an <see cref="ObjectAssertions"/> object that can be used to assert the /// current <see cref="object"/>. /// </summary> public static ObjectAssertions Should(this object actualValue) { return new ObjectAssertions(actualValue); } /// <summary> /// Returns an <see cref="BooleanAssertions"/> object that can be used to assert the /// current <see cref="bool"/>. /// </summary> public static BooleanAssertions Should(this bool actualValue) { return new BooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableBooleanAssertions"/> object that can be used to assert the /// current nullable <see cref="bool"/>. /// </summary> public static NullableBooleanAssertions Should(this bool? actualValue) { return new NullableBooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="GuidAssertions"/> object that can be used to assert the /// current <see cref="Guid"/>. /// </summary> public static GuidAssertions Should(this Guid actualValue) { return new GuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableGuidAssertions"/> object that can be used to assert the /// current nullable <see cref="Guid"/>. /// </summary> public static NullableGuidAssertions Should(this Guid? actualValue) { return new NullableGuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="NonGenericCollectionAssertions"/> object that can be used to assert the /// current <see cref="IEnumerable"/>. /// </summary> public static NonGenericCollectionAssertions Should(this IEnumerable actualValue) { return new NonGenericCollectionAssertions(actualValue); } /// <summary> /// Returns an <see cref="GenericCollectionAssertions{T}"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> public static GenericCollectionAssertions<T> Should<T>(this IEnumerable<T> actualValue) { return new GenericCollectionAssertions<T>(actualValue); } /// <summary> /// Returns an <see cref="StringCollectionAssertions"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> public static StringCollectionAssertions Should(this IEnumerable<string> @this) { return new StringCollectionAssertions(@this); } /// <summary> /// Returns an <see cref="GenericDictionaryAssertions{TKey, TValue}"/> object that can be used to assert the /// current <see cref="IDictionary{TKey, TValue}"/>. /// </summary> public static GenericDictionaryAssertions<TKey, TValue> Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { return new GenericDictionaryAssertions<TKey, TValue>(actualValue); } /// <summary> /// Returns an <see cref="DateTimeOffsetAssertions"/> object that can be used to assert the /// current <see cref="DateTime"/>. /// </summary> public static DateTimeOffsetAssertions Should(this DateTime actualValue) { return new DateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableDateTimeOffsetAssertions"/> object that can be used to assert the /// current nullable <see cref="DateTime"/>. /// </summary> public static NullableDateTimeOffsetAssertions Should(this DateTime? actualValue) { return new NullableDateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="ComparableTypeAssertions{T}"/> object that can be used to assert the /// current <see cref="IComparable{T}"/>. /// </summary> public static ComparableTypeAssertions<T> Should<T>(this IComparable<T> comparableValue) { return new ComparableTypeAssertions<T>(comparableValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="int"/>. /// </summary> public static NumericAssertions<int> Should(this int actualValue) { return new NumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="int"/>. /// </summary> public static NullableNumericAssertions<int> Should(this int? actualValue) { return new NullableNumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="decimal"/>. /// </summary> public static NumericAssertions<decimal> Should(this decimal actualValue) { return new NumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="decimal"/>. /// </summary> public static NullableNumericAssertions<decimal> Should(this decimal? actualValue) { return new NullableNumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="byte"/>. /// </summary> public static NumericAssertions<byte> Should(this byte actualValue) { return new NumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="byte"/>. /// </summary> public static NullableNumericAssertions<byte> Should(this byte? actualValue) { return new NullableNumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="short"/>. /// </summary> public static NumericAssertions<short> Should(this short actualValue) { return new NumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="short"/>. /// </summary> public static NullableNumericAssertions<short> Should(this short? actualValue) { return new NullableNumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="long"/>. /// </summary> public static NumericAssertions<long> Should(this long actualValue) { return new NumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="long"/>. /// </summary> public static NullableNumericAssertions<long> Should(this long? actualValue) { return new NullableNumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="float"/>. /// </summary> public static NumericAssertions<float> Should(this float actualValue) { return new NumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="float"/>. /// </summary> public static NullableNumericAssertions<float> Should(this float? actualValue) { return new NullableNumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="double"/>. /// </summary> public static NumericAssertions<double> Should(this double actualValue) { return new NumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="double"/>. /// </summary> public static NullableNumericAssertions<double> Should(this double? actualValue) { return new NullableNumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="StringAssertions"/> object that can be used to assert the /// current <see cref="string"/>. /// </summary> public static StringAssertions Should(this string actualValue) { return new StringAssertions(actualValue); } /// <summary> /// Returns an <see cref="SimpleTimeSpanAssertions"/> object that can be used to assert the /// current <see cref="TimeSpan"/>. /// </summary> public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue) { return new SimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableSimpleTimeSpanAssertions"/> object that can be used to assert the /// current nullable <see cref="TimeSpan"/>. /// </summary> public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue) { return new NullableSimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="System.Type"/>. /// </summary> public static TypeAssertions Should(this Type subject) { return new TypeAssertions(subject); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="System.Type"/>. /// </summary> public static TypeSelectorAssertions Should(this TypeSelector typeSelector) { return new TypeSelectorAssertions(typeSelector.ToArray()); } /// <summary> /// Returns a <see cref="MethodInfoAssertions"/> object that can be used to assert the current <see cref="MethodInfo"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static MethodInfoAssertions Should(this MethodInfo methodInfo) { return new MethodInfoAssertions(methodInfo); } /// <summary> /// Returns a <see cref="MethodInfoSelectorAssertions"/> object that can be used to assert the methods returned by the /// current <see cref="MethodInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static MethodInfoSelectorAssertions Should(this MethodInfoSelector methodSelector) { return new MethodInfoSelectorAssertions(methodSelector.ToArray()); } /// <summary> /// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static PropertyInfoAssertions Should(this PropertyInfo propertyInfo) { return new PropertyInfoAssertions(propertyInfo); } /// <summary> /// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the properties returned by the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector propertyInfoSelector) { return new PropertyInfoSelectorAssertions(propertyInfoSelector.ToArray()); } /// <summary> /// Asserts that an object is equivalent to another object. /// </summary> /// <remarks> /// Objects are equivalent when both object graphs have equally named properties with the same value, /// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. /// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all /// items in the collection are structurally equal. /// Notice that actual behavior is determined by the <see cref="EquivalencyAssertionOptions.Default"/> instance of the /// <see cref="EquivalencyAssertionOptions"/> class. /// </remarks> /// <param name="because"> /// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the /// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public static void ShouldBeEquivalentTo<T>(this T subject, object expectation, string because = "", params object[] becauseArgs) { ShouldBeEquivalentTo(subject, expectation, config => config, because, becauseArgs); } /// <summary> /// Asserts that an object is equivalent to another object. /// </summary> /// <remarks> /// Objects are equivalent when both object graphs have equally named properties with the same value, /// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. /// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all /// items in the collection are structurally equal. /// </remarks> /// <param name="config"> /// A reference to the <see cref="EquivalencyAssertionOptions.Default"/> configuration object that can be used /// to influence the way the object graphs are compared. You can also provide an alternative instance of the /// <see cref="EquivalencyAssertionOptions"/> class. /// </param> /// <param name="because"> /// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the /// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public static void ShouldBeEquivalentTo<T>(this T subject, object expectation, Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "", params object[] becauseArgs) { IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>()); var context = new EquivalencyValidationContext { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new EquivalencyValidator(options).AssertEquality(context); } public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation, string because = "", params object[] becauseArgs) { ShouldAllBeEquivalentTo(subject, expectation, config => config, because, becauseArgs); } public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation, Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "", params object[] becauseArgs) { IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>()); var context = new EquivalencyValidationContext { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new EquivalencyValidator(options).AssertEquality(context); } /// <summary> /// Safely casts the specified object to the type specified through <typeparamref name="TTo"/>. /// </summary> /// <remarks> /// Has been introduced to allow casting objects without breaking the fluent API. /// </remarks> /// <typeparam name="TTo"></typeparam> public static TTo As<TTo>(this object subject) { return subject is TTo ? (TTo)subject : default(TTo); } } }
SaroTasciyan/FluentAssertions
Src/Core/InternalAssertionExtensions.cs
C#
apache-2.0
19,975
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.shell.commands; import java.util.Map.Entry; import org.apache.accumulo.core.data.constraints.Constraint; import org.apache.accumulo.shell.Shell; import org.apache.accumulo.shell.Shell.Command; import org.apache.accumulo.shell.ShellCommandException; import org.apache.accumulo.shell.ShellCommandException.ErrorCode; import org.apache.accumulo.shell.ShellOptions; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; public class ConstraintCommand extends Command { protected Option namespaceOpt; @Override public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { final String tableName; final String namespace; if (cl.hasOption(namespaceOpt.getOpt())) { namespace = cl.getOptionValue(namespaceOpt.getOpt()); } else { namespace = null; } if (cl.hasOption(OptUtil.tableOpt().getOpt()) || !shellState.getTableName().isEmpty()) { tableName = OptUtil.getTableOpt(cl, shellState); } else { tableName = null; } int i; switch (OptUtil.getAldOpt(cl)) { case ADD: for (String constraint : cl.getArgs()) { if (namespace != null) { if (!shellState.getAccumuloClient().namespaceOperations().testClassLoad(namespace, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().namespaceOperations().addConstraint(namespace, constraint); shellState.getWriter().println("Added constraint " + constraint + " to namespace " + namespace + " with number " + i); } else if (tableName != null && !tableName.isEmpty()) { if (!shellState.getAccumuloClient().tableOperations().testClassLoad(tableName, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().tableOperations().addConstraint(tableName, constraint); shellState.getWriter().println( "Added constraint " + constraint + " to table " + tableName + " with number " + i); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case DELETE: for (String constraint : cl.getArgs()) { i = Integer.parseInt(constraint); if (namespace != null) { shellState.getAccumuloClient().namespaceOperations().removeConstraint(namespace, i); shellState.getWriter() .println("Removed constraint " + i + " from namespace " + namespace); } else if (tableName != null) { shellState.getAccumuloClient().tableOperations().removeConstraint(tableName, i); shellState.getWriter().println("Removed constraint " + i + " from table " + tableName); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case LIST: if (namespace != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().namespaceOperations() .listConstraints(namespace).entrySet()) { shellState.getWriter().println(property.toString()); } } else if (tableName != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().tableOperations() .listConstraints(tableName).entrySet()) { shellState.getWriter().println(property.toString()); } } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } return 0; } @Override public String description() { return "adds, deletes, or lists constraints for a table"; } @Override public int numArgs() { return Shell.NO_FIXED_ARG_LENGTH_CHECK; } @Override public String usage() { return getName() + " <constraint>{ <constraint>}"; } @Override public Options getOptions() { final Options o = new Options(); o.addOptionGroup(OptUtil.addListDeleteGroup("constraint")); OptionGroup grp = new OptionGroup(); grp.addOption(OptUtil.tableOpt("table to add, delete, or list constraints for")); namespaceOpt = new Option(ShellOptions.namespaceOption, "namespace", true, "name of a namespace to operate on"); namespaceOpt.setArgName("namespace"); grp.addOption(namespaceOpt); o.addOptionGroup(grp); return o; } }
milleruntime/accumulo
shell/src/main/java/org/apache/accumulo/shell/commands/ConstraintCommand.java
Java
apache-2.0
5,893
/* * Copyright 2000-2010 JetBrains s.r.o. * * 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.intellij.ui; import com.intellij.util.PairFunction; import com.intellij.util.containers.Convertor; import javax.swing.*; import javax.swing.table.TableModel; import java.util.ListIterator; public class TableSpeedSearch extends SpeedSearchBase<JTable> { private static final PairFunction<Object, Cell, String> TO_STRING = new PairFunction<Object, Cell, String>() { public String fun(Object o, Cell cell) { return o == null ? "" : o.toString(); } }; private final PairFunction<Object, Cell, String> myToStringConvertor; public TableSpeedSearch(JTable table) { this(table, TO_STRING); } public TableSpeedSearch(JTable table, final Convertor<Object, String> toStringConvertor) { this(table, new PairFunction<Object, Cell, String>() { @Override public String fun(Object o, Cell c) { return toStringConvertor.convert(o); } }); } public TableSpeedSearch(JTable table, final PairFunction<Object, Cell, String> toStringConvertor) { super(table); myToStringConvertor = toStringConvertor; } protected boolean isSpeedSearchEnabled() { return !getComponent().isEditing() && super.isSpeedSearchEnabled(); } @Override protected ListIterator<Object> getElementIterator(int startingIndex) { return new MyListIterator(startingIndex); } protected int getElementCount() { final TableModel tableModel = myComponent.getModel(); return tableModel.getRowCount() * tableModel.getColumnCount(); } protected void selectElement(Object element, String selectedText) { final int index = ((Integer)element).intValue(); final TableModel model = myComponent.getModel(); final int row = index / model.getColumnCount(); final int col = index % model.getColumnCount(); myComponent.getSelectionModel().setSelectionInterval(row, row); myComponent.getColumnModel().getSelectionModel().setSelectionInterval(col, col); TableUtil.scrollSelectionToVisible(myComponent); } protected int getSelectedIndex() { final int row = myComponent.getSelectedRow(); final int col = myComponent.getSelectedColumn(); // selected row is not enough as we want to select specific cell in a large multi-column table return row > -1 && col > -1 ? row * myComponent.getModel().getColumnCount() + col : -1; } protected Object[] getAllElements() { throw new UnsupportedOperationException("Not implemented"); } protected String getElementText(Object element) { final int index = ((Integer)element).intValue(); final TableModel model = myComponent.getModel(); int row = myComponent.convertRowIndexToModel(index / model.getColumnCount()); int col = myComponent.convertColumnIndexToModel(index % model.getColumnCount()); Object value = model.getValueAt(row, col); return myToStringConvertor.fun(value, new Cell(row, col)); } private class MyListIterator implements ListIterator<Object> { private int myCursor; public MyListIterator(int startingIndex) { final int total = getElementCount(); myCursor = startingIndex < 0 ? total : startingIndex; } public boolean hasNext() { return myCursor < getElementCount(); } public Object next() { return myCursor++; } public boolean hasPrevious() { return myCursor > 0; } public Object previous() { return (myCursor--) - 1; } public int nextIndex() { return myCursor; } public int previousIndex() { return myCursor - 1; } public void remove() { throw new AssertionError("Not Implemented"); } public void set(Object o) { throw new AssertionError("Not Implemented"); } public void add(Object o) { throw new AssertionError("Not Implemented"); } } }
liveqmock/platform-tools-idea
platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java
Java
apache-2.0
4,403
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.web; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; /** * A resolver for {@link Link links} to web endpoints. * * @author Andy Wilkinson * @since 2.0.0 */ public class EndpointLinksResolver { private static final Log logger = LogFactory.getLog(EndpointLinksResolver.class); private final Collection<? extends ExposableEndpoint<?>> endpoints; /** * Creates a new {@code EndpointLinksResolver} that will resolve links to the given * {@code endpoints}. * @param endpoints the endpoints */ public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints) { this.endpoints = endpoints; } /** * Creates a new {@code EndpointLinksResolver} that will resolve links to the given * {@code endpoints} that are exposed beneath the given {@code basePath}. * @param endpoints the endpoints * @param basePath the basePath */ public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints, String basePath) { this.endpoints = endpoints; if (logger.isInfoEnabled()) { logger.info("Exposing " + endpoints.size() + " endpoint(s) beneath base path '" + basePath + "'"); } } /** * Resolves links to the known endpoints based on a request with the given * {@code requestUrl}. * @param requestUrl the url of the request for the endpoint links * @return the links */ public Map<String, Link> resolveLinks(String requestUrl) { String normalizedUrl = normalizeRequestUrl(requestUrl); Map<String, Link> links = new LinkedHashMap<>(); links.put("self", new Link(normalizedUrl)); for (ExposableEndpoint<?> endpoint : this.endpoints) { if (endpoint instanceof ExposableWebEndpoint) { collectLinks(links, (ExposableWebEndpoint) endpoint, normalizedUrl); } else if (endpoint instanceof PathMappedEndpoint) { links.put(endpoint.getId(), createLink(normalizedUrl, ((PathMappedEndpoint) endpoint).getRootPath())); } } return links; } private String normalizeRequestUrl(String requestUrl) { if (requestUrl.endsWith("/")) { return requestUrl.substring(0, requestUrl.length() - 1); } return requestUrl; } private void collectLinks(Map<String, Link> links, ExposableWebEndpoint endpoint, String normalizedUrl) { for (WebOperation operation : endpoint.getOperations()) { links.put(operation.getId(), createLink(normalizedUrl, operation)); } } private Link createLink(String requestUrl, WebOperation operation) { return createLink(requestUrl, operation.getRequestPredicate().getPath()); } private Link createLink(String requestUrl, String path) { return new Link(requestUrl + (path.startsWith("/") ? path : "/" + path)); } }
bclozel/spring-boot
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java
Java
apache-2.0
3,528
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager.containermanager; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.security.NMTokenIdentifier; import org.apache.hadoop.yarn.server.api.ResourceTracker; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.LocalRMInterface; import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationState; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics; import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.junit.After; import org.junit.Before; public abstract class BaseContainerManagerTest { protected static RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); protected static FileContext localFS; protected static File localDir; protected static File localLogDir; protected static File remoteLogDir; protected static File tmpDir; protected final NodeManagerMetrics metrics = NodeManagerMetrics.create(); public BaseContainerManagerTest() throws UnsupportedFileSystemException { localFS = FileContext.getLocalFSFileContext(); localDir = new File("target", this.getClass().getSimpleName() + "-localDir") .getAbsoluteFile(); localLogDir = new File("target", this.getClass().getSimpleName() + "-localLogDir") .getAbsoluteFile(); remoteLogDir = new File("target", this.getClass().getSimpleName() + "-remoteLogDir") .getAbsoluteFile(); tmpDir = new File("target", this.getClass().getSimpleName() + "-tmpDir"); } protected static Log LOG = LogFactory .getLog(BaseContainerManagerTest.class); protected static final int HTTP_PORT = 5412; protected Configuration conf = new YarnConfiguration(); protected Context context = new NMContext(new NMContainerTokenSecretManager( conf), new NMTokenSecretManagerInNM()) { public int getHttpPort() { return HTTP_PORT; }; }; protected ContainerExecutor exec; protected DeletionService delSrvc; protected String user = "nobody"; protected NodeHealthCheckerService nodeHealthChecker; protected LocalDirsHandlerService dirsHandler; protected final long DUMMY_RM_IDENTIFIER = 1234; protected NodeStatusUpdater nodeStatusUpdater = new NodeStatusUpdaterImpl( context, new AsyncDispatcher(), null, metrics) { @Override protected ResourceTracker getRMClient() { return new LocalRMInterface(); }; @Override protected void stopRMProxy() { return; } @Override protected void startStatusUpdater() { return; // Don't start any updating thread. } @Override public long getRMIdentifier() { // There is no real RM registration, simulate and set RMIdentifier return DUMMY_RM_IDENTIFIER; } }; protected ContainerManagerImpl containerManager = null; protected ContainerExecutor createContainerExecutor() { DefaultContainerExecutor exec = new DefaultContainerExecutor(); exec.setConf(conf); return exec; } @Before public void setup() throws IOException { localFS.delete(new Path(localDir.getAbsolutePath()), true); localFS.delete(new Path(tmpDir.getAbsolutePath()), true); localFS.delete(new Path(localLogDir.getAbsolutePath()), true); localFS.delete(new Path(remoteLogDir.getAbsolutePath()), true); localDir.mkdir(); tmpDir.mkdir(); localLogDir.mkdir(); remoteLogDir.mkdir(); LOG.info("Created localDir in " + localDir.getAbsolutePath()); LOG.info("Created tmpDir in " + tmpDir.getAbsolutePath()); String bindAddress = "0.0.0.0:12345"; conf.set(YarnConfiguration.NM_ADDRESS, bindAddress); conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogDir.getAbsolutePath()); conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1); // Default delSrvc delSrvc = createDeletionService(); delSrvc.init(conf); exec = createContainerExecutor(); nodeHealthChecker = new NodeHealthCheckerService(); nodeHealthChecker.init(conf); dirsHandler = nodeHealthChecker.getDiskHandler(); containerManager = createContainerManager(delSrvc); ((NMContext)context).setContainerManager(containerManager); nodeStatusUpdater.init(conf); containerManager.init(conf); nodeStatusUpdater.start(); } protected ContainerManagerImpl createContainerManager(DeletionService delSrvc) { return new ContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater, metrics, new ApplicationACLsManager(conf), dirsHandler) { @Override public void setBlockNewContainerRequests(boolean blockNewContainerRequests) { // do nothing } @Override protected void authorizeGetAndStopContainerRequest(ContainerId containerId, Container container, boolean stopRequest, NMTokenIdentifier identifier) throws YarnException { // do nothing } @Override protected void authorizeUser(UserGroupInformation remoteUgi, NMTokenIdentifier nmTokenIdentifier) { // do nothing } @Override protected void authorizeStartRequest( NMTokenIdentifier nmTokenIdentifier, ContainerTokenIdentifier containerTokenIdentifier) throws YarnException { // do nothing } @Override protected void updateNMTokenIdentifier( NMTokenIdentifier nmTokenIdentifier) throws InvalidToken { // Do nothing } @Override public Map<String, ByteBuffer> getAuxServiceMetaData() { Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>(); serviceData.put("AuxService1", ByteBuffer.wrap("AuxServiceMetaData1".getBytes())); serviceData.put("AuxService2", ByteBuffer.wrap("AuxServiceMetaData2".getBytes())); return serviceData; } }; } protected DeletionService createDeletionService() { return new DeletionService(exec) { @Override public void delete(String user, Path subDir, Path[] baseDirs) { // Don't do any deletions. LOG.info("Psuedo delete: user - " + user + ", subDir - " + subDir + ", baseDirs - " + baseDirs); }; }; } @After public void tearDown() throws IOException, InterruptedException { if (containerManager != null) { containerManager.stop(); } createContainerExecutor().deleteAsUser(user, new Path(localDir.getAbsolutePath()), new Path[] {}); } public static void waitForContainerState(ContainerManagementProtocol containerManager, ContainerId containerID, ContainerState finalState) throws InterruptedException, YarnException, IOException { waitForContainerState(containerManager, containerID, finalState, 20); } public static void waitForContainerState(ContainerManagementProtocol containerManager, ContainerId containerID, ContainerState finalState, int timeOutMax) throws InterruptedException, YarnException, IOException { List<ContainerId> list = new ArrayList<ContainerId>(); list.add(containerID); GetContainerStatusesRequest request = GetContainerStatusesRequest.newInstance(list); ContainerStatus containerStatus = containerManager.getContainerStatuses(request).getContainerStatuses() .get(0); int timeoutSecs = 0; while (!containerStatus.getState().equals(finalState) && timeoutSecs++ < timeOutMax) { Thread.sleep(1000); LOG.info("Waiting for container to get into state " + finalState + ". Current state is " + containerStatus.getState()); containerStatus = containerManager.getContainerStatuses(request).getContainerStatuses().get(0); } LOG.info("Container state is " + containerStatus.getState()); Assert.assertEquals("ContainerState is not correct (timedout)", finalState, containerStatus.getState()); } static void waitForApplicationState(ContainerManagerImpl containerManager, ApplicationId appID, ApplicationState finalState) throws InterruptedException { // Wait for app-finish Application app = containerManager.getContext().getApplications().get(appID); int timeout = 0; while (!(app.getApplicationState().equals(finalState)) && timeout++ < 15) { LOG.info("Waiting for app to reach " + finalState + ".. Current state is " + app.getApplicationState()); Thread.sleep(1000); } Assert.assertTrue("App is not in " + finalState + " yet!! Timedout!!", app.getApplicationState().equals(finalState)); } }
tomatoKiller/Hadoop_Source_Learn
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
Java
apache-2.0
11,919
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.proxy; import io.airlift.configuration.Config; import io.airlift.configuration.ConfigDescription; import io.airlift.configuration.validation.FileExists; import javax.validation.constraints.NotNull; import java.io.File; import java.net.URI; public class ProxyConfig { private URI uri; private File sharedSecretFile; @NotNull public URI getUri() { return uri; } @Config("proxy.uri") @ConfigDescription("URI of the remote Trino server") public ProxyConfig setUri(URI uri) { this.uri = uri; return this; } @NotNull @FileExists public File getSharedSecretFile() { return sharedSecretFile; } @Config("proxy.shared-secret-file") @ConfigDescription("Shared secret file used for authenticating URIs") public ProxyConfig setSharedSecretFile(File sharedSecretFile) { this.sharedSecretFile = sharedSecretFile; return this; } }
electrum/presto
service/trino-proxy/src/main/java/io/trino/proxy/ProxyConfig.java
Java
apache-2.0
1,534
# # 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. from keystoneclient import exceptions from heat.common import exception from heat.common import heat_keystoneclient as hkc from heat.engine.clients import client_plugin from heat.engine import constraints class KeystoneClientPlugin(client_plugin.ClientPlugin): exceptions_module = exceptions service_types = [IDENTITY] = ['identity'] def _create(self): return hkc.KeystoneClient(self.context) def is_not_found(self, ex): return isinstance(ex, exceptions.NotFound) def is_over_limit(self, ex): return isinstance(ex, exceptions.RequestEntityTooLarge) def is_conflict(self, ex): return isinstance(ex, exceptions.Conflict) def get_role_id(self, role): try: role_obj = self.client().client.roles.get(role) return role_obj.id except exceptions.NotFound: role_list = self.client().client.roles.list(name=role) for role_obj in role_list: if role_obj.name == role: return role_obj.id raise exception.EntityNotFound(entity='KeystoneRole', name=role) def get_project_id(self, project): try: project_obj = self.client().client.projects.get(project) return project_obj.id except exceptions.NotFound: project_list = self.client().client.projects.list(name=project) for project_obj in project_list: if project_obj.name == project: return project_obj.id raise exception.EntityNotFound(entity='KeystoneProject', name=project) def get_domain_id(self, domain): try: domain_obj = self.client().client.domains.get(domain) return domain_obj.id except exceptions.NotFound: domain_list = self.client().client.domains.list(name=domain) for domain_obj in domain_list: if domain_obj.name == domain: return domain_obj.id raise exception.EntityNotFound(entity='KeystoneDomain', name=domain) def get_group_id(self, group): try: group_obj = self.client().client.groups.get(group) return group_obj.id except exceptions.NotFound: group_list = self.client().client.groups.list(name=group) for group_obj in group_list: if group_obj.name == group: return group_obj.id raise exception.EntityNotFound(entity='KeystoneGroup', name=group) def get_service_id(self, service): try: service_obj = self.client().client.services.get(service) return service_obj.id except exceptions.NotFound: service_list = self.client().client.services.list(name=service) if len(service_list) == 1: return service_list[0].id elif len(service_list) > 1: raise exception.KeystoneServiceNameConflict(service=service) else: raise exception.EntityNotFound(entity='KeystoneService', name=service) def get_user_id(self, user): try: user_obj = self.client().client.users.get(user) return user_obj.id except exceptions.NotFound: user_list = self.client().client.users.list(name=user) for user_obj in user_list: if user_obj.name == user: return user_obj.id raise exception.EntityNotFound(entity='KeystoneUser', name=user) class KeystoneRoleConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound,) def validate_with_client(self, client, role): client.client_plugin('keystone').get_role_id(role) class KeystoneDomainConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound,) def validate_with_client(self, client, domain): client.client_plugin('keystone').get_domain_id(domain) class KeystoneProjectConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound,) def validate_with_client(self, client, project): client.client_plugin('keystone').get_project_id(project) class KeystoneGroupConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound,) def validate_with_client(self, client, group): client.client_plugin('keystone').get_group_id(group) class KeystoneServiceConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound, exception.KeystoneServiceNameConflict,) def validate_with_client(self, client, service): client.client_plugin('keystone').get_service_id(service) class KeystoneUserConstraint(constraints.BaseCustomConstraint): expected_exceptions = (exception.EntityNotFound,) def validate_with_client(self, client, user): client.client_plugin('keystone').get_user_id(user)
cryptickp/heat
heat/engine/clients/os/keystone.py
Python
apache-2.0
5,676
// test cube var assert = require('assert'), math = require('../../../index'), error = require('../../../lib/error/index'), unit = math.unit, bignumber = math.bignumber, matrix = math.matrix, range = math.range, cube = math.cube; describe('cube', function() { it('should return the cube of a boolean', function () { assert.equal(cube(true), 1); assert.equal(cube(false), 0); }); it('should return the cube of null', function () { assert.equal(math.ceil(null), 0); }); it('should return the cube of a number', function() { assert.equal(cube(4), 64); assert.equal(cube(-2), -8); assert.equal(cube(0), 0); }); it('should return the cube of a big number', function() { assert.deepEqual(cube(bignumber(4)), bignumber(64)); assert.deepEqual(cube(bignumber(-2)), bignumber(-8)); assert.deepEqual(cube(bignumber(0)), bignumber(0)); }); it('should return the cube of a complex number', function() { assert.deepEqual(cube(math.complex('2i')), math.complex('-8i')); assert.deepEqual(cube(math.complex('2+3i')), math.complex('-46+9i')); assert.deepEqual(cube(math.complex('2')), math.complex('8')); }); it('should throw an error with strings', function() { assert.throws(function () {cube('text')}); }); it('should throw an error with units', function() { assert.throws(function () {cube(unit('5cm'))}); }); it('should throw an error if there\'s wrong number of args', function() { assert.throws(function () {cube()}, error.ArgumentsError); assert.throws(function () {cube(1, 2)}, error.ArgumentsError); }); it('should cube each element in a matrix, array or range', function() { // array, matrix, range // arrays are evaluated element wise assert.deepEqual(cube([2,3,4,5]), [8,27,64,125]); assert.deepEqual(cube(matrix([2,3,4,5])), matrix([8,27,64,125])); assert.deepEqual(cube(matrix([[1,2],[3,4]])), matrix([[1,8],[27,64]])); }); });
owenversteeg/mathjs
test/function/arithmetic/cube.test.js
JavaScript
apache-2.0
1,982
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "hl2mp_cvars.h" // Ready restart ConVar mp_readyrestart( "mp_readyrestart", "0", FCVAR_GAMEDLL, "If non-zero, game will restart once each player gives the ready signal" ); // Ready signal ConVar mp_ready_signal( "mp_ready_signal", "ready", FCVAR_GAMEDLL, "Text that each player must speak for the match to begin" );
TheCallSign/Clifton-Source
src/game/server/hl2mp/hl2mp_cvars.cpp
C++
apache-2.0
616
package servicebroker import ( "reflect" "testing" schema "github.com/lestrrat/go-jsschema" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/openshift/origin/pkg/openservicebroker/api" templateapi "github.com/openshift/origin/pkg/template/api" ) func TestServiceFromTemplate(t *testing.T) { template := &templateapi.Template{ ObjectMeta: metav1.ObjectMeta{ Name: "name", UID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Annotations: map[string]string{ "description": "description", "tags": "tag1,tag2", "openshift.io/display-name": "displayName", "iconClass": "iconClass", "template.openshift.io/long-description": "longDescription", "template.openshift.io/provider-display-name": "providerDisplayName", "template.openshift.io/documentation-url": "documentationURL", "template.openshift.io/support-url": "supportURL", }, }, Parameters: []templateapi.Parameter{ { Name: "param1", Required: true, }, { Name: "param2", }, }, } expectedService := &api.Service{ Name: "name", ID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Description: "description", Tags: []string{"tag1", "tag2"}, Bindable: true, Metadata: map[string]interface{}{ "providerDisplayName": "providerDisplayName", "documentationUrl": "documentationURL", "supportUrl": "supportURL", "displayName": "displayName", "console.openshift.io/iconClass": "iconClass", "longDescription": "longDescription", }, Plans: []api.Plan{ { ID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Name: "default", Description: "Default plan", Free: true, Bindable: true, Schemas: api.Schema{ ServiceInstances: api.ServiceInstances{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{ "template.openshift.io/namespace", "template.openshift.io/requester-username", "param1", }, Properties: map[string]*schema.Schema{ "template.openshift.io/namespace": { Title: "Template service broker: namespace", Description: "OpenShift namespace in which to provision service", Type: schema.PrimitiveTypes{schema.StringType}, }, "template.openshift.io/requester-username": { Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, }, "param1": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, "param2": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, }, }, }, }, ServiceBindings: api.ServiceBindings{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{"template.openshift.io/requester-username"}, Properties: map[string]*schema.Schema{ "template.openshift.io/requester-username": { Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, }, }, }, }, }, }, }, }, } service := serviceFromTemplate(template) if !reflect.DeepEqual(service, expectedService) { t.Error("service did not match expectedService") } }
thrasher-redhat/origin
pkg/template/servicebroker/catalog_test.go
GO
apache-2.0
3,950
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.mllp; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; /** * Represents the component that manages {@link MllpEndpoint}. */ public class MllpComponent extends UriEndpointComponent { public static final String MLLP_LOG_PHI_PROPERTY = "org.apache.camel.component.mllp.logPHI"; public MllpComponent() { super(MllpEndpoint.class); } public MllpComponent(CamelContext context) { super(context, MllpEndpoint.class); } protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { MllpEndpoint endpoint = new MllpEndpoint(uri, this); setProperties(endpoint, parameters); // mllp://hostname:port String hostPort; // look for options int optionsStartIndex = uri.indexOf('?'); if (-1 == optionsStartIndex) { // No options - just get the host/port stuff hostPort = uri.substring(7); } else { hostPort = uri.substring(7, optionsStartIndex); } // Make sure it has a host - may just be a port int colonIndex = hostPort.indexOf(':'); if (-1 != colonIndex) { endpoint.setHostname(hostPort.substring(0, colonIndex)); endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1))); } else { // No host specified - leave the default host and set the port endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1))); } return endpoint; } }
tkopczynski/camel
components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpComponent.java
Java
apache-2.0
2,487
from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False
tecdct2941/nxos_dashboard
repeated_timer.py
Python
apache-2.0
721
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class TakesScreenshotTest : DriverTestFixture { [TearDown] public void SwitchToTop() { driver.SwitchTo().DefaultContent(); } [Test] public void GetScreenshotAsFile() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png"); Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); screenImage.SaveAsFile(filename, ScreenshotImageFormat.Png); Assert.That(File.Exists(filename), Is.True); Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0)); File.Delete(filename); } [Test] public void GetScreenshotAsBase64() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); string base64 = screenImage.AsBase64EncodedString; Assert.That(base64.Length, Is.GreaterThan(0)); } [Test] public void GetScreenshotAsBinary() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); byte[] bytes = screenImage.AsByteArray; Assert.That(bytes.Length, Is.GreaterThan(0)); } [Test] public void ShouldCaptureScreenshotOfCurrentViewport() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldTakeScreenshotsOfAnElement() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); IWebElement element = driver.FindElement(By.Id("cell11")); ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot; if (screenshotCapableElement == null) { return; } Screenshot screenImage = screenshotCapableElement.GetScreenshot(); byte[] imageData = screenImage.AsByteArray; Assert.That(imageData, Is.Not.Null); Assert.That(imageData.Length, Is.GreaterThan(0)); Color pixelColor = GetPixelColor(screenImage, 1, 1); string pixelColorString = FormatColorToHex(pixelColor.ToArgb()); Assert.AreEqual("#0f12f7", pixelColorString); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongXandY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldCaptureScreenshotAtFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(TitleToBe("screen test"), "Title was not expected value"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")] public void ShouldCaptureScreenshotAtIFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.IE, "Color comparisons fail on IE")] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtIFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page CompareColors(expectedColors, actualColors); } private string FormatColorToHex(int colorValue) { string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF)); return pixelColorString; } private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors) { // Ignore black and white for further comparison actualColors.Remove("#000000"); actualColors.Remove("#ffffff"); Assert.That(actualColors, Is.EquivalentTo(expectedColors)); } private HashSet<string> GenerateExpectedColors(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY) { HashSet<string> colors = new HashSet<string>(); int count = 1; for (int i = 1; i < numberOfSamplesX; i++) { for (int j = 1; j < numberOfSamplesY; j++) { int color = initialColor + (count * stepColor); string hex = FormatColorToHex(color); colors.Add(hex); count++; } } return colors; } private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY) { HashSet<string> colors = new HashSet<string>(); #if !NETCOREAPP2_0 && !NETSTANDARD2_0 try { Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); int height = bitmap.Height; int width = bitmap.Width; Assert.That(width, Is.GreaterThan(0)); Assert.That(height, Is.GreaterThan(0)); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb()); colors.Add(hex); } } } catch (Exception e) { Assert.Fail("Unable to get actual colors from screenshot: " + e.Message); } Assert.That(colors.Count, Is.GreaterThan(0)); #endif return colors; } private Color GetPixelColor(Screenshot screenshot, int x, int y) { Color pixelColor = Color.Black; #if !NETCOREAPP2_0 && !NETSTANDARD2_0 Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); pixelColor = bitmap.GetPixel(1, 1); #endif return pixelColor; } private Func<bool> FrameToBeAvailableAndSwitchedTo(string frameId) { return () => { try { IWebElement frameElement = driver.FindElement(By.Id(frameId)); driver.SwitchTo().Frame(frameElement); } catch(Exception) { return false; } return true; }; } private Func<bool> ElementToBeVisibleWithId(string elementId) { return () => { try { IWebElement element = driver.FindElement(By.Id(elementId)); return element.Displayed; } catch(Exception) { return false; } }; } private Func<bool> TitleToBe(string desiredTitle) { return () => driver.Title == desiredTitle; } } }
asashour/selenium
dotnet/test/common/TakesScreenshotTest.cs
C#
apache-2.0
22,313
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The following is taken from Closure Library: // // buildFromEncodedParts // splitRe // ComponentIndex // split // removeDotSegments /** * Builds a URI string from already-encoded parts. * * No encoding is performed. Any component may be omitted as either null or * undefined. * * @param {?string=} opt_scheme The scheme such as 'http'. * @param {?string=} opt_userInfo The user name before the '@'. * @param {?string=} opt_domain The domain such as 'www.google.com', already * URI-encoded. * @param {(string|number|null)=} opt_port The port number. * @param {?string=} opt_path The path, already URI-encoded. If it is not * empty, it must begin with a slash. * @param {?string=} opt_queryData The URI-encoded query data. * @param {?string=} opt_fragment The URI-encoded fragment identifier. * @return {string} The fully combined URI. */ function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); }; /** * A regular expression for breaking a URI into its component parts. * * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says * As the "first-match-wins" algorithm is identical to the "greedy" * disambiguation method used by POSIX regular expressions, it is natural and * commonplace to use a regular expression for parsing the potential five * components of a URI reference. * * The following line is the regular expression for breaking-down a * well-formed URI reference into its components. * * <pre> * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? * 12 3 4 5 6 7 8 9 * </pre> * * The numbers in the second line above are only to assist readability; they * indicate the reference points for each subexpression (i.e., each paired * parenthesis). We refer to the value matched for subexpression <n> as $<n>. * For example, matching the above expression to * <pre> * http://www.ics.uci.edu/pub/ietf/uri/#Related * </pre> * results in the following subexpression matches: * <pre> * $1 = http: * $2 = http * $3 = //www.ics.uci.edu * $4 = www.ics.uci.edu * $5 = /pub/ietf/uri/ * $6 = <undefined> * $7 = <undefined> * $8 = #Related * $9 = Related * </pre> * where <undefined> indicates that the component is not present, as is the * case for the query component in the above example. Therefore, we can * determine the value of the five components as * <pre> * scheme = $2 * authority = $4 * path = $5 * query = $7 * fragment = $9 * </pre> * * The regular expression has been modified slightly to expose the * userInfo, domain, and port separately from the authority. * The modified version yields * <pre> * $1 = http scheme * $2 = <undefined> userInfo -\ * $3 = www.ics.uci.edu domain | authority * $4 = <undefined> port -/ * $5 = /pub/ietf/uri/ path * $6 = <undefined> query without ? * $7 = Related fragment without # * </pre> * @type {!RegExp} * @private */ var splitRe = new RegExp( '^' + '(?:' + '([^:/?#.]+)' + // scheme - ignore special characters // used by other URL parts such as :, // ?, /, #, and . ':)?' + '(?://' + '(?:([^/?#]*)@)?' + // userInfo '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters, // digits, dashes, dots, percent // escapes, and unicode characters. '(?::([0-9]+))?' + // port ')?' + '([^?#]+)?' + // path '(?:\\?([^#]*))?' + // query '(?:#(.*))?' + // fragment '$'); /** * The index of each URI component in the return value of goog.uri.utils.split. * @enum {number} */ var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; /** * Splits a URI into its component parts. * * Each component can be accessed via the component indices; for example: * <pre> * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA]; * </pre> * * @param {string} uri The URI string to examine. * @return {!Array.<string|undefined>} Each component still URI-encoded. * Each component that is present will contain the encoded value, whereas * components that are not present will be undefined or empty, depending * on the browser's regular expression implementation. Never null, since * arbitrary strings may still look like path names. */ function split(uri) { // See @return comment -- never null. return /** @type {!Array.<string|undefined>} */ ( uri.match(splitRe)); } /** * Removes dot segments in given path component, as described in * RFC 3986, section 5.2.4. * * @param {string} path A non-empty path component. * @return {string} Path component with removed dot segments. */ export function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } /** * Takes an array of the parts from split and canonicalizes the path part * and then joins all the parts. * @param {Array.<string?} parts * @return {string} */ function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH]; path = removeDotSegments(path.replace(/\/\//.g, '/')); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts( parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } /** * Canonicalizes a URL by eliminating ./ path entries, * canonicalizing ../ entries, and collapsing occurrences of //. * * @param {string} url * @return {string} */ export function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } /** * Resovles a URL. * @param {string} base The URL acting as the base URL. * @param {string} to The URL to resolve. * @return {string} */ export function resolveUrl(base, url) { if (url[0] === '@') return url; var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); }
passy/traceur-todomvc
src/util/url.js
JavaScript
apache-2.0
8,826
package network // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // LoadBalancerLoadBalancingRulesClient is the network Client type LoadBalancerLoadBalancingRulesClient struct { BaseClient } // NewLoadBalancerLoadBalancingRulesClient creates an instance of the LoadBalancerLoadBalancingRulesClient client. func NewLoadBalancerLoadBalancingRulesClient(subscriptionID string) LoadBalancerLoadBalancingRulesClient { return NewLoadBalancerLoadBalancingRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewLoadBalancerLoadBalancingRulesClientWithBaseURI creates an instance of the LoadBalancerLoadBalancingRulesClient // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func NewLoadBalancerLoadBalancingRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerLoadBalancingRulesClient { return LoadBalancerLoadBalancingRulesClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets the specified load balancer load balancing rule. // Parameters: // resourceGroupName - the name of the resource group. // loadBalancerName - the name of the load balancer. // loadBalancingRuleName - the name of the load balancing rule. func (client LoadBalancerLoadBalancingRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (result LoadBalancingRule, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, loadBalancingRuleName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client LoadBalancerLoadBalancingRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "loadBalancingRuleName": autorest.Encode("path", loadBalancingRuleName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancerLoadBalancingRulesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client LoadBalancerLoadBalancingRulesClient) GetResponder(resp *http.Response) (result LoadBalancingRule, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all the load balancing rules in a load balancer. // Parameters: // resourceGroupName - the name of the resource group. // loadBalancerName - the name of the load balancer. func (client LoadBalancerLoadBalancingRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") defer func() { sc := -1 if result.lblbrlr.Response.Response != nil { sc = result.lblbrlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lblbrlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure sending request") return } result.lblbrlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure responding to request") return } if result.lblbrlr.hasNextLink() && result.lblbrlr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client LoadBalancerLoadBalancingRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancerLoadBalancingRulesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client LoadBalancerLoadBalancingRulesClient) ListResponder(resp *http.Response) (result LoadBalancerLoadBalancingRuleListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client LoadBalancerLoadBalancingRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerLoadBalancingRuleListResult) (result LoadBalancerLoadBalancingRuleListResult, err error) { req, err := lastResults.loadBalancerLoadBalancingRuleListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client LoadBalancerLoadBalancingRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) return }
djs55/linuxkit
src/cmd/linuxkit/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-10-01/network/loadbalancerloadbalancingrules.go
GO
apache-2.0
10,169
# -*- coding: utf-8 -*- """ Covenant Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import urlparse from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import dom_parser from resources.lib.modules import source_utils class source: def __init__(self): self.priority = 1 self.language = ['de'] self.genre_filter = ['horror'] self.domains = ['horrorkino.do.am'] self.base_link = 'http://horrorkino.do.am/' self.search_link = 'video/shv' def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search([localtitle] + source_utils.aliases_to_array(aliases), year) if not url and title != localtitle: url = self.__search([title] + source_utils.aliases_to_array(aliases), year) return url except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources r = client.request(urlparse.urljoin(self.base_link, url)) r = re.findall('''vicode\s*=\s*["'](.*?)["'];''', r)[0].decode('string_escape') r = dom_parser.parse_dom(r, 'iframe', req='src') r = [i.attrs['src'] for i in r] for i in r: valid, host = source_utils.is_host_valid(i, hostDict) if not valid: continue sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': i, 'direct': False, 'debridonly': False, 'checkquality': True}) return sources except: return sources def resolve(self, url): return url def __search(self, titles, year): try: t = [cleantitle.get(i) for i in set(titles) if i] y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0'] r = client.request(urlparse.urljoin(self.base_link, self.search_link), post={'query': cleantitle.query(titles[0])}) r = dom_parser.parse_dom(r, 'li', attrs={'class': 'entTd'}) r = dom_parser.parse_dom(r, 'div', attrs={'class': 've-screen'}, req='title') r = [(dom_parser.parse_dom(i, 'a', req='href'), i.attrs['title'].split(' - ')[0]) for i in r] r = [(i[0][0].attrs['href'], i[1], re.findall('(.+?) \(*(\d{4})', i[1])) for i in r] r = [(i[0], i[2][0][0] if len(i[2]) > 0 else i[1], i[2][0][1] if len(i[2]) > 0 else '0') for i in r] r = sorted(r, key=lambda i: int(i[2]), reverse=True) # with year > no year r = [i[0] for i in r if cleantitle.get(i[1]) in t and i[2] in y][0] return source_utils.strip_domain(r) except: return
TheWardoctor/Wardoctors-repo
script.module.uncoded/lib/resources/lib/sources/de/horrorkino.py
Python
apache-2.0
3,418
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.assertions; import com.google.common.collect.ImmutableList; import io.trino.Session; import io.trino.metadata.Metadata; import io.trino.sql.parser.ParsingOptions; import io.trino.sql.parser.SqlParser; import io.trino.sql.planner.Symbol; import io.trino.sql.planner.plan.ApplyNode; import io.trino.sql.planner.plan.PlanNode; import io.trino.sql.planner.plan.ProjectNode; import io.trino.sql.tree.Expression; import io.trino.sql.tree.InPredicate; import io.trino.sql.tree.SymbolReference; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkState; import static io.trino.sql.ExpressionUtils.rewriteIdentifiersToSymbolReferences; import static java.util.Objects.requireNonNull; public class ExpressionMatcher implements RvalueMatcher { private final String sql; private final Expression expression; public ExpressionMatcher(String expression) { this.sql = requireNonNull(expression, "expression is null"); this.expression = expression(expression); } public ExpressionMatcher(Expression expression) { this.expression = requireNonNull(expression, "expression is null"); this.sql = expression.toString(); } private Expression expression(String sql) { SqlParser parser = new SqlParser(); return rewriteIdentifiersToSymbolReferences(parser.createExpression(sql, new ParsingOptions())); } public static ExpressionMatcher inPredicate(SymbolReference value, SymbolReference valueList) { return new ExpressionMatcher(new InPredicate(value, valueList)); } @Override public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) { Optional<Symbol> result = Optional.empty(); ImmutableList.Builder<Expression> matchesBuilder = ImmutableList.builder(); Map<Symbol, Expression> assignments = getAssignments(node); if (assignments == null) { return result; } ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); for (Map.Entry<Symbol, Expression> assignment : assignments.entrySet()) { if (verifier.process(assignment.getValue(), expression)) { result = Optional.of(assignment.getKey()); matchesBuilder.add(assignment.getValue()); } } List<Expression> matches = matchesBuilder.build(); checkState(matches.size() < 2, "Ambiguous expression %s matches multiple assignments", expression, (matches.stream().map(Expression::toString).collect(Collectors.joining(", ")))); return result; } private static Map<Symbol, Expression> getAssignments(PlanNode node) { if (node instanceof ProjectNode) { ProjectNode projectNode = (ProjectNode) node; return projectNode.getAssignments().getMap(); } else if (node instanceof ApplyNode) { ApplyNode applyNode = (ApplyNode) node; return applyNode.getSubqueryAssignments().getMap(); } else { return null; } } @Override public String toString() { return sql; } }
electrum/presto
core/trino-main/src/test/java/io/trino/sql/planner/assertions/ExpressionMatcher.java
Java
apache-2.0
3,920
require 'spec_helper' describe 'collectd::plugin::swap', :type => :class do context ':ensure => present, default params' do let :facts do {:osfamily => 'RedHat'} end it 'Will create /etc/collectd.d/10-swap.conf' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => /\#\ Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n<\/Plugin>\n/, }) end end context ':ensure => present, specific params, collectd version 5.0' do let :facts do { :osfamily => 'Redhat', :collectd_version => '5.0' } end it 'Will create /etc/collectd.d/10-swap.conf for collectd < 5.2' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => "# Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n</Plugin>\n", }) end end context ':ensure => present, specific params, collectd version 5.2.0' do let :facts do { :osfamily => 'Redhat', :collectd_version => '5.2.0' } end it 'Will create /etc/collectd.d/10-swap.conf for collectd >= 5.2' do should contain_file('swap.load').with({ :ensure => 'present', :path => '/etc/collectd.d/10-swap.conf', :content => "# Generated by Puppet\nLoadPlugin swap\n\n<Plugin swap>\n ReportByDevice false\n ReportBytes true\n</Plugin>\n", }) end end context ':ensure => absent' do let :facts do {:osfamily => 'RedHat'} end let :params do {:ensure => 'absent'} end it 'Will not create /etc/collectd.d/10-swap.conf' do should contain_file('swap.load').with({ :ensure => 'absent', :path => '/etc/collectd.d/10-swap.conf', }) end end end
apache/infrastructure-puppet
modules/collectd/spec/classes/collectd_plugin_swap_spec.rb
Ruby
apache-2.0
1,936
/* * Copyright 2017-present Open Networking Foundation * * 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 org.onosproject.store.service; import java.util.Objects; import com.google.common.base.MoreObjects; import com.google.common.collect.ComparisonChain; import org.onosproject.store.Timestamp; import static com.google.common.base.Preconditions.checkArgument; /** * Logical timestamp for versions. * <p> * The version is a logical timestamp that represents a point in logical time at which an event occurs. * This is used in both pessimistic and optimistic locking protocols to ensure that the state of a shared resource * has not changed at the end of a transaction. */ public class Version implements Timestamp { private final long version; public Version(long version) { this.version = version; } @Override public int compareTo(Timestamp o) { checkArgument(o instanceof Version, "Must be LockVersion", o); Version that = (Version) o; return ComparisonChain.start() .compare(this.version, that.version) .result(); } @Override public int hashCode() { return Long.hashCode(version); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Version)) { return false; } Version that = (Version) obj; return Objects.equals(this.version, that.version); } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("version", version) .toString(); } /** * Returns the lock version. * * @return the lock version */ public long value() { return this.version; } }
gkatsikas/onos
core/api/src/main/java/org/onosproject/store/service/Version.java
Java
apache-2.0
2,369
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.nativeplatform.internal; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.language.nativeplatform.DependentSourceSet; import org.gradle.nativeplatform.*; import org.gradle.nativeplatform.internal.resolve.NativeBinaryRequirementResolveResult; import org.gradle.nativeplatform.internal.resolve.NativeDependencyResolver; import org.gradle.nativeplatform.platform.NativePlatform; import org.gradle.nativeplatform.toolchain.NativeToolChain; import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider; import org.gradle.nativeplatform.toolchain.internal.PreCompiledHeader; import org.gradle.platform.base.internal.BinarySpecInternal; import java.io.File; import java.util.Collection; import java.util.Map; public interface NativeBinarySpecInternal extends NativeBinarySpec, BinarySpecInternal { void setFlavor(Flavor flavor); void setToolChain(NativeToolChain toolChain); void setTargetPlatform(NativePlatform targetPlatform); void setBuildType(BuildType buildType); Tool getToolByName(String name); PlatformToolProvider getPlatformToolProvider(); void setPlatformToolProvider(PlatformToolProvider toolProvider); void setResolver(NativeDependencyResolver resolver); void setFileCollectionFactory(FileCollectionFactory fileCollectionFactory); File getPrimaryOutput(); Collection<NativeDependencySet> getLibs(DependentSourceSet sourceSet); Collection<NativeLibraryBinary> getDependentBinaries(); /** * Adds some files to include as input to the link/assemble step of this binary. */ void binaryInputs(FileCollection files); Collection<NativeBinaryRequirementResolveResult> getAllResolutions(); Map<File, PreCompiledHeader> getPrefixFileToPCH(); void addPreCompiledHeaderFor(DependentSourceSet sourceSet); }
gstevey/gradle
subprojects/platform-native/src/main/java/org/gradle/nativeplatform/internal/NativeBinarySpecInternal.java
Java
apache-2.0
2,517
/* * Copyright 2012 Amadeus s.a.s. * 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. */ Aria.classDefinition({ $classpath : "test.aria.storage.localStorage.NamespaceTestCase", $dependencies : ["aria.storage.LocalStorage"], $extends : "test.aria.storage.base.GeneralNamespaceBase", $constructor : function () { this.storageLocation = "localStorage"; this.$GeneralNamespaceBase.constructor.call(this); }, $prototype : { /** * Check what happens when you use namespaces, one namespaced shouldn't affect the others */ testNamespaceAPI : function () { if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) { this.$GeneralNamespaceBase.testNamespaceAPI.call(this); } }, /** * Verify if the events are raised correctly */ testNamespaceEvents : function () { if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) { this.$GeneralNamespaceBase.testNamespaceEvents.call(this); } } } });
vcarle/ariatemplates
test/aria/storage/localStorage/NamespaceTestCase.js
JavaScript
apache-2.0
1,613
<?php /* +*********************************************************************************** * The contents of this file are subject to the vtiger CRM Public License Version 1.0 * ("License"); You may not use this file except in compliance with the License * The Original Code is: vtiger CRM Open Source * The Initial Developer of the Original Code is vtiger. * Portions created by vtiger are Copyright (C) vtiger. * All Rights Reserved. * *********************************************************************************** */ class Project_RelationListView_Model extends Vtiger_RelationListView_Model { public function getCreateViewUrl() { $createViewUrl = parent::getCreateViewUrl(); $relationModuleModel = $this->getRelationModel()->getRelationModuleModel(); if($relationModuleModel->getName() == 'HelpDesk') { if($relationModuleModel->getField('parent_id')->isViewable()) { $createViewUrl .='&parent_id='.$this->getParentRecordModel()->get('linktoaccountscontacts'); } } return $createViewUrl; } }
basiljose1/byjcrm
pkg/vtiger/modules/Projects/Project/modules/Project/models/RelationListView.php
PHP
apache-2.0
1,041
using System.ComponentModel.DataAnnotations; using FluentMigrator.Infrastructure; namespace FluentMigrator.Expressions { /// <summary> /// Expression to delete a sequence /// </summary> public class DeleteSequenceExpression : MigrationExpressionBase, ISchemaExpression { /// <inheritdoc /> public virtual string SchemaName { get; set; } /// <summary> /// Gets or sets the sequence name /// </summary> [Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = nameof(ErrorMessages.SequenceNameCannotBeNullOrEmpty))] public virtual string SequenceName { get; set; } /// <inheritdoc /> public override void ExecuteWith(IMigrationProcessor processor) { processor.Process(this); } /// <inheritdoc /> public override string ToString() { return base.ToString() + SequenceName; } } }
schambers/fluentmigrator
src/FluentMigrator.Abstractions/Expressions/DeleteSequenceExpression.cs
C#
apache-2.0
978
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization.Formatters; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Commands.Resources.Models.Authorization; using Microsoft.Azure.Commands.Tags.Model; using Microsoft.Azure.Common.Authentication; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Newtonsoft.Json; using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources; namespace Microsoft.Azure.Commands.Resources.Models { public partial class ResourcesClient { /// <summary> /// A string that indicates the value of the resource type name for the RP's operations api /// </summary> public const string Operations = "operations"; /// <summary> /// A string that indicates the value of the registering state enum for a provider /// </summary> public const string RegisteredStateName = "Registered"; /// <summary> /// Used when provisioning the deployment status. /// </summary> private List<DeploymentOperation> operations; public IResourceManagementClient ResourceManagementClient { get; set; } public IAuthorizationManagementClient AuthorizationManagementClient { get; set; } public GalleryTemplatesClient GalleryTemplatesClient { get; set; } // TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094 //public IEventsClient EventsClient { get; set; } public Action<string> VerboseLogger { get; set; } public Action<string> ErrorLogger { get; set; } public Action<string> WarningLogger { get; set; } /// <summary> /// Creates new ResourceManagementClient /// </summary> /// <param name="profile">Profile containing resources to manipulate</param> public ResourcesClient(AzureProfile profile) : this( AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(profile, AzureEnvironment.Endpoint.ResourceManager), new GalleryTemplatesClient(profile.Context), // TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094 //AzureSession.ClientFactory.CreateClient<EventsClient>(context, AzureEnvironment.Endpoint.ResourceManager), AzureSession.ClientFactory.CreateClient<AuthorizationManagementClient>(profile.Context, AzureEnvironment.Endpoint.ResourceManager)) { } /// <summary> /// Creates new ResourcesClient instance /// </summary> /// <param name="resourceManagementClient">The IResourceManagementClient instance</param> /// <param name="galleryTemplatesClient">The IGalleryClient instance</param> /// <param name="authorizationManagementClient">The management client instance</param> public ResourcesClient( IResourceManagementClient resourceManagementClient, GalleryTemplatesClient galleryTemplatesClient, // TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094 //IEventsClient eventsClient, IAuthorizationManagementClient authorizationManagementClient) { GalleryTemplatesClient = galleryTemplatesClient; // TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094 //EventsClient = eventsClient; AuthorizationManagementClient = authorizationManagementClient; this.ResourceManagementClient = resourceManagementClient; } /// <summary> /// Parameterless constructor for mocking /// </summary> public ResourcesClient() { } private string GetDeploymentParameters(Hashtable templateParameterObject) { if (templateParameterObject != null) { return SerializeHashtable(templateParameterObject, addValueLayer: true); } else { return null; } } public string SerializeHashtable(Hashtable templateParameterObject, bool addValueLayer) { if (templateParameterObject == null) { return null; } Dictionary<string, object> parametersDictionary = templateParameterObject.ToDictionary(addValueLayer); return JsonConvert.SerializeObject(parametersDictionary, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, TypeNameHandling = TypeNameHandling.None, Formatting = Formatting.Indented }); } public virtual PSResourceProvider UnregisterProvider(string providerName) { var response = this.ResourceManagementClient.Providers.Unregister(providerName); if (response.Provider == null) { throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderUnregistrationFailed, providerName)); } return response.Provider.ToPSResourceProvider(); } private string GetTemplate(string templateFile, string galleryTemplateName) { string template; if (!string.IsNullOrEmpty(templateFile)) { if (Uri.IsWellFormedUriString(templateFile, UriKind.Absolute)) { template = GeneralUtilities.DownloadFile(templateFile); } else { template = FileUtilities.DataStore.ReadFileAsText(templateFile); } } else { Debug.Assert(!string.IsNullOrEmpty(galleryTemplateName)); string templateUri = GalleryTemplatesClient.GetGalleryTemplateFile(galleryTemplateName); template = GeneralUtilities.DownloadFile(templateUri); } return template; } private ResourceGroupExtended CreateOrUpdateResourceGroup(string name, string location, Hashtable[] tags) { Dictionary<string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(tags, validate: true); var result = ResourceManagementClient.ResourceGroups.CreateOrUpdate(name, new ResourceGroup { Location = location, Tags = tagDictionary }); return result.ResourceGroup; } private void WriteVerbose(string progress) { if (VerboseLogger != null) { VerboseLogger(progress); } } private void WriteWarning(string warning) { if (WarningLogger != null) { WarningLogger(warning); } } private void WriteError(string error) { if (ErrorLogger != null) { ErrorLogger(error); } } private DeploymentExtended ProvisionDeploymentStatus(string resourceGroup, string deploymentName, Deployment deployment) { operations = new List<DeploymentOperation>(); return WaitDeploymentStatus( resourceGroup, deploymentName, deployment, WriteDeploymentProgress, ProvisioningState.Canceled, ProvisioningState.Succeeded, ProvisioningState.Failed); } private void WriteDeploymentProgress(string resourceGroup, string deploymentName, Deployment deployment) { const string normalStatusFormat = "Resource {0} '{1}' provisioning status is {2}"; const string failureStatusFormat = "Resource {0} '{1}' failed with message '{2}'"; List<DeploymentOperation> newOperations; DeploymentOperationsListResult result; result = ResourceManagementClient.DeploymentOperations.List(resourceGroup, deploymentName, null); newOperations = GetNewOperations(operations, result.Operations); operations.AddRange(newOperations); while (!string.IsNullOrEmpty(result.NextLink)) { result = ResourceManagementClient.DeploymentOperations.ListNext(result.NextLink); newOperations = GetNewOperations(operations, result.Operations); operations.AddRange(newOperations); } foreach (DeploymentOperation operation in newOperations) { string statusMessage; if (operation.Properties.ProvisioningState != ProvisioningState.Failed) { statusMessage = string.Format(normalStatusFormat, operation.Properties.TargetResource.ResourceType, operation.Properties.TargetResource.ResourceName, operation.Properties.ProvisioningState.ToLower()); WriteVerbose(statusMessage); } else { string errorMessage = ParseErrorMessage(operation.Properties.StatusMessage); statusMessage = string.Format(failureStatusFormat, operation.Properties.TargetResource.ResourceType, operation.Properties.TargetResource.ResourceName, errorMessage); WriteError(statusMessage); } } } public static string ParseErrorMessage(string statusMessage) { CloudError error = CloudException.ParseXmlOrJsonError(statusMessage); if (error.Message == null) { return error.OriginalMessage; } else { return error.Message; } } private DeploymentExtended WaitDeploymentStatus( string resourceGroup, string deploymentName, Deployment basicDeployment, Action<string, string, Deployment> job, params string[] status) { DeploymentExtended deployment; do { if (job != null) { job(resourceGroup, deploymentName, basicDeployment); } deployment = ResourceManagementClient.Deployments.Get(resourceGroup, deploymentName).Deployment; Thread.Sleep(2000); } while (!status.Any(s => s.Equals(deployment.Properties.ProvisioningState, StringComparison.OrdinalIgnoreCase))); return deployment; } private List<DeploymentOperation> GetNewOperations(List<DeploymentOperation> old, IList<DeploymentOperation> current) { List<DeploymentOperation> newOperations = new List<DeploymentOperation>(); foreach (DeploymentOperation operation in current) { DeploymentOperation operationWithSameIdAndProvisioningState = old.Find(o => o.OperationId.Equals(operation.OperationId) && o.Properties.ProvisioningState.Equals(operation.Properties.ProvisioningState)); if (operationWithSameIdAndProvisioningState == null) { newOperations.Add(operation); } } return newOperations; } private Deployment CreateBasicDeployment(ValidatePSResourceGroupDeploymentParameters parameters) { Deployment deployment = new Deployment { Properties = new DeploymentProperties { Mode = DeploymentMode.Incremental, Template = GetTemplate(parameters.TemplateFile, parameters.GalleryTemplateIdentity), Parameters = GetDeploymentParameters(parameters.TemplateParameterObject) } }; return deployment; } private TemplateValidationInfo CheckBasicDeploymentErrors(string resourceGroup, string deploymentName, Deployment deployment) { DeploymentValidateResponse validationResult = ResourceManagementClient.Deployments.Validate( resourceGroup, deploymentName, deployment); return new TemplateValidationInfo(validationResult); } internal List<PSPermission> GetResourceGroupPermissions(string resourceGroup) { PermissionGetResult permissionsResult = AuthorizationManagementClient.Permissions.ListForResourceGroup(resourceGroup); if (permissionsResult != null) { return permissionsResult.Permissions.Select(p => p.ToPSPermission()).ToList(); } return null; } internal List<PSPermission> GetResourcePermissions(ResourceIdentifier identity) { PermissionGetResult permissionsResult = AuthorizationManagementClient.Permissions.ListForResource( identity.ResourceGroupName, identity.ToResourceIdentity()); if (permissionsResult != null) { return permissionsResult.Permissions.Select(p => p.ToPSPermission()).ToList(); } return null; } public virtual PSResourceProvider[] ListPSResourceProviders(string providerName = null) { return this.ListResourceProviders(providerName: providerName, listAvailable: false) .Select(provider => provider.ToPSResourceProvider()) .ToArray(); } public virtual PSResourceProvider[] ListPSResourceProviders(bool listAvailable) { return this.ListResourceProviders(providerName: null, listAvailable: listAvailable) .Select(provider => provider.ToPSResourceProvider()) .ToArray(); } public virtual List<Provider> ListResourceProviders(string providerName = null, bool listAvailable = true) { if (!string.IsNullOrEmpty(providerName)) { var provider = this.ResourceManagementClient.Providers.Get(providerName).Provider; if (provider == null) { throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderNotFound, providerName)); } return new List<Provider> {provider}; } else { var returnList = new List<Provider>(); var tempResult = this.ResourceManagementClient.Providers.List(null); returnList.AddRange(tempResult.Providers); while (!string.IsNullOrWhiteSpace(tempResult.NextLink)) { tempResult = this.ResourceManagementClient.Providers.ListNext(tempResult.NextLink); returnList.AddRange(tempResult.Providers); } return listAvailable ? returnList : returnList.Where(this.IsProviderRegistered).ToList(); } } private bool IsProviderRegistered(Provider provider) { return string.Equals( ResourcesClient.RegisteredStateName, provider.RegistrationState, StringComparison.InvariantCultureIgnoreCase); } public PSResourceProvider RegisterProvider(string providerName) { var response = this.ResourceManagementClient.Providers.Register(providerName); if (response.Provider == null) { throw new KeyNotFoundException(string.Format(ProjectResources.ResourceProviderRegistrationFailed, providerName)); } return response.Provider.ToPSResourceProvider(); } /// <summary> /// Parses an array of resource ids to extract the resource group name /// </summary> /// <param name="resourceIds">An array of resource ids</param> public ResourceIdentifier[] ParseResourceIds(string[] resourceIds) { var splitResourceIds = resourceIds .Select(resourceId => resourceId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)) .ToArray(); if (splitResourceIds.Any(splitResourceId => splitResourceId.Length % 2 != 0 || splitResourceId.Length < 8 || !string.Equals("subscriptions", splitResourceId[0], StringComparison.InvariantCultureIgnoreCase) || !string.Equals("resourceGroups", splitResourceId[2], StringComparison.InvariantCultureIgnoreCase) || !string.Equals("providers", splitResourceId[4], StringComparison.InvariantCultureIgnoreCase))) { throw new System.Management.Automation.PSArgumentException(ProjectResources.InvalidFormatOfResourceId); } return resourceIds .Distinct(StringComparer.InvariantCultureIgnoreCase) .Select(resourceId => new ResourceIdentifier(resourceId)) .ToArray(); } /// <summary> /// Get a mapping of Resource providers that support the operations API (/operations) to the operations api-version supported for that RP /// (Current logic is to prefer the latest "non-test' api-version. If there are no such version, choose the latest one) /// </summary> public Dictionary<string, string> GetResourceProvidersWithOperationsSupport() { PSResourceProvider[] allProviders = this.ListPSResourceProviders(listAvailable: true); Dictionary<string, string> providersSupportingOperations = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); PSResourceProviderResourceType[] providerResourceTypes = null; foreach (PSResourceProvider provider in allProviders) { providerResourceTypes = provider.ResourceTypes; if (providerResourceTypes != null && providerResourceTypes.Any()) { PSResourceProviderResourceType operationsResourceType = providerResourceTypes.Where(r => r != null && r.ResourceTypeName == ResourcesClient.Operations).FirstOrDefault(); if (operationsResourceType != null && operationsResourceType.ApiVersions != null && operationsResourceType.ApiVersions.Any()) { string[] allowedTestPrefixes = new[] { "-preview", "-alpha", "-beta", "-rc", "-privatepreview" }; List<string> nonTestApiVersions = new List<string>(); foreach (string apiVersion in operationsResourceType.ApiVersions) { bool isTestApiVersion = false; foreach (string testPrefix in allowedTestPrefixes) { if (apiVersion.EndsWith(testPrefix, StringComparison.InvariantCultureIgnoreCase)) { isTestApiVersion = true; break; } } if(isTestApiVersion == false && !nonTestApiVersions.Contains(apiVersion)) { nonTestApiVersions.Add(apiVersion); } } if(nonTestApiVersions.Any()) { string latestNonTestApiVersion = nonTestApiVersions.OrderBy(o => o).Last(); providersSupportingOperations.Add(provider.ProviderNamespace, latestNonTestApiVersion); } else { providersSupportingOperations.Add(provider.ProviderNamespace, operationsResourceType.ApiVersions.OrderBy(o => o).Last()); } } } } return providersSupportingOperations; } /// <summary> /// Get the list of resource provider operations for every provider specified by the identities list /// </summary> public IList<PSResourceProviderOperation> ListPSProviderOperations(IList<ResourceIdentity> identities) { var allProviderOperations = new List<PSResourceProviderOperation>(); Task<ResourceProviderOperationDetailListResult> task; if(identities != null) { foreach (var identity in identities) { try { task = this.ResourceManagementClient.ResourceProviderOperationDetails.ListAsync(identity); task.Wait(10000); // Add operations for this provider. if (task.IsCompleted) { allProviderOperations.AddRange(task.Result.ResourceProviderOperationDetails.Select(op => op.ToPSResourceProviderOperation())); } } catch(AggregateException ae) { AggregateException flattened = ae.Flatten(); foreach (Exception inner in flattened.InnerExceptions) { // Do nothing for now - this is just a mitigation against one provider which hasn't implemented the operations API correctly //WriteWarning(inner.ToString()); } } } } return allProviderOperations; } } }
praveennet/azure-powershell
src/ResourceManager/Resources/Commands.Resources/Models.ResourceGroups/ResourceClient.cs
C#
apache-2.0
23,374
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.storage.am.common.api; @FunctionalInterface public interface ITreeIndexMetadataFrameFactory { ITreeIndexMetadataFrame createFrame(); }
ty1er/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-storage-am-common/src/main/java/org/apache/hyracks/storage/am/common/api/ITreeIndexMetadataFrameFactory.java
Java
apache-2.0
976
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; namespace Google.Cloud.Bigtable.V2 { /// <summary> /// A version which uniquely identifies a cell within a column. /// </summary> /// <remarks> /// <para> /// Note: version values are stored on the server as if they are microseconds since the Unix epoch. /// However, the server only supports millisecond granularity, so the server only allows microseconds /// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing /// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning /// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying /// microsecond value is still provided via <see cref="Micros"/>. /// </para> /// <para> /// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which /// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes /// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to /// using a custom versioning scheme with 64-bit values. /// </para> /// </remarks> public struct BigtableVersion : IComparable, IComparable<BigtableVersion>, IEquatable<BigtableVersion> { private const long MillisPerMicro = 1000; private const long TicksPerMicro = 10; private const long TicksPerMilli = TicksPerMicro * MillisPerMicro; // Visible for testing internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private long _micros; private BigtableVersion(long value, bool valueIsMillis) { if (valueIsMillis) { GaxPreconditions.CheckArgumentRange(value, nameof(value), -1, long.MaxValue / MillisPerMicro); _micros = value == -1 ? MicrosFromTimestamp(DateTime.UtcNow) : value * MillisPerMicro; } else { GaxPreconditions.CheckArgumentRange(value, nameof(value), -1, long.MaxValue); _micros = value; } } /// <summary> /// Creates a new <see cref="BigtableVersion"/> value from a 64-bit value. /// </summary> /// <remarks> /// <para> /// Note: version values are stored on the server as if they are microseconds since the Unix epoch. /// However, the server only supports millisecond granularity, so the server only allows microseconds /// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing /// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning /// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying /// microsecond value is still provided via <see cref="Micros"/>. /// </para> /// <para> /// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which /// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes /// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to /// using a custom versioning scheme with 64-bit values. /// </para> /// </remarks> /// <param name="value"> /// The non-negative version value, or -1 to initialize from the milliseconds of DateTime.UtcNow. /// Must be less than or equal to 9223372036854775. /// </param> public BigtableVersion(long value) : this(value, valueIsMillis: true) { } /// <summary> /// Creates a new <see cref="BigtableVersion"/> value from the milliseconds of a timestamp since the Unix epoch. /// </summary> /// <remarks> /// <para> /// Note: version values are stored on the server as if they are microseconds since the Unix epoch. /// However, the server only supports millisecond granularity, so the server only allows microseconds /// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing /// its underlying <see cref="Value"/> in terms of milliseconds, so if desired, a custom versioning /// scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to the underlying /// microsecond value is still provided via <see cref="Micros"/>. /// </para> /// <para> /// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which /// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes /// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to /// using a custom versioning scheme with 64-bit values. /// </para> /// </remarks> /// <param name="timestamp"> /// The timestamp whose milliseconds since the Unix epoch should be used as the version value. It must be specified in UTC. /// </param> public BigtableVersion(DateTime timestamp) { GaxPreconditions.CheckArgument( timestamp.Kind == DateTimeKind.Utc, nameof(timestamp), $"The {nameof(BigtableVersion)} timestamp must be specified in UTC."); GaxPreconditions.CheckArgumentRange( timestamp, nameof(timestamp), UnixEpoch, DateTime.MaxValue); _micros = MicrosFromTimestamp(timestamp); } internal static BigtableVersion FromMicros(long value) => new BigtableVersion(value, valueIsMillis: false); private static long MicrosFromTimestamp(DateTime timestamp) => ((timestamp.Ticks - UnixEpoch.Ticks) / TicksPerMilli) * MillisPerMicro; /// <summary> /// Gets the version value interpreted as microseconds of a timestamp since the Unix epoch. /// Greater version values indicate newer cell values. /// </summary> public long Micros => _micros; /// <summary> /// Gets the version value. Greater version values indicate newer cell values. /// </summary> /// <remarks> /// If timestamps are used as versions, this would be the milliseconds since the Unix epoch. /// </remarks> public long Value => _micros / 1000; /// <summary> /// Gets the DateTime equivalent to the version assuming the value is a timestamp milliseconds value since the Unix epoch. /// </summary> /// <returns>The DateTime representing the version timestamp.</returns> public DateTime ToDateTime() => new DateTime((_micros * TicksPerMicro) + UnixEpoch.Ticks, DateTimeKind.Utc); /// <inheritdoc /> public int CompareTo(object obj) { if (obj is BigtableVersion other) { return CompareTo(other); } throw new ArgumentException($"The specified object cannot be compared with {nameof(BigtableVersion)}", nameof(obj)); } /// <inheritdoc /> public int CompareTo(BigtableVersion other) => _micros.CompareTo(other._micros); /// <summary> /// Compares two nullable <see cref="BigtableVersion"/> values. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is less than <paramref name="y"/>; otherwise false.</returns> public static int Compare(BigtableVersion? x, BigtableVersion? y) { if (x == null) { return y == null ? 0 : -1; } else if (y == null) { return 1; } return x.Value.CompareTo(y.Value); } /// <inheritdoc /> public bool Equals(BigtableVersion other) => CompareTo(other) == 0; /// <inheritdoc /> public override bool Equals(object obj) => obj is BigtableVersion other && Equals(other); /// <inheritdoc /> public override int GetHashCode() => _micros.GetHashCode(); /// <inheritdoc /> public override string ToString() => $"{nameof(BigtableVersion)}: {Value}"; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is less than <paramref name="y"/>; otherwise false.</returns> public static bool operator <(BigtableVersion x, BigtableVersion y) => x._micros < y._micros; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is less than or equal <paramref name="y"/>; otherwise false.</returns> public static bool operator <=(BigtableVersion x, BigtableVersion y) => x._micros <= y._micros; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values for equality. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is equal to <paramref name="y"/>; otherwise false.</returns> public static bool operator ==(BigtableVersion x, BigtableVersion y) => x._micros == y._micros; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values for inequality. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is not equal to <paramref name="y"/>; otherwise false.</returns> public static bool operator !=(BigtableVersion x, BigtableVersion y) => x._micros != y._micros; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is greater than or equal <paramref name="y"/>; otherwise false.</returns> public static bool operator >=(BigtableVersion x, BigtableVersion y) => x._micros >= y._micros; /// <summary> /// Operator overload to compare two <see cref="BigtableVersion"/> values. /// </summary> /// <param name="x">Left value to compare</param> /// <param name="y">Right value to compare</param> /// <returns>true if <paramref name="x"/> is greater than <paramref name="y"/>; otherwise false.</returns> public static bool operator >(BigtableVersion x, BigtableVersion y) => x._micros > y._micros; } internal static class BigtableVersionExtensions { public static long ToTimestampMicros(this BigtableVersion? version) => version == null ? 0 : version.Value.Micros; public static BigtableVersion? ToVersion(this long? timestampMillis) => timestampMillis == null ? default(BigtableVersion?) : new BigtableVersion(timestampMillis.Value); public static BigtableVersion? ToVersion(this DateTime? timestamp) => timestamp == null ? default(BigtableVersion?) : new BigtableVersion(timestamp.Value); } }
googleapis/google-cloud-dotnet
apis/Google.Cloud.Bigtable.V2/Google.Cloud.Bigtable.V2/BigtableVersion.cs
C#
apache-2.0
12,638
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Training helper that checkpoints models and creates session.""" import time import numpy as np from tensorflow.python.client import session from tensorflow.python.distribute import distribution_strategy_context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import checkpoint_management from tensorflow.python.util.tf_export import tf_export def _maybe_name(obj): """Returns object name if it has one, or a message otherwise. This is useful for names that apper in error messages. Args: obj: Object to get the name of. Returns: name, "None", or a "no name" message. """ if obj is None: return "None" elif hasattr(obj, "name"): return obj.name else: return "<no name for %s>" % type(obj) def _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, path): """Restores checkpoint values and SavedModel initializers if found.""" # NOTE: All references to SavedModel refer to SavedModels loaded from the # load_v2 API (which does not require the `sess` argument). # If the graph contains resources loaded from a SavedModel, they are not # restored when calling `saver.restore`. Thus, the SavedModel initializer must # be called with `saver.restore` to properly initialize the model. # The SavedModel init is stored in the "saved_model_initializers" collection. # This collection is part of the MetaGraph's default_init_op, so it is already # called by MonitoredSession as long as the saver doesn't restore any # checkpoints from the working dir. saved_model_init_ops = ops.get_collection("saved_model_initializers") if saved_model_init_ops: sess.run(saved_model_init_ops) # The saver must be called *after* the SavedModel init, because the SavedModel # init will restore the variables from the SavedModel variables directory. # Initializing/restoring twice is not ideal but there's no other way to do it. saver.restore(sess, path) @tf_export(v1=["train.SessionManager"]) class SessionManager(object): """Training helper that restores from checkpoint and creates session. This class is a small wrapper that takes care of session creation and checkpoint recovery. It also provides functions that to facilitate coordination among multiple training threads or processes. * Checkpointing trained variables as the training progresses. * Initializing variables on startup, restoring them from the most recent checkpoint after a crash, or wait for checkpoints to become available. ### Usage: ```python with tf.Graph().as_default(): ...add operations to the graph... # Create a SessionManager that will checkpoint the model in '/tmp/mydir'. sm = SessionManager() sess = sm.prepare_session(master, init_op, saver, checkpoint_dir) # Use the session to train the graph. while True: sess.run(<my_train_op>) ``` `prepare_session()` initializes or restores a model. It requires `init_op` and `saver` as an argument. A second process could wait for the model to be ready by doing the following: ```python with tf.Graph().as_default(): ...add operations to the graph... # Create a SessionManager that will wait for the model to become ready. sm = SessionManager() sess = sm.wait_for_session(master) # Use the session to train the graph. while True: sess.run(<my_train_op>) ``` `wait_for_session()` waits for a model to be initialized by other processes. """ def __init__(self, local_init_op=None, ready_op=None, ready_for_local_init_op=None, graph=None, recovery_wait_secs=30, local_init_run_options=None, local_init_feed_dict=None): """Creates a SessionManager. The `local_init_op` is an `Operation` that is run always after a new session was created. If `None`, this step is skipped. The `ready_op` is an `Operation` used to check if the model is ready. The model is considered ready if that operation returns an empty 1D string tensor. If the operation returns a non empty 1D string tensor, the elements are concatenated and used to indicate to the user why the model is not ready. The `ready_for_local_init_op` is an `Operation` used to check if the model is ready to run local_init_op. The model is considered ready if that operation returns an empty 1D string tensor. If the operation returns a non empty 1D string tensor, the elements are concatenated and used to indicate to the user why the model is not ready. If `ready_op` is `None`, the model is not checked for readiness. `recovery_wait_secs` is the number of seconds between checks that the model is ready. It is used by processes to wait for a model to be initialized or restored. Defaults to 30 seconds. Args: local_init_op: An `Operation` run immediately after session creation. Usually used to initialize tables and local variables. ready_op: An `Operation` to check if the model is initialized. ready_for_local_init_op: An `Operation` to check if the model is ready to run local_init_op. graph: The `Graph` that the model will use. recovery_wait_secs: Seconds between checks for the model to be ready. local_init_run_options: RunOptions to be passed to session.run when executing the local_init_op. local_init_feed_dict: Optional session feed dictionary to use when running the local_init_op. Raises: ValueError: If ready_for_local_init_op is not None but local_init_op is None """ # Sets default values of arguments. if graph is None: graph = ops.get_default_graph() self._local_init_op = local_init_op self._ready_op = ready_op self._ready_for_local_init_op = ready_for_local_init_op self._graph = graph self._recovery_wait_secs = recovery_wait_secs self._target = None self._local_init_run_options = local_init_run_options self._local_init_feed_dict = local_init_feed_dict if ready_for_local_init_op is not None and local_init_op is None: raise ValueError("If you pass a ready_for_local_init_op " "you must also pass a local_init_op " ", ready_for_local_init_op [%s]" % ready_for_local_init_op) def _restore_checkpoint(self, master, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None): """Creates a `Session`, and tries to restore a checkpoint. Args: master: `String` representation of the TensorFlow master to use. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. Returns: A pair (sess, is_restored) where 'is_restored' is `True` if the session could be restored, `False` otherwise. Raises: ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """ self._target = master # This is required to so that we initialize the TPU device before # restoring from checkpoint since we'll be placing variables on the device # and TPUInitialize wipes out the memory of the device. strategy = distribution_strategy_context.get_strategy() if strategy and hasattr(strategy.extended, "_experimental_initialize_system"): strategy.extended._experimental_initialize_system() # pylint: disable=protected-access sess = session.Session(self._target, graph=self._graph, config=config) if checkpoint_dir and checkpoint_filename_with_path: raise ValueError("Can not provide both checkpoint_dir and " "checkpoint_filename_with_path.") # If either saver or checkpoint_* is not specified, cannot restore. Just # return. if not saver or not (checkpoint_dir or checkpoint_filename_with_path): return sess, False if checkpoint_filename_with_path: _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, checkpoint_filename_with_path) return sess, True # Waits up until max_wait_secs for checkpoint to become available. wait_time = 0 ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) while not ckpt or not ckpt.model_checkpoint_path: if wait_for_checkpoint and wait_time < max_wait_secs: logging.info("Waiting for checkpoint to be available.") time.sleep(self._recovery_wait_secs) wait_time += self._recovery_wait_secs ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) else: return sess, False # Loads the checkpoint. _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, ckpt.model_checkpoint_path) saver.recover_last_checkpoints(ckpt.all_model_checkpoint_paths) return sess, True def prepare_session(self, master, init_op=None, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None): """Creates a `Session`. Makes sure the model is ready to be used. Creates a `Session` on 'master'. If a `saver` object is passed in, and `checkpoint_dir` points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and `wait_for_checkpoint` is `True`, then the process would check every `recovery_wait_secs`, up to `max_wait_secs`, for recovery to succeed. If the model cannot be recovered successfully then it is initialized by running the `init_op` and calling `init_fn` if they are provided. The `local_init_op` is also run after init_op and init_fn, regardless of whether the model was recovered successfully, but only if `ready_for_local_init_op` passes. If the model is recovered from a checkpoint it is assumed that all global variables have been initialized, in particular neither `init_op` nor `init_fn` will be executed. It is an error if the model cannot be recovered and no `init_op` or `init_fn` or `local_init_op` are passed. Args: master: `String` representation of the TensorFlow master to use. init_op: Optional `Operation` used to initialize the model. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. init_feed_dict: Optional dictionary that maps `Tensor` objects to feed values. This feed dictionary is passed to the session `run()` call when running the init op. init_fn: Optional callable used to initialize the model. Called after the optional `init_op` is called. The callable must accept one argument, the session being initialized. Returns: A `Session` object that can be used to drive the model. Raises: RuntimeError: If the model cannot be initialized or recovered. ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """ sess, is_loaded_from_checkpoint = self._restore_checkpoint( master, saver, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config) if not is_loaded_from_checkpoint: if init_op is None and not init_fn and self._local_init_op is None: raise RuntimeError("Model is not initialized and no init_op or " "init_fn or local_init_op was given") if init_op is not None: sess.run(init_op, feed_dict=init_feed_dict) if init_fn: init_fn(sess) local_init_success, msg = self._try_run_local_init_op(sess) if not local_init_success: raise RuntimeError( "Init operations did not make model ready for local_init. " "Init op: %s, init fn: %s, error: %s" % (_maybe_name(init_op), init_fn, msg)) is_ready, msg = self._model_ready(sess) if not is_ready: raise RuntimeError( "Init operations did not make model ready. " "Init op: %s, init fn: %s, local_init_op: %s, error: %s" % (_maybe_name(init_op), init_fn, self._local_init_op, msg)) return sess def recover_session(self, master, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None): """Creates a `Session`, recovering if possible. Creates a new session on 'master'. If the session is not initialized and can be recovered from a checkpoint, recover it. Args: master: `String` representation of the TensorFlow master to use. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. Returns: A pair (sess, initialized) where 'initialized' is `True` if the session could be recovered and initialized, `False` otherwise. Raises: ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """ sess, is_loaded_from_checkpoint = self._restore_checkpoint( master, saver, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config) # Always try to run local_init_op local_init_success, msg = self._try_run_local_init_op(sess) if not is_loaded_from_checkpoint: # Do not need to run checks for readiness return sess, False restoring_file = checkpoint_dir or checkpoint_filename_with_path if not local_init_success: logging.info( "Restoring model from %s did not make model ready for local init:" " %s", restoring_file, msg) return sess, False is_ready, msg = self._model_ready(sess) if not is_ready: logging.info("Restoring model from %s did not make model ready: %s", restoring_file, msg) return sess, False logging.info("Restored model from %s", restoring_file) return sess, is_loaded_from_checkpoint def wait_for_session(self, master, config=None, max_wait_secs=float("Inf")): """Creates a new `Session` and waits for model to be ready. Creates a new `Session` on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained. NB: The amount of time this method waits for the session is bounded by max_wait_secs. By default, this function will wait indefinitely. Args: master: `String` representation of the TensorFlow master to use. config: Optional ConfigProto proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. Returns: A `Session`. May be None if the operation exceeds the timeout specified by config.operation_timeout_in_ms. Raises: tf.DeadlineExceededError: if the session is not available after max_wait_secs. """ self._target = master if max_wait_secs is None: max_wait_secs = float("Inf") timer = _CountDownTimer(max_wait_secs) while True: sess = session.Session(self._target, graph=self._graph, config=config) not_ready_msg = None not_ready_local_msg = None local_init_success, not_ready_local_msg = self._try_run_local_init_op( sess) if local_init_success: # Successful if local_init_op is None, or ready_for_local_init_op passes is_ready, not_ready_msg = self._model_ready(sess) if is_ready: return sess self._safe_close(sess) # Do we have enough time left to try again? remaining_ms_after_wait = ( timer.secs_remaining() - self._recovery_wait_secs) if remaining_ms_after_wait < 0: raise errors.DeadlineExceededError( None, None, "Session was not ready after waiting %d secs." % (max_wait_secs,)) logging.info("Waiting for model to be ready. " "Ready_for_local_init_op: %s, ready: %s", not_ready_local_msg, not_ready_msg) time.sleep(self._recovery_wait_secs) def _safe_close(self, sess): """Closes a session without raising an exception. Just like sess.close() but ignores exceptions. Args: sess: A `Session`. """ # pylint: disable=broad-except try: sess.close() except Exception: # Intentionally not logging to avoid user complaints that # they get cryptic errors. We really do not care that Close # fails. pass # pylint: enable=broad-except def _model_ready(self, sess): """Checks if the model is ready or not. Args: sess: A `Session`. Returns: A tuple (is_ready, msg), where is_ready is True if ready and False otherwise, and msg is `None` if the model is ready, a `String` with the reason why it is not ready otherwise. """ return _ready(self._ready_op, sess, "Model not ready") def _model_ready_for_local_init(self, sess): """Checks if the model is ready to run local_init_op. Args: sess: A `Session`. Returns: A tuple (is_ready, msg), where is_ready is True if ready to run local_init_op and False otherwise, and msg is `None` if the model is ready to run local_init_op, a `String` with the reason why it is not ready otherwise. """ return _ready(self._ready_for_local_init_op, sess, "Model not ready for local init") def _try_run_local_init_op(self, sess): """Tries to run _local_init_op, if not None, and is ready for local init. Args: sess: A `Session`. Returns: A tuple (is_successful, msg), where is_successful is True if _local_init_op is None, or we ran _local_init_op, and False otherwise; and msg is a `String` with the reason why the model was not ready to run local init. """ if self._local_init_op is not None: is_ready_for_local_init, msg = self._model_ready_for_local_init(sess) if is_ready_for_local_init: logging.info("Running local_init_op.") sess.run(self._local_init_op, feed_dict=self._local_init_feed_dict, options=self._local_init_run_options) logging.info("Done running local_init_op.") return True, None else: return False, msg return True, None def _ready(op, sess, msg): """Checks if the model is ready or not, as determined by op. Args: op: An op, either _ready_op or _ready_for_local_init_op, which defines the readiness of the model. sess: A `Session`. msg: A message to log to warning if not ready Returns: A tuple (is_ready, msg), where is_ready is True if ready and False otherwise, and msg is `None` if the model is ready, a `String` with the reason why it is not ready otherwise. """ if op is None: return True, None else: try: ready_value = sess.run(op) # The model is considered ready if ready_op returns an empty 1-D tensor. # Also compare to `None` and dtype being int32 for backward # compatibility. if (ready_value is None or ready_value.dtype == np.int32 or ready_value.size == 0): return True, None else: # TODO(sherrym): If a custom ready_op returns other types of tensor, # or strings other than variable names, this message could be # confusing. non_initialized_varnames = ", ".join( [i.decode("utf-8") for i in ready_value]) return False, "Variables not initialized: " + non_initialized_varnames except errors.FailedPreconditionError as e: if "uninitialized" not in str(e): logging.warning("%s : error [%s]", msg, str(e)) raise e return False, str(e) class _CountDownTimer(object): __slots__ = ["_start_time_secs", "_duration_secs"] def __init__(self, duration_secs): self._start_time_secs = time.time() self._duration_secs = duration_secs def secs_remaining(self): diff = self._duration_secs - (time.time() - self._start_time_secs) return max(0, diff)
tensorflow/tensorflow
tensorflow/python/training/session_manager.py
Python
apache-2.0
23,320
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.sabrcube; import static com.opengamma.engine.value.ValueRequirementNames.SABR_SURFACES; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.interestrate.PresentValueCurveSensitivitySABRCalculator; import com.opengamma.analytics.financial.interestrate.PresentValueNodeSensitivityCalculator; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateCorrelationParameters; import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateDataBundle; import com.opengamma.analytics.math.function.DoubleFunction1D; import com.opengamma.analytics.math.surface.InterpolatedDoublesSurface; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.SurfaceAndCubePropertyNames; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.financial.analytics.model.sabr.SABRDiscountingFunction; import com.opengamma.financial.analytics.model.volatility.SmileFittingPropertyNamesAndValues; import com.opengamma.financial.analytics.volatility.fittedresults.SABRFittedSurfaces; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.financial.security.FinancialSecurityUtils; import com.opengamma.util.money.Currency; /** * @deprecated Use descendants of {@link SABRDiscountingFunction} */ @Deprecated public class SABRCMSSpreadNoExtrapolationYCNSFunction extends SABRYCNSFunction { private static final PresentValueNodeSensitivityCalculator NSC = PresentValueNodeSensitivityCalculator.using(PresentValueCurveSensitivitySABRCalculator.getInstance()); @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.CAP_FLOOR_CMS_SPREAD_SECURITY; } @Override protected SABRInterestRateDataBundle getModelParameters(final ComputationTarget target, final FunctionInputs inputs, final Currency currency, final YieldCurveBundle yieldCurves, final ValueRequirement desiredValue) { final Object surfacesObject = inputs.getValue(SABR_SURFACES); if (surfacesObject == null) { throw new OpenGammaRuntimeException("Could not get SABR parameter surfaces"); } final SABRFittedSurfaces surfaces = (SABRFittedSurfaces) surfacesObject; final InterpolatedDoublesSurface alphaSurface = surfaces.getAlphaSurface(); final InterpolatedDoublesSurface betaSurface = surfaces.getBetaSurface(); final InterpolatedDoublesSurface nuSurface = surfaces.getNuSurface(); final InterpolatedDoublesSurface rhoSurface = surfaces.getRhoSurface(); final DoubleFunction1D correlationFunction = getCorrelationFunction(); final SABRInterestRateCorrelationParameters modelParameters = new SABRInterestRateCorrelationParameters(alphaSurface, betaSurface, rhoSurface, nuSurface, correlationFunction); return new SABRInterestRateDataBundle(modelParameters, yieldCurves); } @Override protected ValueProperties.Builder createValueProperties(final Currency currency) { return createValueProperties() .with(ValuePropertyNames.CURRENCY, currency.getCode()) .with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode()) .withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.CURVE) .withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION) .withAny(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD) .with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION); } @Override protected ValueProperties.Builder createValueProperties(final ComputationTarget target, final ValueRequirement desiredValue) { final String cubeDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION); final String cubeSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION); final String surfaceDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION); final String surfaceSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION); final String currency = FinancialSecurityUtils.getCurrency(target.getSecurity()).getCode(); final String curveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG); final String fittingMethod = desiredValue.getConstraint(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD); final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE); return createValueProperties() .with(ValuePropertyNames.CURRENCY, currency) .with(ValuePropertyNames.CURVE_CURRENCY, currency) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfig) .with(ValuePropertyNames.CURVE, curveName) .with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION, cubeDefinitionName) .with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION, cubeSpecificationName) .with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION, surfaceDefinitionName) .with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION, surfaceSpecificationName) .with(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD, fittingMethod) .with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION); } @Override protected PresentValueNodeSensitivityCalculator getNodeSensitivityCalculator(final ValueRequirement desiredValue) { return NSC; } private static DoubleFunction1D getCorrelationFunction() { return new DoubleFunction1D() { @Override public Double evaluate(final Double x) { return 0.8; } }; } }
jeorme/OG-Platform
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/sabrcube/SABRCMSSpreadNoExtrapolationYCNSFunction.java
Java
apache-2.0
6,665
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.databridge.agent.conf; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.wso2.carbon.databridge.agent.util.DataEndpointConstants; public class DataEndpointConfiguration { private String receiverURL; private String authURL; private String username; private String password; private GenericKeyedObjectPool transportPool; private GenericKeyedObjectPool securedTransportPool; private int batchSize; private String publisherKey; private String authKey; private String sessionId; private int corePoolSize; private int maxPoolSize; private int keepAliveTimeInPool; public enum Protocol { TCP, SSL; @Override public String toString() { return super.toString().toLowerCase(); } } public DataEndpointConfiguration(String receiverURL, String authURL, String username, String password, GenericKeyedObjectPool transportPool, GenericKeyedObjectPool securedTransportPool, int batchSize, int corePoolSize, int maxPoolSize, int keepAliveTimeInPool) { this.receiverURL = receiverURL; this.authURL = authURL; this.username = username; this.password = password; this.transportPool = transportPool; this.securedTransportPool = securedTransportPool; this.publisherKey = this.receiverURL + DataEndpointConstants.SEPARATOR + username + DataEndpointConstants.SEPARATOR + password; this.authKey = this.authURL + DataEndpointConstants.SEPARATOR + username + DataEndpointConstants.SEPARATOR + password; this.batchSize = batchSize; this.corePoolSize = corePoolSize; this.maxPoolSize = maxPoolSize; this.keepAliveTimeInPool = keepAliveTimeInPool; } public String getReceiverURL() { return receiverURL; } public String getUsername() { return username; } public String getAuthURL() { return authURL; } public String getPassword() { return password; } public String toString() { return "ReceiverURL: " + receiverURL + "," + "Authentication URL: " + authURL + "," + "Username: " + username; } public String getPublisherKey() { return publisherKey; } public String getAuthKey() { return authKey; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public GenericKeyedObjectPool getTransportPool() { return transportPool; } public GenericKeyedObjectPool getSecuredTransportPool() { return securedTransportPool; } public int getCorePoolSize() { return corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public int getKeepAliveTimeInPool() { return keepAliveTimeInPool; } public int getBatchSize() { return batchSize; } }
keizer619/carbon-analytics-common
components/data-bridge/org.wso2.carbon.databridge.agent/src/main/java/org/wso2/carbon/databridge/agent/conf/DataEndpointConfiguration.java
Java
apache-2.0
3,842
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.olingo.odata2.core.batch; import java.util.List; import org.apache.olingo.odata2.api.batch.BatchResponsePart; import org.apache.olingo.odata2.api.processor.ODataResponse; public class BatchResponsePartImpl extends BatchResponsePart { private List<ODataResponse> responses; private boolean isChangeSet; @Override public List<ODataResponse> getResponses() { return responses; } @Override public boolean isChangeSet() { return isChangeSet; } public class BatchResponsePartBuilderImpl extends BatchResponsePartBuilder { private List<ODataResponse> responses; private boolean isChangeSet; @Override public BatchResponsePart build() { BatchResponsePartImpl.this.responses = responses; BatchResponsePartImpl.this.isChangeSet = isChangeSet; return BatchResponsePartImpl.this; } @Override public BatchResponsePartBuilder responses(final List<ODataResponse> responses) { this.responses = responses; return this; } @Override public BatchResponsePartBuilder changeSet(final boolean isChangeSet) { this.isChangeSet = isChangeSet; return this; } } }
apache/olingo-odata2
odata2-lib/odata-core/src/main/java/org/apache/olingo/odata2/core/batch/BatchResponsePartImpl.java
Java
apache-2.0
2,137
/// <reference path='fourslash.ts' /> // @allowjs: true // @checkJs: true // @noEmit: true // @filename: a.js ////// @ts-check ////let x = ""; ////[|x|] = 1; // verify.codeFixAvailable([ // { description: ts.Diagnostics.Ignore_this_error_message.message }, // { description: ts.Diagnostics.Disable_checking_for_this_file.message } // ]); verify.codeFix({ description: ts.Diagnostics.Disable_checking_for_this_file.message, index: 1, newFileContent: `// @ts-nocheck let x = ""; x = 1;`, });
Microsoft/TypeScript
tests/cases/fourslash/codeFixDisableJsDiagnosticsInFile9.ts
TypeScript
apache-2.0
538
//----------------------------------------------------------------------- // <copyright file="SourceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class SourceSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public SourceSpec(ITestOutputHelper helper) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } [Fact] public void Single_Source_must_produce_element() { var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); var sub = c.ExpectSubscription(); sub.Request(1); c.ExpectNext(1); c.ExpectComplete(); } [Fact] public void Single_Source_must_reject_later_subscriber() { var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer); var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c1); var sub1 = c1.ExpectSubscription(); sub1.Request(1); c1.ExpectNext(1); c1.ExpectComplete(); p.Subscribe(c2); c2.ExpectSubscriptionAndError(); } [Fact] public void Empty_Source_must_complete_immediately() { var p = Source.Empty<int>().RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); c.ExpectSubscriptionAndComplete(); //reject additional subscriber var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c2); c2.ExpectSubscriptionAndError(); } [Fact] public void Failed_Source_must_emit_error_immediately() { var ex = new SystemException(); var p = Source.Failed<int>(ex).RunWith(Sink.AsPublisher<int>(false), Materializer); var c = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c); c.ExpectSubscriptionAndError(); //reject additional subscriber var c2 = TestSubscriber.CreateManualProbe<int>(this); p.Subscribe(c2); c2.ExpectSubscriptionAndError(); } [Fact] public void Maybe_Source_must_complete_materialized_future_with_None_when_stream_cancels() { this.AssertAllStagesStopped(() => { var neverSource = Source.Maybe<object>(); var pubSink = Sink.AsPublisher<object>(false); var t = neverSource.ToMaterialized(pubSink, Keep.Both).Run(Materializer); var f = t.Item1; var neverPub = t.Item2; var c = TestSubscriber.CreateManualProbe<object>(this); neverPub.Subscribe(c); var subs = c.ExpectSubscription(); subs.Request(1000); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); subs.Cancel(); f.Task.Wait(500).Should().BeTrue(); f.Task.Result.Should().Be(null); }, Materializer); } [Fact] public void Maybe_Source_must_allow_external_triggering_of_empty_completion() { this.AssertAllStagesStopped(() => { var neverSource = Source.Maybe<int>().Where(_ => false); var counterSink = Sink.Aggregate<int, int>(0, (acc, _) => acc + 1); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.TrySetResult(0).Should().BeTrue(); counterFuture.Wait(500).Should().BeTrue(); counterFuture.Result.Should().Be(0); }, Materializer); } [Fact] public void Maybe_Source_must_allow_external_triggering_of_non_empty_completion() { this.AssertAllStagesStopped(() => { var neverSource = Source.Maybe<int>(); var counterSink = Sink.First<int>(); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.TrySetResult(6).Should().BeTrue(); counterFuture.Wait(500).Should().BeTrue(); counterFuture.Result.Should().Be(6); }, Materializer); } [Fact] public void Maybe_Source_must_allow_external_triggering_of_OnError() { this.AssertAllStagesStopped(() => { var neverSource = Source.Maybe<int>(); var counterSink = Sink.First<int>(); var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer); var neverPromise = t.Item1; var counterFuture = t.Item2; //external cancellation neverPromise.SetException(new Exception("Boom")); counterFuture.Invoking(f => f.Wait(500)).ShouldThrow<Exception>() .WithMessage("Boom"); }, Materializer); } [Fact] public void Composite_Source_must_merge_from_many_inputs() { var probes = Enumerable.Range(1, 5).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = Source.AsSubscriber<int>(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); var s = Source.FromGraph(GraphDsl.Create(source, source, source, source, source, (a, b, c, d, e) => new[] {a, b, c, d, e}, (b, i0, i1, i2, i3, i4) => { var m = b.Add(new Merge<int>(5)); b.From(i0.Outlet).To(m.In(0)); b.From(i1.Outlet).To(m.In(1)); b.From(i2.Outlet).To(m.In(2)); b.From(i3.Outlet).To(m.In(3)); b.From(i4.Outlet).To(m.In(4)); return new SourceShape<int>(m.Out); })).To(Sink.FromSubscriber(outProbe)).Run(Materializer); for (var i = 0; i < 5; i++) probes[i].Subscribe(s[i]); var sub = outProbe.ExpectSubscription(); sub.Request(10); for (var i = 0; i < 5; i++) { var subscription = probes[i].ExpectSubscription(); subscription.ExpectRequest(); subscription.SendNext(i); subscription.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 5; i++) gotten.Add(outProbe.ExpectNext()); gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2, 3, 4}); outProbe.ExpectComplete(); } [Fact] public void Composite_Source_must_combine_from_many_inputs_with_simplified_API() { var probes = Enumerable.Range(1, 3).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = probes.Select(Source.FromPublisher).ToList(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); Source.Combine(source[0], source[1], i => new Merge<int, int>(i), source[2]) .To(Sink.FromSubscriber(outProbe)) .Run(Materializer); var sub = outProbe.ExpectSubscription(); sub.Request(3); for (var i = 0; i < 3; i++) { var s = probes[i].ExpectSubscription(); s.ExpectRequest(); s.SendNext(i); s.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 3; i++) gotten.Add(outProbe.ExpectNext()); gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2}); outProbe.ExpectComplete(); } [Fact] public void Composite_Source_must_combine_from_two_inputs_with_simplified_API() { var probes = Enumerable.Range(1, 2).Select(_ => TestPublisher.CreateManualProbe<int>(this)).ToList(); var source = probes.Select(Source.FromPublisher).ToList(); var outProbe = TestSubscriber.CreateManualProbe<int>(this); Source.Combine(source[0], source[1], i => new Merge<int, int>(i)) .To(Sink.FromSubscriber(outProbe)) .Run(Materializer); var sub = outProbe.ExpectSubscription(); sub.Request(3); for (var i = 0; i < 2; i++) { var s = probes[i].ExpectSubscription(); s.ExpectRequest(); s.SendNext(i); s.SendComplete(); } var gotten = new List<int>(); for (var i = 0; i < 2; i++) gotten.Add(outProbe.ExpectNext()); gotten.ShouldAllBeEquivalentTo(new[] {0, 1}); outProbe.ExpectComplete(); } [Fact] public void Repeat_Source_must_repeat_as_long_as_it_takes() { var f = Source.Repeat(42).Grouped(1000).RunWith(Sink.First<IEnumerable<int>>(), Materializer); f.Result.Should().HaveCount(1000).And.Match(x => x.All(i => i == 42)); } private static readonly int[] Expected = { 9227465, 5702887, 3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711, 10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0 }; [Fact] public void Unfold_Source_must_generate_a_finite_fibonacci_sequence() { Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) return null; return Tuple.Create(Tuple.Create(b, a + b), a); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void Unfold_Source_must_terminate_with_a_failure_if_there_is_an_exception_thrown() { EventFilter.Exception<SystemException>(message: "expected").ExpectOne(() => { var task = Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) throw new SystemException("expected"); return Tuple.Create(Tuple.Create(b, a + b), a); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<SystemException>() .WithMessage("expected"); }); } [Fact] public void Unfold_Source_must_generate_a_finite_fibonacci_sequence_asynchronously() { Source.UnfoldAsync(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; if (a > 10000000) return Task.FromResult<Tuple<Tuple<int, int>, int>>(null); return Task.FromResult(Tuple.Create(Tuple.Create(b, a + b), a)); }).RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void Unfold_Source_must_generate_a_unboundeed_fibonacci_sequence() { Source.Unfold(Tuple.Create(0, 1), tuple => { var a = tuple.Item1; var b = tuple.Item2; return Tuple.Create(Tuple.Create(b, a + b), a); }) .Take(36) .RunAggregate(new LinkedList<int>(), (ints, i) => { ints.AddFirst(i); return ints; }, Materializer).Result.Should().Equal(Expected); } [Fact] public void Iterator_Source_must_properly_iterate() { var expected = new[] {false, true, false, true, false, true, false, true, false, true }.ToList(); Source.FromEnumerator(() => expected.GetEnumerator()) .Grouped(10) .RunWith(Sink.First<IEnumerable<bool>>(), Materializer) .Result.Should() .Equal(expected); } [Fact] public void A_Source_must_suitably_override_attribute_handling_methods() { Source.Single(42).Async().AddAttributes(Attributes.None).Named(""); } } }
derwasp/akka.net
src/core/Akka.Streams.Tests/Dsl/SourceSpec.cs
C#
apache-2.0
14,043
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Protos.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Messages { /// <summary>Holder for reflection information generated from Protos.proto</summary> public static partial class ProtosReflection { #region Descriptor /// <summary>File descriptor for Protos.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ProtosReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgxQcm90b3MucHJvdG8SCG1lc3NhZ2VzIh0KDVJlbmFtZUNvbW1hbmQSDAoE", "bmFtZRgBIAEoCSIbCgtSZW5hbWVFdmVudBIMCgRuYW1lGAEgASgJIhUKBVN0", "YXRlEgwKBE5hbWUYASABKAlCC6oCCE1lc3NhZ2VzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Messages.RenameCommand), global::Messages.RenameCommand.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Messages.RenameEvent), global::Messages.RenameEvent.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Messages.State), global::Messages.State.Parser, new[]{ "Name" }, null, null, null) })); } #endregion } #region Messages public sealed partial class RenameCommand : pb::IMessage<RenameCommand> { private static readonly pb::MessageParser<RenameCommand> _parser = new pb::MessageParser<RenameCommand>(() => new RenameCommand()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RenameCommand> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameCommand() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameCommand(RenameCommand other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameCommand Clone() { return new RenameCommand(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RenameCommand); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RenameCommand other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RenameCommand other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } public sealed partial class RenameEvent : pb::IMessage<RenameEvent> { private static readonly pb::MessageParser<RenameEvent> _parser = new pb::MessageParser<RenameEvent>(() => new RenameEvent()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RenameEvent> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameEvent() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameEvent(RenameEvent other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RenameEvent Clone() { return new RenameEvent(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RenameEvent); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RenameEvent other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RenameEvent other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } public sealed partial class State : pb::IMessage<State> { private static readonly pb::MessageParser<State> _parser = new pb::MessageParser<State>(() => new State()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<State> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public State() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public State(State other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public State Clone() { return new State(this); } /// <summary>Field number for the "Name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as State); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(State other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(State other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
masteryee/protoactor-dotnet
examples/Persistence/Messages/Protos.g.cs
C#
apache-2.0
12,536
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.tools.ant.taskdefs.optional; // -- Batik classes ---------------------------------------------------------- import org.apache.batik.transcoder.Transcoder; import org.apache.batik.apps.rasterizer.SVGConverterController; import org.apache.batik.apps.rasterizer.SVGConverterSource; // -- Ant classes ------------------------------------------------------------ import org.apache.tools.ant.Task; // -- Java SDK classes ------------------------------------------------------- import java.io.File; import java.util.Map; import java.util.List; /** * Implements simple controller for the <code>SVGConverter</code> operation. * * <p>This is almost the same as the * {@link org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController} * except this produces error message when the conversion fails.</p> * * <p>See {@link SVGConverterController} for the method documentation.</p> * * @see SVGConverterController SVGConverterController * @see org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController * * @author <a href="mailto:ruini@iki.fi">Henri Ruini</a> * @version $Id: RasterizerTaskSVGConverterController.java 479617 2006-11-27 13:43:51Z dvholten $ */ public class RasterizerTaskSVGConverterController implements SVGConverterController { // -- Variables ---------------------------------------------------------- /** Ant task that is used to log messages. */ protected Task executingTask = null; // -- Constructors ------------------------------------------------------- /** * Don't allow public usage. */ protected RasterizerTaskSVGConverterController() { } /** * Sets the given Ant task to receive log messages. * * @param task Ant task. The value can be <code>null</code> when log messages won't be written. */ public RasterizerTaskSVGConverterController(Task task) { executingTask = task; } // -- Public interface --------------------------------------------------- public boolean proceedWithComputedTask(Transcoder transcoder, Map hints, List sources, List dest){ return true; } public boolean proceedWithSourceTranscoding(SVGConverterSource source, File dest) { return true; } public boolean proceedOnSourceTranscodingFailure(SVGConverterSource source, File dest, String errorCode){ if(executingTask != null) { executingTask.log("Unable to rasterize image '" + source.getName() + "' to '" + dest.getAbsolutePath() + "': " + errorCode); } return true; } public void onSourceTranscodingSuccess(SVGConverterSource source, File dest){ } }
stumoodie/PathwayEditor
libs/batik-1.7/contrib/rasterizertask/sources/org/apache/tools/ant/taskdefs/optional/RasterizerTaskSVGConverterController.java
Java
apache-2.0
3,878
# # Author:: Bryan McLellan <btm@opscode.com> # Copyright:: Copyright (c) 2012 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # require 'spec_helper' describe Chef::Resource::IpsPackage, "initialize" do before(:each) do @resource = Chef::Resource::IpsPackage.new("crypto/gnupg") end it "should return a Chef::Resource::IpsPackage" do @resource.should be_a_kind_of(Chef::Resource::IpsPackage) end it "should set the resource_name to :ips_package" do @resource.resource_name.should eql(:ips_package) end it "should set the provider to Chef::Provider::Package::Ips" do @resource.provider.should eql(Chef::Provider::Package::Ips) end it "should support accept_license" do @resource.accept_license(true) @resource.accept_license.should eql(true) end end
elgalu/chef-depth-1
spec/unit/resource/ips_package_spec.rb
Ruby
apache-2.0
1,353
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public interface MessageAware { public abstract MessageContext getMessageContext(); }
salyh/geronimo-specs
geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageAware.java
Java
apache-2.0
952
<?php /** * ALIPAY API: alipay.eco.mycar.parking.lotbarcode.create request * * @author auto create * @since 1.0, 2016-06-14 15:08:52 */ class AlipayEcoMycarParkingLotbarcodeCreateRequest { /** * 物料二维码 **/ private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; private $returnUrl; private $needEncrypt=false; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.eco.mycar.parking.lotbarcode.create"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function setReturnUrl($returnUrl) { $this->returnUrl=$returnUrl; } public function getReturnUrl() { return $this->returnUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } public function setNeedEncrypt($needEncrypt) { $this->needEncrypt=$needEncrypt; } public function getNeedEncrypt() { return $this->needEncrypt; } }
houdunwang/hdphp
vendor/houdunwang/alipay/src/org/aop/request/AlipayEcoMycarParkingLotbarcodeCreateRequest.php
PHP
apache-2.0
1,918
package com.github.dockerjava.core.command; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; import com.github.dockerjava.core.util.FiltersBuilder; /** * List images */ public class ListImagesCmdImpl extends AbstrDockerCmd<ListImagesCmd, List<Image>> implements ListImagesCmd { private String imageNameFilter; private Boolean showAll = false; private FiltersBuilder filters = new FiltersBuilder(); public ListImagesCmdImpl(ListImagesCmd.Exec exec) { super(exec); } @Override public Map<String, List<String>> getFilters() { return filters.build(); } @Override public Boolean hasShowAllEnabled() { return showAll; } @Override public ListImagesCmd withShowAll(Boolean showAll) { this.showAll = showAll; return this; } @Override public ListImagesCmd withDanglingFilter(Boolean dangling) { checkNotNull(dangling, "dangling have not been specified"); filters.withFilter("dangling", dangling.toString()); return this; } @Override public ListImagesCmd withLabelFilter(String... labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withLabelFilter(Map<String, String> labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withImageNameFilter(String imageNameFilter) { checkNotNull(imageNameFilter, "image name filter not specified"); this.imageNameFilter = imageNameFilter; return this; } @Override public String getImageNameFilter() { return this.imageNameFilter; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
ollie314/docker-java
src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java
Java
apache-2.0
2,238
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * Number.NEGATIVE_INFINITY is -Infinity * * @path ch15/15.7/15.7.3/15.7.3.5/S15.7.3.5_A1.js * @description Checking sign and finiteness of Number.NEGATIVE_INFINITY */ // CHECK#1 if (isFinite(Number.NEGATIVE_INFINITY) !== false) { $ERROR('#1: Number.NEGATIVE_INFINITY === Not-a-Finite'); } else { if ((Number.NEGATIVE_INFINITY < 0) !== true) { $ERROR('#1: Number.NEGATIVE_INFINITY === -Infinity'); } }
hippich/typescript
tests/Fidelity/test262/suite/ch15/15.7/15.7.3/15.7.3.5/S15.7.3.5_A1.js
JavaScript
apache-2.0
555
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.rmi.server; /** * An obsolete subclass of {@link ExportException}. * * @author Ann Wollrath * @since JDK1.1 * @deprecated This class is obsolete. Use {@link ExportException} instead. */ @Deprecated public class SocketSecurityException extends ExportException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7622072999407781979L; /** * Constructs an <code>SocketSecurityException</code> with the specified * detail message. * * @param s the detail message. * @since JDK1.1 */ public SocketSecurityException(String s) { super(s); } /** * Constructs an <code>SocketSecurityException</code> with the specified * detail message and nested exception. * * @param s the detail message. * @param ex the nested exception * @since JDK1.1 */ public SocketSecurityException(String s, Exception ex) { super(s, ex); } }
shun634501730/java_source_cn
src_en/java/rmi/server/SocketSecurityException.java
Java
apache-2.0
1,223
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.codeInsight.navigation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator; import com.intellij.codeInsight.generation.actions.PresentableCodeInsightActionHandler; import com.intellij.codeInsight.navigation.actions.GotoSuperAction; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.util.MethodCellRenderer; import com.intellij.ide.util.PsiNavigationSupport; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.impl.FindSuperElementsHelper; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; public class JavaGotoSuperHandler implements PresentableCodeInsightActionHandler { @Override public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID); int offset = editor.getCaretModel().getOffset(); PsiElement[] superElements = findSuperElements(file, offset); if (superElements.length == 0) return; if (superElements.length == 1) { PsiElement superElement = superElements[0].getNavigationElement(); final PsiFile containingFile = superElement.getContainingFile(); if (containingFile == null) return; final VirtualFile virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) return; Navigatable descriptor = PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, superElement.getTextOffset()); descriptor.navigate(true); } else if (superElements[0] instanceof PsiMethod) { boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature((PsiMethod[])superElements); PsiElementListNavigator.openTargets(editor, (PsiMethod[])superElements, CodeInsightBundle.message("goto.super.method.chooser.title"), CodeInsightBundle .message("goto.super.method.findUsages.title", ((PsiMethod)superElements[0]).getName()), new MethodCellRenderer(showMethodNames)); } else { NavigationUtil.getPsiElementPopup(superElements, CodeInsightBundle.message("goto.super.class.chooser.title")) .showInBestPositionFor(editor); } } @NotNull private PsiElement[] findSuperElements(@NotNull PsiFile file, int offset) { PsiElement element = getElement(file, offset); if (element == null) return PsiElement.EMPTY_ARRAY; final PsiElement psiElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class); if (psiElement instanceof PsiFunctionalExpression) { final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(psiElement); if (interfaceMethod != null) { return ArrayUtil.prepend(interfaceMethod, interfaceMethod.findSuperMethods(false)); } } final PsiNameIdentifierOwner parent = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class, PsiClass.class); if (parent == null) { return PsiElement.EMPTY_ARRAY; } return FindSuperElementsHelper.findSuperElements(parent); } protected PsiElement getElement(@NotNull PsiFile file, int offset) { return file.findElementAt(offset); } @Override public boolean startInWriteAction() { return false; } @Override public void update(@NotNull Editor editor, @NotNull PsiFile file, Presentation presentation) { final PsiElement element = getElement(file, editor.getCaretModel().getOffset()); final PsiElement containingElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class); if (containingElement instanceof PsiClass) { presentation.setText(ActionsBundle.actionText("GotoSuperClass")); presentation.setDescription(ActionsBundle.actionDescription("GotoSuperClass")); } else { presentation.setText(ActionsBundle.actionText("GotoSuperMethod")); presentation.setDescription(ActionsBundle.actionDescription("GotoSuperMethod")); } } }
goodwinnk/intellij-community
java/java-impl/src/com/intellij/codeInsight/navigation/JavaGotoSuperHandler.java
Java
apache-2.0
5,139
package brooklyn.location.jclouds.pool; import java.util.Map; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Processor; import org.jclouds.domain.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; public class MachinePoolPredicates { private static final Logger log = LoggerFactory.getLogger(MachinePoolPredicates.class); public static Predicate<NodeMetadata> except(final MachineSet removedItems) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return !removedItems.contains(input); } }; } public static Predicate<NodeMetadata> except(final Predicate<NodeMetadata> predicateToExclude) { return Predicates.not(predicateToExclude); } public static Predicate<NodeMetadata> matching(final ReusableMachineTemplate template) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return matches(template, input); } }; } public static Predicate<NodeMetadata> withTag(final String tag) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return input.getTags().contains(tag); } }; } public static Predicate<NodeMetadata> compose(final Predicate<NodeMetadata> ...predicates) { return Predicates.and(predicates); } /** True iff the node matches the criteria specified in this template. * <p> * NB: This only checks some of the most common fields, * plus a hashcode (in strict mode). * In strict mode you're practically guaranteed to match only machines created by this template. * (Add a tag(uid) and you _will_ be guaranteed, strict mode or not.) * <p> * Outside strict mode, some things (OS and hypervisor) can fall through the gaps. * But if that is a problem we can easily add them in. * <p> * (Caveat: If explicit Hardware, Image, and/or Template were specified in the template, * then the hash code probably will not detect it.) **/ public static boolean matches(ReusableMachineTemplate template, NodeMetadata m) { try { // tags and user metadata if (! m.getTags().containsAll( template.getTags(false) )) return false; if (! isSubMapOf(template.getUserMetadata(false), m.getUserMetadata())) return false; // common hardware parameters if (template.getMinRam()!=null && m.getHardware().getRam() < template.getMinRam()) return false; if (template.getMinCores()!=null) { double numCores = 0; for (Processor p: m.getHardware().getProcessors()) numCores += p.getCores(); if (numCores+0.001 < template.getMinCores()) return false; } if (template.getIs64bit()!=null) { if (m.getOperatingSystem().is64Bit() != template.getIs64bit()) return false; } if (template.getOsFamily()!=null) { if (m.getOperatingSystem() == null || !template.getOsFamily().equals(m.getOperatingSystem().getFamily())) return false; } if (template.getOsNameMatchesRegex()!=null) { if (m.getOperatingSystem() == null || m.getOperatingSystem().getName()==null || !m.getOperatingSystem().getName().matches(template.getOsNameMatchesRegex())) return false; } if (template.getLocationId()!=null) { if (!isLocationContainedIn(m.getLocation(), template.getLocationId())) return false; } // TODO other TemplateBuilder fields and TemplateOptions return true; } catch (Exception e) { log.warn("Error (rethrowing) trying to match "+m+" against "+template+": "+e, e); throw Throwables.propagate(e); } } private static boolean isLocationContainedIn(Location location, String locationId) { if (location==null) return false; if (locationId.equals(location.getId())) return true; return isLocationContainedIn(location.getParent(), locationId); } public static boolean isSubMapOf(Map<String, String> sub, Map<String, String> bigger) { for (Map.Entry<String, String> e: sub.entrySet()) { if (e.getValue()==null) { if (!bigger.containsKey(e.getKey())) return false; if (bigger.get(e.getKey())!=null) return false; } else { if (!e.getValue().equals(bigger.get(e.getKey()))) return false; } } return true; } }
bmwshop/brooklyn
locations/jclouds/src/main/java/brooklyn/location/jclouds/pool/MachinePoolPredicates.java
Java
apache-2.0
5,001
# encoding: utf-8 module RuboCop module Cop module Lint # This cop checks for uses of the deprecated class method usages. class DeprecatedClassMethods < Cop include AST::Sexp MSG = '`%s` is deprecated in favor of `%s`.' DEPRECATED_METHODS = [ [:File, :exists?, :exist?], [:Dir, :exists?, :exist?] ] def on_send(node) receiver, method_name, *_args = *node DEPRECATED_METHODS.each do |data| next unless class_nodes(data).include?(receiver) next unless method_name == data[1] add_offense(node, :selector, format(MSG, deprecated_method(data), replacement_method(data))) end end def autocorrect(node) lambda do |corrector| receiver, method_name, *_args = *node DEPRECATED_METHODS.each do |data| next unless class_nodes(data).include?(receiver) next unless method_name == data[1] corrector.replace(node.loc.selector, data[2].to_s) end end end private def class_nodes(data) [s(:const, nil, data[0]), s(:const, s(:cbase), data[0])] end def deprecated_method(data) format('%s.%s', data[0], data[1]) end def replacement_method(data) format('%s.%s', data[0], data[2]) end end end end end
cpbuckingham/cpbuckingham.github.io
vendor/bundle/gems/rubocop-0.32.1/lib/rubocop/cop/lint/deprecated_class_methods.rb
Ruby
apache-2.0
1,583
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.documentum.fc.client; /** Stub interface to allow the connector to build fully. */ public class DfIdentityException extends DfServiceException { }
kishorejangid/manifoldcf
connectors/documentum/build-stub/src/main/java/com/documentum/fc/client/DfIdentityException.java
Java
apache-2.0
954
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.portlets.statistics; import java.util.Collections; import java.util.List; import org.jasig.portal.events.aggr.portletlayout.PortletLayoutAggregation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.annotation.RenderMapping; import org.springframework.web.portlet.bind.annotation.ResourceMapping; import com.google.visualization.datasource.base.TypeMismatchException; import com.google.visualization.datasource.datatable.value.NumberValue; import com.google.visualization.datasource.datatable.value.Value; /** * @author Chris Waymire <cwaymire@unicon.net> */ @Controller @RequestMapping(value="VIEW") public class PortletMoveStatisticsController extends BasePortletLayoutStatisticsController<PortletMoveReportForm> { private static final String DATA_TABLE_RESOURCE_ID = "portletMoveData"; private static final String REPORT_NAME = "portletMove.totals"; @RenderMapping(value="MAXIMIZED", params="report=" + REPORT_NAME) public String getLoginView() throws TypeMismatchException { return super.getLoginView(); } @ResourceMapping(DATA_TABLE_RESOURCE_ID) public ModelAndView renderPortletAddAggregationReport(PortletMoveReportForm form) throws TypeMismatchException { return super.renderPortletAddAggregationReport(form); } @Override public String getReportName() { return REPORT_NAME; } @Override public String getReportDataResourceId() { return DATA_TABLE_RESOURCE_ID; } @Override protected List<Value> createRowValues(PortletLayoutAggregation aggr, PortletMoveReportForm form) { int count = aggr != null ? aggr.getMoveCount() : 0; return Collections.<Value>singletonList(new NumberValue(count)); } }
pspaude/uPortal
uportal-war/src/main/java/org/jasig/portal/portlets/statistics/PortletMoveStatisticsController.java
Java
apache-2.0
2,682
#!/usr/bin/env python # example checkbutton.py import pygtk pygtk.require('2.0') import gtk class CheckButton: # Our callback. # The data passed to this method is printed to stdout def callback(self, widget, data=None): print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()]) # This callback quits the program def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # Set the window title self.window.set_title("Check Button") # Set a handler for delete_event that immediately # exits GTK. self.window.connect("delete_event", self.delete_event) # Sets the border width of the window. self.window.set_border_width(20) # Create a vertical box vbox = gtk.VBox(True, 2) # Put the vbox in the main window self.window.add(vbox) # Create first button button = gtk.CheckButton("check button 1") # When the button is toggled, we call the "callback" method # with a pointer to "button" as its argument button.connect("toggled", self.callback, "check button 1") # Insert button 1 vbox.pack_start(button, True, True, 2) button.show() # Create second button button = gtk.CheckButton("check button 2") # When the button is toggled, we call the "callback" method # with a pointer to "button 2" as its argument button.connect("toggled", self.callback, "check button 2") # Insert button 2 vbox.pack_start(button, True, True, 2) button.show() # Create "Quit" button button = gtk.Button("Quit") # When the button is clicked, we call the mainquit function # and the program exits button.connect("clicked", lambda wid: gtk.main_quit()) # Insert the quit button vbox.pack_start(button, True, True, 2) button.show() vbox.show() self.window.show() def main(): gtk.main() return 0 if __name__ == "__main__": CheckButton() main()
spaceone/pyjs
pygtkweb/demos/checkbutton.py
Python
apache-2.0
2,231
/* * Copyright 2013 MovingBlocks * * 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 org.terasology.entitySystem.prefab.internal; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.terasology.assets.AssetType; import org.terasology.assets.ResourceUrn; import org.terasology.entitySystem.Component; import org.terasology.entitySystem.prefab.Prefab; import org.terasology.entitySystem.prefab.PrefabData; import java.util.List; import java.util.Map; /** * @author Immortius */ public class PojoPrefab extends Prefab { private Prefab parent; private Map<Class<? extends Component>, Component> componentMap; private List<Prefab> children = Lists.newArrayList(); private boolean persisted; private boolean alwaysRelevant = true; public PojoPrefab(ResourceUrn urn, AssetType<?, PrefabData> assetType, PrefabData data) { super(urn, assetType); reload(data); } @Override public Prefab getParent() { return parent; } @Override public List<Prefab> getChildren() { return ImmutableList.copyOf(children); } @Override public boolean isPersisted() { return persisted; } @Override public boolean isAlwaysRelevant() { return alwaysRelevant; } @Override public boolean exists() { return true; } @Override public boolean hasComponent(Class<? extends Component> component) { return componentMap.containsKey(component); } @Override public <T extends Component> T getComponent(Class<T> componentClass) { return componentClass.cast(componentMap.get(componentClass)); } @Override public Iterable<Component> iterateComponents() { return ImmutableList.copyOf(componentMap.values()); } @Override protected void doDispose() { } @Override protected void doReload(PrefabData data) { this.componentMap = ImmutableMap.copyOf(data.getComponents()); this.persisted = data.isPersisted(); this.alwaysRelevant = data.isAlwaysRelevant(); this.parent = data.getParent(); if (parent != null && parent instanceof PojoPrefab) { ((PojoPrefab) parent).children.add(this); } } }
immortius/Terasology
engine/src/main/java/org/terasology/entitySystem/prefab/internal/PojoPrefab.java
Java
apache-2.0
2,855
/*! * Module dependencies. */ var Command = require('./util/command'), phonegapbuild = require('./util/phonegap-build'), util = require('util'); /*! * Command setup. */ module.exports = { create: function(phonegap) { return new RemoteLogoutCommand(phonegap); } }; function RemoteLogoutCommand(phonegap) { return Command.apply(this, arguments); } util.inherits(RemoteLogoutCommand, Command); /** * Logout. * * Logout of PhoneGap/Build. * * Options: * * - `options` {Object} is unused and should be `{}`. * - [`callback`] {Function} is a callback function. * - `e` {Error} is null unless there is an error. * * Returns: * * {PhoneGap} for chaining. */ RemoteLogoutCommand.prototype.run = function(options, callback) { var self = this; // require options if (!options) throw new Error('requires options parameter'); // optional callback callback = callback || function() {}; // logout phonegapbuild.logout(options, function(e) { callback(e); }); return self.phonegap; };
mati191188/ecopueblo-mobile
node_modules/phonegap/lib/phonegap/remote.logout.js
JavaScript
apache-2.0
1,079
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.services.jmx; import org.jasig.cas.services.RegisteredService; import org.jasig.cas.services.RegisteredServiceImpl; import org.jasig.cas.services.ServicesManager; import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperationParameter; import org.springframework.util.Assert; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; /** * Abstract base class to support both the {@link org.jasig.cas.services.ServicesManager} and the * {@link org.jasig.cas.services.ReloadableServicesManager}. * * @author <a href="mailto:tobias.trelle@proximity.de">Tobias Trelle</a> * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.4.4 */ public abstract class AbstractServicesManagerMBean<T extends ServicesManager> { @NotNull private T servicesManager; protected AbstractServicesManagerMBean(final T servicesManager) { this.servicesManager = servicesManager; } protected final T getServicesManager() { return this.servicesManager; } @ManagedAttribute(description = "Retrieves the list of Registered Services in a slightly friendlier output.") public final List<String> getRegisteredServicesAsStrings() { final List<String> services = new ArrayList<String>(); for (final RegisteredService r : this.servicesManager.getAllServices()) { services.add(new StringBuilder().append("id: ").append(r.getId()) .append(" name: ").append(r.getName()) .append(" enabled: ").append(r.isEnabled()) .append(" ssoEnabled: ").append(r.isSsoEnabled()) .append(" serviceId: ").append(r.getServiceId()) .toString()); } return services; } @ManagedOperation(description = "Can remove a service based on its identifier.") @ManagedOperationParameter(name="id", description = "the identifier to remove") public final RegisteredService removeService(final long id) { return this.servicesManager.delete(id); } @ManagedOperation(description = "Disable a service by id.") @ManagedOperationParameter(name="id", description = "the identifier to disable") public final void disableService(final long id) { changeEnabledState(id, false); } @ManagedOperation(description = "Enable a service by its id.") @ManagedOperationParameter(name="id", description = "the identifier to enable.") public final void enableService(final long id) { changeEnabledState(id, true); } private void changeEnabledState(final long id, final boolean newState) { final RegisteredService r = this.servicesManager.findServiceBy(id); Assert.notNull(r, "invalid RegisteredService id"); // we screwed up our APIs in older versions of CAS, so we need to CAST this to do anything useful. ((RegisteredServiceImpl) r).setEnabled(newState); this.servicesManager.save(r); } }
briandwyer/cas-hudson
cas-server-core/src/main/java/org/jasig/cas/services/jmx/AbstractServicesManagerMBean.java
Java
apache-2.0
3,919
//go:build 386 || amd64p32 || arm || mipsle || mips64p32le // +build 386 amd64p32 arm mipsle mips64p32le package sys import ( "unsafe" ) // Pointer wraps an unsafe.Pointer to be 64bit to // conform to the syscall specification. type Pointer struct { ptr unsafe.Pointer pad uint32 }
opencontainers/runc
vendor/github.com/cilium/ebpf/internal/sys/ptr_32_le.go
GO
apache-2.0
288
cask 'multibit' do version '0.5.19' sha256 'f84aefa0b3762e36659ea3e71806f747db4198641d658d88c8772978b23f99dc' url "https://multibit.org/releases/multibit-classic/multibit-classic-#{version}/multibit-classic-macos-#{version}.dmg" gpg "#{url}.asc", :key_id => '23f7fb7b' name 'MultiBit' homepage 'https://multibit.org/' license :mit app 'MultiBit.app' end
jppelteret/homebrew-cask
Casks/multibit.rb
Ruby
bsd-2-clause
378
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-skipped.case // - src/dstr-binding/default/cls-decl-async-gen-meth-dflt.template /*--- description: Destructuring initializer is not evaluated when value is not `undefined` (class expression async generator method (default parameters)) esid: sec-class-definitions-runtime-semantics-evaluation features: [async-iteration] flags: [generated, async] info: | ClassDeclaration : class BindingIdentifier ClassTail 1. Let className be StringValue of BindingIdentifier. 2. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] Runtime Semantics: PropertyDefinitionEvaluation AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters, AsyncGeneratorBody, scope, strict). [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then [...] [...] ---*/ var initCount = 0; function counter() { initCount += 1; } var callCount = 0; class C { async *method({ w = counter(), x = counter(), y = counter(), z = counter() } = { w: null, x: 0, y: false, z: '' }) { assert.sameValue(w, null); assert.sameValue(x, 0); assert.sameValue(y, false); assert.sameValue(z, ''); assert.sameValue(initCount, 0); callCount = callCount + 1; } }; new C().method().next().then(() => { assert.sameValue(callCount, 1, 'invoked exactly once'); }).then($DONE, $DONE);
sebastienros/jint
Jint.Tests.Test262/test/language/statements/class/dstr-async-gen-meth-dflt-obj-ptrn-id-init-skipped.js
JavaScript
bsd-2-clause
2,395
"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:])
dbbhattacharya/kitsune
vendor/packages/pylint/gui.py
Python
bsd-3-clause
2,790
<?php $this->breadcrumbs = [ Yii::t('StoreModule.category', 'Categories') => ['index'], $model->name, ]; $this->pageTitle = Yii::t('StoreModule.category', 'Categories - view'); $this->menu = [ ['icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('StoreModule.category', 'Manage categories'), 'url' => ['/store/categoryBackend/index']], ['icon' => 'fa fa-fw fa-plus-square', 'label' => Yii::t('StoreModule.category', 'Create category'), 'url' => ['/store/categoryBackend/create']], ['label' => Yii::t('StoreModule.category', 'Category') . ' «' . mb_substr($model->name, 0, 32) . '»'], [ 'icon' => 'fa fa-fw fa-pencil', 'label' => Yii::t('StoreModule.category', 'Update category'), 'url' => [ '/store/categoryBackend/update', 'id' => $model->id ] ], [ 'icon' => 'fa fa-fw fa-eye', 'label' => Yii::t('StoreModule.category', 'View category'), 'url' => [ '/store/categoryBackend/view', 'id' => $model->id ] ], [ 'icon' => 'fa fa-fw fa-trash-o', 'label' => Yii::t('StoreModule.category', 'Delete category'), 'url' => '#', 'linkOptions' => [ 'submit' => ['/store/categoryBackend/delete', 'id' => $model->id], 'params' => [Yii::app()->getRequest()->csrfTokenName => Yii::app()->getRequest()->csrfToken], 'confirm' => Yii::t('StoreModule.category', 'Do you really want to remove category?'), 'csrf' => true, ] ], ]; ?> <div class="page-header"> <h1> <?php echo Yii::t('StoreModule.category', 'Viewing category'); ?><br/> <small>&laquo;<?php echo $model->name; ?>&raquo;</small> </h1> </div> <?php $this->widget( 'bootstrap.widgets.TbDetailView', [ 'data' => $model, 'attributes' => [ 'id', [ 'name' => 'parent_id', 'value' => $model->getParentName(), ], 'name', 'slug', [ 'name' => 'image', 'type' => 'raw', 'value' => $model->image ? CHtml::image($model->getImageUrl(200, 200), $model->name) : '---', ], [ 'name' => 'description', 'type' => 'raw' ], [ 'name' => 'short_description', 'type' => 'raw' ], [ 'name' => 'status', 'value' => $model->getStatus(), ], ], ] ); ?>
mettoff/archive
protected/modules/store/views/categoryBackend/view.php
PHP
bsd-3-clause
2,603
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const EventEmitter = require('../../vendor/emitter/EventEmitter'); const RCTDeviceEventEmitter = require('../RCTDeviceEventEmitter'); /** * Mock the NativeEventEmitter as a normal JS EventEmitter. */ class NativeEventEmitter extends EventEmitter { constructor() { super(RCTDeviceEventEmitter.sharedSubscriber); } } module.exports = NativeEventEmitter;
exponentjs/react-native
Libraries/EventEmitter/__mocks__/NativeEventEmitter.js
JavaScript
bsd-3-clause
592
# Generated by Django 2.2.6 on 2019-10-23 09:06 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import olympia.amo.models class Migration(migrations.Migration): dependencies = [ ('scanners', '0008_auto_20191021_1718'), ] operations = [ migrations.CreateModel( name='ScannerMatch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)), ('modified', models.DateTimeField(auto_now=True)), ('result', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerResult')), ('rule', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerRule')), ], options={ 'get_latest_by': 'created', 'abstract': False, 'base_manager_name': 'objects', }, bases=(olympia.amo.models.SearchMixin, olympia.amo.models.SaveUpdateMixin, models.Model), ), migrations.AddField( model_name='scannerresult', name='matched_rules', field=models.ManyToManyField(through='scanners.ScannerMatch', to='scanners.ScannerRule'), ), ]
bqbn/addons-server
src/olympia/scanners/migrations/0009_auto_20191023_0906.py
Python
bsd-3-clause
1,450
# # Copyright (c) 2012, NuoDB, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NuoDB, Inc. nor the names of its contributors may # be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NUODB, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'active_record/connection_adapters/nuodb_adapter'
scarey/nuodb-drivers
ruby/activerecord-nuodb-adapter/lib/activerecord-nuodb-adapter.rb
Ruby
bsd-3-clause
1,595
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/local/local_file_sync_context.h" #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h" #include "chrome/browser/sync_file_system/sync_file_metadata.h" #include "chrome/browser/sync_file_system/sync_status_code.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/mock_blob_url_request_context.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/file_system_operation_runner.h" #include "webkit/browser/fileapi/isolated_context.h" #include "webkit/common/blob/scoped_file.h" #define FPL FILE_PATH_LITERAL using content::BrowserThread; using fileapi::FileSystemContext; using fileapi::FileSystemURL; using fileapi::FileSystemURLSet; // This tests LocalFileSyncContext behavior in multi-thread / // multi-file-system-context environment. // Basic combined tests (single-thread / single-file-system-context) // that involve LocalFileSyncContext are also in // syncable_file_system_unittests.cc. namespace sync_file_system { namespace { const char kOrigin1[] = "http://example.com"; const char kOrigin2[] = "http://chromium.org"; } class LocalFileSyncContextTest : public testing::Test { protected: LocalFileSyncContextTest() : thread_bundle_( content::TestBrowserThreadBundle::REAL_FILE_THREAD | content::TestBrowserThreadBundle::REAL_IO_THREAD), status_(SYNC_FILE_ERROR_FAILED), file_error_(base::File::FILE_ERROR_FAILED), async_modify_finished_(false), has_inflight_prepare_for_sync_(false) {} virtual void SetUp() OVERRIDE { RegisterSyncableFileSystem(); ASSERT_TRUE(dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default())); ui_task_runner_ = base::MessageLoop::current()->message_loop_proxy(); io_task_runner_ = BrowserThread::GetMessageLoopProxyForThread( BrowserThread::IO); file_task_runner_ = BrowserThread::GetMessageLoopProxyForThread( BrowserThread::IO); } virtual void TearDown() OVERRIDE { RevokeSyncableFileSystem(); } void StartPrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { ASSERT_TRUE(changes != NULL); ASSERT_FALSE(has_inflight_prepare_for_sync_); status_ = SYNC_STATUS_UNKNOWN; has_inflight_prepare_for_sync_ = true; sync_context_->PrepareForSync( file_system_context, url, sync_mode, base::Bind(&LocalFileSyncContextTest::DidPrepareForSync, base::Unretained(this), metadata, changes, snapshot)); } SyncStatusCode PrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { StartPrepareForSync(file_system_context, url, sync_mode, metadata, changes, snapshot); base::MessageLoop::current()->Run(); return status_; } base::Closure GetPrepareForSyncClosure( FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, webkit_blob::ScopedFile* snapshot) { return base::Bind(&LocalFileSyncContextTest::StartPrepareForSync, base::Unretained(this), base::Unretained(file_system_context), url, sync_mode, metadata, changes, snapshot); } void DidPrepareForSync(SyncFileMetadata* metadata_out, FileChangeList* changes_out, webkit_blob::ScopedFile* snapshot_out, SyncStatusCode status, const LocalFileSyncInfo& sync_file_info, webkit_blob::ScopedFile snapshot) { ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); has_inflight_prepare_for_sync_ = false; status_ = status; *metadata_out = sync_file_info.metadata; *changes_out = sync_file_info.changes; if (snapshot_out) *snapshot_out = snapshot.Pass(); base::MessageLoop::current()->Quit(); } SyncStatusCode ApplyRemoteChange(FileSystemContext* file_system_context, const FileChange& change, const base::FilePath& local_path, const FileSystemURL& url, SyncFileType expected_file_type) { SCOPED_TRACE(testing::Message() << "ApplyChange for " << url.DebugString()); // First we should call PrepareForSync to disable writing. SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system_context, url, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(expected_file_type, metadata.file_type); status_ = SYNC_STATUS_UNKNOWN; sync_context_->ApplyRemoteChange( file_system_context, change, local_path, url, base::Bind(&LocalFileSyncContextTest::DidApplyRemoteChange, base::Unretained(this), make_scoped_refptr(file_system_context), url)); base::MessageLoop::current()->Run(); return status_; } void DidApplyRemoteChange(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status) { status_ = status; sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::MessageLoop::QuitClosure()); } void StartModifyFileOnIOThread(CannedSyncableFileSystem* file_system, const FileSystemURL& url) { ASSERT_TRUE(file_system != NULL); if (!io_task_runner_->RunsTasksOnCurrentThread()) { async_modify_finished_ = false; ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); io_task_runner_->PostTask( FROM_HERE, base::Bind(&LocalFileSyncContextTest::StartModifyFileOnIOThread, base::Unretained(this), file_system, url)); return; } ASSERT_TRUE(io_task_runner_->RunsTasksOnCurrentThread()); file_error_ = base::File::FILE_ERROR_FAILED; file_system->operation_runner()->Truncate( url, 1, base::Bind(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this))); } base::File::Error WaitUntilModifyFileIsDone() { while (!async_modify_finished_) base::MessageLoop::current()->RunUntilIdle(); return file_error_; } void DidModifyFile(base::File::Error error) { if (!ui_task_runner_->RunsTasksOnCurrentThread()) { ASSERT_TRUE(io_task_runner_->RunsTasksOnCurrentThread()); ui_task_runner_->PostTask( FROM_HERE, base::Bind(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this), error)); return; } ASSERT_TRUE(ui_task_runner_->RunsTasksOnCurrentThread()); file_error_ = error; async_modify_finished_ = true; } void SimulateFinishSync(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status, LocalFileSyncContext::SyncMode sync_mode) { if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { sync_context_->FinalizeSnapshotSync( file_system_context, url, status, base::Bind(&base::DoNothing)); } else { sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::Bind(&base::DoNothing)); } } void PrepareForSync_Basic(LocalFileSyncContext::SyncMode sync_mode, SyncStatusCode simulate_sync_finish_status) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); // We should see the same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); SimulateFinishSync(file_system.file_system_context(), kFile, simulate_sync_finish_status, sync_mode); file_system.GetChangesForURLInTracker(kFile, &changes); if (simulate_sync_finish_status == SYNC_STATUS_OK) { // The change's cleared. EXPECT_TRUE(changes.empty()); } else { EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); } sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } void PrepareForSync_WriteDuringSync( LocalFileSyncContext::SyncMode sync_mode) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; webkit_blob::ScopedFile snapshot; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, &snapshot)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT, !snapshot.path().empty()); // Tracker keeps same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); StartModifyFileOnIOThread(&file_system, kFile); if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { // Write should succeed. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); } else { base::MessageLoop::current()->RunUntilIdle(); EXPECT_FALSE(async_modify_finished_); } SimulateFinishSync(file_system.file_system_context(), kFile, SYNC_STATUS_OK, sync_mode); EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // Sync succeeded, but the other change that was made during or // after sync is recorded. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } base::ScopedTempDir dir_; scoped_ptr<leveldb::Env> in_memory_env_; // These need to remain until the very end. content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; scoped_refptr<LocalFileSyncContext> sync_context_; SyncStatusCode status_; base::File::Error file_error_; bool async_modify_finished_; bool has_inflight_prepare_for_sync_; }; TEST_F(LocalFileSyncContextTest, ConstructAndDestruct) { sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); sync_context_->ShutdownOnUIThread(); } TEST_F(LocalFileSyncContextTest, InitializeFileSystemContext) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system using |sync_context_|. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); // Make sure everything's set up for file_system to be able to handle // syncable file system operations. EXPECT_TRUE(file_system.backend()->sync_context() != NULL); EXPECT_TRUE(file_system.backend()->change_tracker() != NULL); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Calling MaybeInitialize for the same context multiple times must be ok. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Opens the file_system, perform some operation and see if the change tracker // correctly captures the change. EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL(file_system.URL("foo")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL)); FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL)); // Finishing the test. sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, MultipleFileSystemContexts) { CannedSyncableFileSystem file_system1(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); CannedSyncableFileSystem file_system2(GURL(kOrigin2), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system1.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); file_system2.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system1 and file_system2. EXPECT_EQ(SYNC_STATUS_OK, file_system1.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(SYNC_STATUS_OK, file_system2.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system1.OpenFileSystem()); EXPECT_EQ(base::File::FILE_OK, file_system2.OpenFileSystem()); const FileSystemURL kURL1(file_system1.URL("foo")); const FileSystemURL kURL2(file_system2.URL("bar")); // Creates a file in file_system1. EXPECT_EQ(base::File::FILE_OK, file_system1.CreateFile(kURL1)); // file_system1's tracker must have recorded the change. FileSystemURLSet urls; file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system1's tracker must have no change. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_TRUE(urls.empty()); // Creates a directory in file_system2. EXPECT_EQ(base::File::FILE_OK, file_system2.CreateDirectory(kURL2)); // file_system1's tracker must have the change for kURL1 as before. urls.clear(); file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL1)); // file_system2's tracker now must have the change for kURL2. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kURL2)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system1.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(0, metadata.size); changes.clear(); EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system2.file_system_context(), kURL2, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(1U, changes.size()); EXPECT_FALSE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_DIRECTORY, metadata.file_type); EXPECT_EQ(0, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system1.TearDown(); file_system2.TearDown(); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Exclusive) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_EXCLUSIVE); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Snapshot) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_SNAPSHOT); } // LocalFileSyncContextTest.PrepareSyncWhileWriting is flaky on android. // http://crbug.com/239793 // It is also flaky on the TSAN v2 bots, and hangs other bots. // http://crbug.com/305905. TEST_F(LocalFileSyncContextTest, DISABLED_PrepareSyncWhileWriting) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL1(file_system.URL("foo")); // Creates a file in file_system. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL1)); // Kick file write on IO thread. StartModifyFileOnIOThread(&file_system, kURL1); // Until the operation finishes PrepareForSync should return BUSY error. SyncFileMetadata metadata; metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_FILE_BUSY, PrepareForSync(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); // Register PrepareForSync method to be invoked when kURL1 becomes // syncable. (Actually this may be done after all operations are done // on IO thread in this test.) metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; changes.clear(); sync_context_->RegisterURLForWaitingSync( kURL1, GetPrepareForSyncClosure(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, NULL)); // Wait for the completion. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // The PrepareForSync must have been started; wait until DidPrepareForSync // is done. base::MessageLoop::current()->Run(); ASSERT_FALSE(has_inflight_prepare_for_sync_); // Now PrepareForSync should have run and returned OK. EXPECT_EQ(SYNC_STATUS_OK, status_); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(1, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64 initial_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(3U, urls.size()); ASSERT_TRUE(ContainsKey(urls, kFile)); ASSERT_TRUE(ContainsKey(urls, kDir)); ASSERT_TRUE(ContainsKey(urls, kChild)); for (FileSystemURLSet::iterator iter = urls.begin(); iter != urls.end(); ++iter) { file_system.ClearChangeForURLInTracker(*iter); } // At this point the usage must be greater than the initial usage. int64 new_usage = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); // Now let's apply remote deletion changes. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kFile, SYNC_FILE_TYPE_FILE)); // The implementation doesn't check file type for deletion, and it must be ok // even if we don't know if the deletion change was for a file or a directory. change = FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion_ForRoot) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64 initial_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // At this point the usage must be greater than the initial usage. int64 new_usage = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); const FileSystemURL kRoot(file_system.URL("")); // Now let's apply remote deletion changes for the root. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kRoot, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // All changes made for the previous creation must have been also reset. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = NULL; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile1(file_system.URL("file1")); const FileSystemURL kFile2(file_system.URL("file2")); const FileSystemURL kDir(file_system.URL("dir")); const char kTestFileData0[] = "0123456789"; const char kTestFileData1[] = "Lorem ipsum!"; const char kTestFileData2[] = "This is sample test data."; // Create kFile1 and populate it with kTestFileData0. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile1)); EXPECT_EQ(static_cast<int64>(arraysize(kTestFileData0) - 1), file_system.WriteString(kFile1, kTestFileData0)); // kFile2 and kDir are not there yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(ContainsKey(urls, kFile1)); file_system.ClearChangeForURLInTracker(*urls.begin()); // Prepare temporary files which represent the remote file data. const base::FilePath kFilePath1(temp_dir.path().Append(FPL("file1"))); const base::FilePath kFilePath2(temp_dir.path().Append(FPL("file2"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData1) - 1), base::WriteFile(kFilePath1, kTestFileData1, arraysize(kTestFileData1) - 1)); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData2) - 1), base::WriteFile(kFilePath2, kTestFileData2, arraysize(kTestFileData2) - 1)); // Record the usage. int64 usage = -1, new_usage = -1; int64 quota = -1; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&usage, &quota)); // Here in the local filesystem we have: // * kFile1 with kTestFileData0 // // In the remote side let's assume we have: // * kFile1 with kTestFileData1 // * kFile2 with kTestFileData2 // * kDir // // By calling ApplyChange's: // * kFile1 will be updated to have kTestFileData1 // * kFile2 will be created // * kDir will be created // Apply the remote change to kFile1 (which will update the file). FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kFile1, SYNC_FILE_TYPE_FILE)); // Check if the usage has been increased by (kTestFileData1 - kTestFileData0). const int updated_size = arraysize(kTestFileData1) - arraysize(kTestFileData0); EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(updated_size, new_usage - usage); // Apply remote changes to kFile2 and kDir (should create a file and // directory respectively). // They are non-existent yet so their expected file type (the last // parameter of ApplyRemoteChange) are // SYNC_FILE_TYPE_UNKNOWN. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath2, kFile2, SYNC_FILE_TYPE_UNKNOWN)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_UNKNOWN)); // Calling ApplyRemoteChange with different file type should be handled as // overwrite. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_DIRECTORY)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kDir)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_FILE)); // Creating a file/directory must have increased the usage more than // the size of kTestFileData2. new_usage = usage; EXPECT_EQ(quota::kQuotaStatusOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, static_cast<int64>(usage + arraysize(kTestFileData2) - 1)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure all three files/directory exist. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile1)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate_NoParent) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext( dir_.path(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const char kTestFileData[] = "Lorem ipsum!"; const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kFile(file_system.URL("dir/file")); // Either kDir or kFile not exist yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); // Prepare a temporary file which represents remote file data. const base::FilePath kFilePath(temp_dir.path().Append(FPL("file"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData) - 1), base::WriteFile(kFilePath, kTestFileData, arraysize(kTestFileData) - 1)); // Calling ApplyChange's with kFilePath should create // kFile along with kDir. FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath, kFile, SYNC_FILE_TYPE_UNKNOWN)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. FileSystemURLSet urls; urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure kDir and kFile are created by ApplyRemoteChange. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } } // namespace sync_file_system
ondra-novak/chromium.src
chrome/browser/sync_file_system/local/local_file_sync_context_unittest.cc
C++
bsd-3-clause
38,460
/*! * jQuery twitter bootstrap wizard plugin * Examples and documentation at: http://github.com/VinceG/twitter-bootstrap-wizard * version 1.0 * Requires jQuery v1.3.2 or later * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * Authors: Vadim Vincent Gabriel (http://vadimg.com) */ ; (function ($) { var bootstrapWizardCreate = function (element, options) { var element = $(element); var obj = this; // Merge options with defaults //var $settings = $.extend($.fn.bootstrapWizard.defaults, options || {}); var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options); var $activeTab = null; var $navigation = null; this.fixNavigationButtons = function () { // Get the current active tab if (!$activeTab.length) { // Select first one $navigation.find('a:first').tab('show'); $activeTab = $navigation.find('li:first'); } // See if we currently in the first then disable the previous and last buttons if (obj.firstIndex() >= obj.currentIndex()) { $('li.previous', element).addClass('disabled'); } else { $('li.previous', element).removeClass('disabled'); } if (obj.currentIndex() >= obj.navigationLength()) { $('li.next', element).addClass('disabled'); } else { $('li.next', element).removeClass('disabled'); } if ($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex()) === false) { return false; } }; this.next = function (e) { // If we clicked the last then dont activate this if (element.hasClass('last')) { return false; } if ($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex()) === false) { return false; } // Did we click the last button $index = obj.nextIndex(); if ($index > obj.navigationLength()) { } else { $navigation.find('li:eq(' + $index + ') a').tab('show'); } }; this.previous = function (e) { // If we clicked the first then dont activate this if (element.hasClass('first')) { return false; } if ($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex()) === false) { return false; } $index = obj.previousIndex(); if ($index < 0) { } else { $navigation.find('li:eq(' + $index + ') a').tab('show'); } }; this.first = function (e) { if ($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex()) === false) { return false; } // If the element is disabled then we won't do anything if (element.hasClass('disabled')) { return false; } $navigation.find('li:eq(0) a').tab('show'); }; this.last = function (e) { if ($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex()) === false) { return false; } // If the element is disabled then we won't do anything if (element.hasClass('disabled')) { return false; } $navigation.find('li:eq(' + obj.navigationLength() + ') a').tab('show'); }; this.currentIndex = function () { return $navigation.find('li').index($activeTab); }; this.firstIndex = function () { return 0; }; this.lastIndex = function () { return obj.navigationLength(); }; this.getIndex = function (elem) { return $navigation.find('li').index(elem); }; this.nextIndex = function () { return $navigation.find('li').index($activeTab) + 1; }; this.previousIndex = function () { return $navigation.find('li').index($activeTab) - 1; }; this.navigationLength = function () { return $navigation.find('li').length - 1; }; this.activeTab = function () { return $activeTab; }; this.nextTab = function () { return $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')').length ? $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')') : null; }; this.previousTab = function () { if (obj.currentIndex() <= 0) { return null; } return $navigation.find('li:eq(' + parseInt(obj.currentIndex() - 1) + ')'); }; $navigation = element.find('ul:first', element); $activeTab = $navigation.find('li.active', element); if (!$navigation.hasClass($settings.class)) { $navigation.addClass($settings.class); } // Load onShow if ($settings.onInit && typeof $settings.onInit === 'function') { $settings.onInit($activeTab, $navigation, 0); } // Next/Previous events $($settings.nextSelector, element).bind('click', obj.next); $($settings.previousSelector, element).bind('click', obj.previous); $($settings.lastSelector, element).bind('click', obj.last); $($settings.firstSelector, element).bind('click', obj.first); // Load onShow if ($settings.onShow && typeof $settings.onShow === 'function') { $settings.onShow($activeTab, $navigation, obj.nextIndex()); } // Work the next/previous buttons obj.fixNavigationButtons(); $('a[data-toggle="tab"]', element).on('click', function (e) { if ($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex()) === false) { return false; } }); $('a[data-toggle="tab"]', element).on('show', function (e) { $element = $(e.target).parent(); // If it's disabled then do not change if ($element.hasClass('disabled')) { return false; } $activeTab = $element; // activated tab obj.fixNavigationButtons(); }); }; $.fn.bootstrapWizard = function (options) { return this.each(function (index) { var element = $(this); // Return early if this element already has a plugin instance if (element.data('bootstrapWizard')) return; // pass options to plugin constructor var wizard = new bootstrapWizardCreate(element, options); // Store plugin object in this element's data element.data('bootstrapWizard', wizard); }); }; // expose options $.fn.bootstrapWizard.defaults = { 'class':'nav nav-pills', 'nextSelector':'.wizard li.next', 'previousSelector':'.wizard li.previous', 'firstSelector':'.wizard li.first', 'lastSelector':'.wizard li.last', 'onShow':null, 'onInit':null, 'onNext':null, 'onPrevious':null, 'onLast':null, 'onFirst':null, 'onTabClick':null, 'onTabShow':null }; })(jQuery);
flesch91/uaweb-work.github.com
web/booster-install/assets/js/jquery.bootstrap.wizard.js
JavaScript
bsd-3-clause
7,891