How to use defaults method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

jquery-autotab.js

Source:jquery-autotab.js Github

copy

Full Screen

1/**2 * Autotab - jQuery plugin 1.8.13 * https://github.com/Mathachew/jquery-autotab4 *5 * Copyright (c) 2008, 2014 Matthew Miller6 *7 * Licensed under the MIT licensing:8 * http://www.opensource.org/licenses/mit-license.php9 */10(function($) {11 var platform = navigator.platform,12 settings = {13 tabPause: 800,14 focusChange: null,15 iOS: (platform === 'iPad' || platform === 'iPhone' || platform === 'iPod'),16 firefox: (typeof InstallTrigger !== 'undefined')17 };18 var setSettings = function(e, settings) {19 if (settings === null || typeof settings === 'undefined') {20 return;21 }22 for (var key in settings) {23 $(e).data('autotab-' + key, settings[key]);24 }25 };26 var getSettings = function(e) {27 var settings = {28 format: 'all',29 loaded: false,30 disabled: false,31 pattern: null,32 uppercase: false,33 lowercase: false,34 nospace: false,35 maxlength: 2147483647,36 target: null,37 previous: null,38 trigger: null,39 originalValue: '',40 changed: false,41 editable: (e.type == 'text' || e.type == 'password' || e.type == 'textarea'),42 tabOnSelect: false43 };44 // If $.autotab.selectFilterByClas is true and the format not specified, automatically select an element's format based on a matching class name.45 // The first matched element becomes the selected format for the filter.46 if ($.autotab.selectFilterByClass === true && typeof $(e).data('autotab-format') === 'undefined') {47 var classes = ['all', 'text', 'alpha', 'number', 'numeric', 'alphanumeric', 'hex', 'hexadecimal', 'custom'];48 for (var key in classes) {49 if ($(e).hasClass(classes[key])) {50 settings.format = classes[key];51 break;52 }53 }54 }55 for (var key in settings) {56 if (typeof $(e).data('autotab-' + key) !== 'undefined') {57 settings[key] = $(e).data('autotab-' + key);58 }59 }60 // Save settings on first run61 if (!settings.loaded) {62 if (settings.trigger !== null && typeof settings.trigger === 'string') {63 settings.trigger = settings.trigger.toString();64 }65 setSettings(e, settings);66 }67 return settings;68 };69 var queryObject = function(e) {70 return (typeof e !== 'undefined' && (typeof e === 'string' || !(e instanceof jQuery)));71 };72 $.autotab = function(options) {73 if (typeof options !== 'object') {74 options = {};75 }76 $(':input').autotab(options);77 };78 $.autotab.selectFilterByClass = false;79 $.autotab.next = function() {80 var e = $(document.activeElement);81 if (e.length) {82 e.trigger('autotab-next');83 }84 };85 $.autotab.previous = function() {86 var e = $(document.activeElement);87 if (e.length) {88 e.trigger('autotab-previous');89 }90 };91 $.autotab.remove = function(e) {92 queryObject(e) ? $(e).autotab('remove') : $(':input').autotab('remove');93 };94 $.autotab.restore = function(e) {95 queryObject(e) ? $(e).autotab('restore') : $(':input').autotab('restore');96 };97 $.autotab.refresh = function(e) {98 queryObject(e) ? $(e).autotab('refresh') : $(':input').autotab('refresh');99 };100 $.fn.autotab = function(method, options) {101 if (!this.length) {102 return this;103 }104 // Remove hidden fields since tabbing backwards is supported on different form elements105 var filtered = $.grep(this, function(e, i) {106 return e.type != 'hidden';107 });108 // Apply filter options109 if (method == 'filter') {110 if (typeof options === 'string' || typeof options === 'function') {111 options = {112 format: options113 };114 }115 for (var i = 0, length = filtered.length; i < length; i++) {116 var defaults = getSettings(filtered[i]),117 newOptions = options;118 // Retain the established target/previous values as this area is for filtering only119 newOptions.target = defaults.target;120 newOptions.previous = defaults.previous;121 $.extend(defaults, newOptions);122 if (!defaults.loaded) {123 defaults.disabled = true;124 autotabBind(filtered[i], newOptions);125 } else {126 setSettings(filtered[i], defaults);127 }128 }129 }130 // Disable auto tab and filtering131 else if (method == 'remove' || method == 'destroy' || method == 'disable') {132 for (var i = 0, length = filtered.length; i < length; i++) {133 var defaults = getSettings(filtered[i]);134 defaults.disabled = true;135 setSettings(filtered[i], defaults);136 }137 }138 // Re-enable auto tab and filtering139 else if (method == 'restore' || method == 'enable') {140 for (var i = 0, length = filtered.length; i < length; i++) {141 var defaults = getSettings(filtered[i]);142 defaults.disabled = false;143 setSettings(filtered[i], defaults);144 }145 }146 // Refresh target/previous elements147 else if (method == 'refresh') {148 for (var i = 0, length = filtered.length; i < length; i++) {149 var defaults = getSettings(filtered[i]),150 n = i + 1,151 p = i - 1,152 selectTarget = function() {153 if (i > 0 && n < length) {154 defaults.target = filtered[n];155 } else if (i > 0) {156 defaults.target = null;157 } else {158 defaults.target = filtered[n];159 }160 },161 selectPrevious = function() {162 if (i > 0 && n < length) {163 defaults.previous = filtered[p];164 } else if (i > 0) {165 defaults.previous = filtered[p];166 } else {167 defaults.previous = null;168 }169 };170 // Nothing was specified for the target element, so automatically set it171 if (defaults.target === null || defaults.target.selector === '') {172 selectTarget();173 } else if (typeof defaults.target === 'string' || defaults.target.selector) {174 defaults.target = $(typeof defaults.target === 'string' ? defaults.target : defaults.target.selector);175 if (defaults.target.length === 0) {176 selectTarget();177 }178 }179 // Nothing was specified for the previous element, so automatically set it180 if (defaults.previous === null || defaults.previous.selector === '') {181 selectPrevious();182 } else if (typeof defaults.previous === 'string' || defaults.previous.selector) {183 defaults.previous = $(typeof defaults.previous === 'string' ? defaults.previous : defaults.previous.selector);184 if (defaults.previous.length === 0) {185 selectPrevious();186 }187 }188 if (!defaults.loaded) {189 autotabBind(filtered[i], defaults);190 } else {191 if (queryObject(defaults.target)) {192 defaults.target = $(defaults.target);193 }194 if (queryObject(defaults.previous)) {195 defaults.previous = $(defaults.previous);196 }197 setSettings(filtered[i], defaults);198 }199 }200 } else {201 if (method === null || typeof method === 'undefined') {202 options = {};203 } else if (typeof method === 'string' || typeof method === 'function') {204 options = {205 format: method206 };207 } else if (typeof method === 'object') {208 options = method;209 }210 // Bind key events to element(s) passed211 if (filtered.length > 1) {212 for (var i = 0, length = filtered.length; i < length; i++) {213 var n = i + 1,214 p = i - 1,215 newOptions = options;216 if (i > 0 && n < length) {217 newOptions.target = filtered[n];218 newOptions.previous = filtered[p];219 } else if (i > 0) {220 newOptions.target = null;221 newOptions.previous = filtered[p];222 } else {223 newOptions.target = filtered[n];224 newOptions.previous = null;225 }226 autotabBind(filtered[i], newOptions);227 }228 } else {229 autotabBind(filtered[0], options);230 }231 }232 return this;233 };234 var filterValue = function(e, value, defaults) {235 if (typeof defaults.format === 'function') {236 return defaults.format(value, e);237 }238 var pattern = null;239 switch (defaults.format) {240 case 'text':241 pattern = new RegExp('[0-9]+', 'g');242 break;243 case 'alpha':244 pattern = new RegExp('[^a-zA-Z]+', 'g');245 break;246 case 'number':247 case 'numeric':248 pattern = new RegExp('[^0-9]+', 'g');249 break;250 case 'alphanumeric':251 pattern = new RegExp('[^0-9a-zA-Z]+', 'g');252 break;253 case 'hex':254 case 'hexadecimal':255 pattern = new RegExp('[^0-9A-Fa-f]+', 'g');256 break;257 case 'custom':258 pattern = new RegExp(defaults.pattern, 'g');259 break;260 case 'all':261 default:262 break;263 }264 if (pattern !== null) {265 value = value.replace(pattern, '');266 }267 if (defaults.nospace) {268 pattern = new RegExp('[ ]+', 'g');269 value = value.replace(pattern, '');270 }271 if (defaults.uppercase) {272 value = value.toUpperCase();273 }274 if (defaults.lowercase) {275 value = value.toLowerCase();276 }277 return value;278 };279 var autotabBind = function(element, options) {280 var defaults = getSettings(element);281 if (defaults.disabled) {282 defaults.disabled = false;283 defaults.target = null;284 defaults.previous = null;285 }286 $.extend(defaults, options);287 // Sets targets to element based on the name or ID passed if they are not currently objects288 if (queryObject(defaults.target)) {289 defaults.target = $(defaults.target);290 }291 if (queryObject(defaults.previous)) {292 defaults.previous = $(defaults.previous);293 }294 var oldMaxlength = element.maxLength;295 if (typeof element.maxLength === 'undefined' && element.type == 'textarea') {296 oldMaxlength = element.maxLength = element.getAttribute('maxlength');297 }298 // defaults.maxlength has not changed and maxlength was specified299 if (defaults.maxlength == 2147483647 && oldMaxlength != 2147483647 && oldMaxlength != -1) {300 defaults.maxlength = oldMaxlength;301 }302 // defaults.maxlength overrides maxlength303 else if (defaults.maxlength > 0) {304 element.maxLength = defaults.maxlength;305 }306 // defaults.maxlength and maxlength have not been specified307 // A target cannot be used since there is no defined maxlength308 else {309 defaults.target = null;310 }311 if (!defaults.loaded) {312 defaults.loaded = true;313 setSettings(element, defaults);314 } else {315 setSettings(element, defaults);316 return;317 }318 // Add a change event to select lists only so that we can auto tab when a value is selected319 if (element.type == 'select-one') {320 $(element).on('change', function(e) {321 var defaults = getSettings(this);322 if (defaults.tabOnSelect) {323 $(this).trigger('autotab-next');324 }325 });326 }327 // The 1ms timeouts allow for keypress events to complete in case a328 // custom function or exterior method calls for a manual auto tab329 $(element).on('autotab-next', function(event, defaults) {330 var self = this;331 setTimeout(function() {332 if (!defaults) {333 defaults = getSettings(self);334 }335 var target = defaults.target;336 if (!defaults.disabled && target.length) {337 // Using focus on iOS devices is a pain, so use the browser's next/previous buttons to proceed338 if (!settings.iOS) {339 // Field is disabled/readonly, so tab to next element340 if (target.prop('disabled') || target.prop('readonly')) {341 target.trigger('autotab-next');342 } else {343 target.focus().select();344 }345 settings.focusChange = new Date();346 }347 }348 }, 1);349 }).on('autotab-previous', function(event, defaults) {350 var self = this;351 setTimeout(function() {352 if (!defaults) {353 defaults = getSettings(self);354 }355 var previous = defaults.previous;356 if (!defaults.disabled && previous.length) {357 var value = previous.val();358 // Field is disabled/readonly, so tab to previous element359 if (previous.prop('disabled') || previous.prop('readonly')) {360 previous.trigger('autotab-previous');361 } else if (value.length && previous.data('autotab-editable')) {362 previous.focus().val(value.substring(0, value.length - 1));363 setSettings(previous, {364 changed: true365 });366 } else {367 previous.focus();368 }369 settings.focusChange = null;370 }371 }, 1);372 }).on('focus', function() {373 setSettings(this, {374 originalValue: this.value375 });376 }).on('blur', function() {377 var defaults = getSettings(this);378 if (defaults.changed && this.value != defaults.originalValue) {379 setSettings(this, {380 changed: false381 });382 $(this).change();383 }384 }).on('keydown', function(e) {385 var defaults = getSettings(this);386 if (!defaults || defaults.disabled) {387 return true;388 }389 var keyCode = e.which || e.charCode;390 // Go to the previous element when backspace391 // is pressed in an empty input field392 if (keyCode == 8) {393 // Prevent the browser from of navigating to the previous page394 if (this.type === 'select-one' || this.type === 'checkbox' || this.type === 'radio' || this.type === 'button' || this.type === 'submit' || this.type === 'range') {395 $(this).trigger('autotab-previous', defaults);396 return false;397 }398 if (this.value.length === 0) {399 $(this).trigger('autotab-previous', defaults);400 return;401 }402 setSettings(this, {403 changed: (this.value !== defaults.originalValue)404 });405 } else if (keyCode == 9 && settings.focusChange !== null) {406 // Tab backwards407 if (e.shiftKey) {408 settings.focusChange = null;409 return;410 }411 if ((new Date().getTime() - settings.focusChange.getTime()) < settings.tabPause) {412 settings.focusChange = null;413 return false;414 }415 }416 }).on('keypress', function(e) {417 var defaults = getSettings(this),418 keyCode = e.which || e.keyCode;419 // e.charCode == 0 indicates a special key has been pressed, which only Firefox triggers420 if (!defaults || defaults.disabled || (settings.firefox && e.charCode === 0) || e.ctrlKey || e.altKey || keyCode == 13 || (this.type != 'text' && this.type != 'password' && this.type != 'textarea') || this.disabled) {421 return true;422 }423 var keyChar = String.fromCharCode(keyCode);424 // Prevents auto tabbing when defaults.trigger is pressed425 if (defaults.trigger !== null && defaults.trigger.indexOf(keyChar) >= 0) {426 if (settings.focusChange !== null && (new Date().getTime() - settings.focusChange.getTime()) < settings.tabPause) {427 settings.focusChange = null;428 } else {429 $(this).trigger('autotab-next', defaults);430 }431 return false;432 }433 settings.focusChange = null;434 var hasValue = document.selection && document.selection.createRange ? true : (e.charCode > 0);435 keyChar = filterValue(this, keyChar, defaults);436 if (hasValue && (keyChar === null || keyChar === '')) {437 return false;438 }439 // Many, many thanks to Tim Down for this solution: http://stackoverflow.com/a/3923320/94656440 if (hasValue && (this.value.length <= this.maxLength)) {441 var start, end,442 selectionType = 0;443 if (typeof this.selectionStart === 'number' && typeof this.selectionEnd === 'number') {444 // Non-IE browsers and IE 9445 start = this.selectionStart;446 end = this.selectionEnd;447 selectionType = 1;448 } else if (document.selection && document.selection.createRange) {449 // For IE up to version 8450 var selectionRange = document.selection.createRange(),451 textInputRange = this.createTextRange(),452 precedingRange = this.createTextRange(),453 bookmark = selectionRange.getBookmark();454 textInputRange.moveToBookmark(bookmark);455 precedingRange.setEndPoint("EndToStart", textInputRange);456 start = precedingRange.text.length;457 end = start + selectionRange.text.length;458 selectionType = 2;459 }460 // Text is fully selected, so it needs to be replaced461 if (start === 0 && end == this.value.length) {462 this.value = keyChar;463 setSettings(this, {464 changed: (this.value != defaults.originalValue)465 });466 } else {467 if (this.value.length == this.maxLength && start === end) {468 $(this).trigger('autotab-next', defaults);469 return false;470 }471 this.value = this.value.slice(0, start) + keyChar + this.value.slice(end);472 setSettings(this, {473 changed: (this.value != defaults.originalValue)474 });475 }476 // Prevents the cursor position from being set to the end of the text box477 // This is called even if the text is fully selected and replaced due to an unexpected behavior in IE6 and up (#32)478 if (this.value.length != defaults.maxlength) {479 start++;480 if (selectionType == 1) {481 this.selectionStart = this.selectionEnd = start;482 } else if (selectionType == 2) {483 var range = this.createTextRange();484 range.collapse(true);485 range.moveEnd('character', start);486 range.moveStart('character', start);487 range.select();488 }489 }490 }491 if (this.value.length == defaults.maxlength) {492 $(this).trigger('autotab-next', defaults);493 }494 return false;495 }).on('paste', function(e) {496 var defaults = getSettings(this);497 if (!defaults) {498 return true;499 }500 this.maxLength = 2147483647;501 (function(e, originDefaults) {502 setTimeout(function() {503 var lastIndex = -1,504 hiddenInput = document.createElement('input');505 hiddenInput.type = 'hidden';506 hiddenInput.value = e.value.toLowerCase();507 hiddenInput.originalValue = e.value;508 e.maxLength = originDefaults.maxlength;509 e.value = filterValue(e, e.value, originDefaults).substr(0, originDefaults.maxlength);510 var handlePaste = function(e, previousValue) {511 if (!e) {512 return;513 }514 var defaults = getSettings(e);515 if ($(e).prop('disabled') || $(e).prop('readonly')) {516 $(e).trigger('autotab-next');517 if (!settings.iOS) {518 handlePaste(defaults.target[0], previousValue);519 }520 return;521 }522 for (var i = 0, count = previousValue.length; i < count; i++) {523 lastIndex = hiddenInput.value.indexOf(previousValue.charAt(i).toLowerCase(), lastIndex) + 1;524 }525 var trimmedValue = hiddenInput.originalValue.substr(lastIndex),526 filteredValue = filterValue(e, trimmedValue, defaults).substr(0, defaults.maxlength);527 if (!filteredValue) {528 e.value = '';529 return;530 }531 e.value = filteredValue;532 if (filteredValue.length == defaults.maxlength) {533 $(e).trigger('autotab-next', defaults);534 if (!settings.iOS) {535 handlePaste(defaults.target[0], filteredValue);536 }537 }538 };539 if (e.value.length == originDefaults.maxlength) {540 $(e).trigger('autotab-next', defaults);541 if (!settings.iOS) {542 handlePaste(originDefaults.target[0], e.value.toLowerCase());543 }544 }545 }, 1);546 })(this, defaults);547 });548 };549 // Deprecated, here for backwards compatibility550 $.fn.autotab_magic = function(focus) {551 return $(this).autotab();552 };553 $.fn.autotab_filter = function(options) {554 var defaults = {};555 if (typeof options === 'string' || typeof options === 'function') {556 defaults.format = options;557 } else {558 $.extend(defaults, options);559 }560 return $(this).autotab('filter', defaults);561 };...

Full Screen

Full Screen

csv_dataset_test.py

Source:csv_dataset_test.py Github

copy

Full Screen

1# Copyright 2018 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for `tf.data.experimental.CsvDataset`."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import gzip20import os21import zlib22from absl.testing import parameterized23from tensorflow.python.data.experimental.ops import error_ops24from tensorflow.python.data.experimental.ops import readers25from tensorflow.python.data.kernel_tests import test_base26from tensorflow.python.data.ops import readers as core_readers27from tensorflow.python.eager import context28from tensorflow.python.framework import combinations29from tensorflow.python.framework import constant_op30from tensorflow.python.framework import dtypes31from tensorflow.python.framework import errors32from tensorflow.python.ops import parsing_ops33from tensorflow.python.platform import test34class CsvDatasetTest(test_base.DatasetTestBase, parameterized.TestCase):35 def _setup_files(self, inputs, linebreak='\n', compression_type=None):36 filenames = []37 for i, ip in enumerate(inputs):38 fn = os.path.join(self.get_temp_dir(), 'temp_%d.csv' % i)39 contents = linebreak.join(ip).encode('utf-8')40 if compression_type is None:41 with open(fn, 'wb') as f:42 f.write(contents)43 elif compression_type == 'GZIP':44 with gzip.GzipFile(fn, 'wb') as f:45 f.write(contents)46 elif compression_type == 'ZLIB':47 contents = zlib.compress(contents)48 with open(fn, 'wb') as f:49 f.write(contents)50 else:51 raise ValueError('Unsupported compression_type', compression_type)52 filenames.append(fn)53 return filenames54 def _make_test_datasets(self, inputs, **kwargs):55 # Test by comparing its output to what we could get with map->decode_csv56 filenames = self._setup_files(inputs)57 dataset_expected = core_readers.TextLineDataset(filenames)58 dataset_expected = dataset_expected.map(59 lambda l: parsing_ops.decode_csv(l, **kwargs))60 dataset_actual = readers.CsvDataset(filenames, **kwargs)61 return (dataset_actual, dataset_expected)62 def _test_by_comparison(self, inputs, **kwargs):63 """Checks that CsvDataset is equiv to TextLineDataset->map(decode_csv)."""64 dataset_actual, dataset_expected = self._make_test_datasets(65 inputs, **kwargs)66 self.assertDatasetsEqual(dataset_actual, dataset_expected)67 def _verify_output_or_err(self,68 dataset,69 expected_output=None,70 expected_err_re=None):71 if expected_err_re is None:72 # Verify that output is expected, without errors73 nxt = self.getNext(dataset)74 expected_output = [[75 v.encode('utf-8') if isinstance(v, str) else v for v in op76 ] for op in expected_output]77 for value in expected_output:78 op = self.evaluate(nxt())79 self.assertAllEqual(op, value)80 with self.assertRaises(errors.OutOfRangeError):81 self.evaluate(nxt())82 else:83 nxt = self.getNext(dataset)84 while True:85 try:86 self.evaluate(nxt())87 except errors.OutOfRangeError:88 break89 def _test_dataset(90 self,91 inputs,92 expected_output=None,93 expected_err_re=None,94 linebreak='\n',95 compression_type=None, # Used for both setup and parsing96 **kwargs):97 """Checks that elements produced by CsvDataset match expected output."""98 # Convert str type because py3 tf strings are bytestrings99 filenames = self._setup_files(inputs, linebreak, compression_type)100 kwargs['compression_type'] = compression_type101 if expected_err_re is not None:102 # Verify that OpError is produced as expected103 with self.assertRaisesOpError(expected_err_re):104 dataset = readers.CsvDataset(filenames, **kwargs)105 self._verify_output_or_err(dataset, expected_output, expected_err_re)106 else:107 dataset = readers.CsvDataset(filenames, **kwargs)108 self._verify_output_or_err(dataset, expected_output, expected_err_re)109 @combinations.generate(test_base.default_test_combinations())110 def testCsvDataset_requiredFields(self):111 record_defaults = [[]] * 4112 inputs = [['1,2,3,4']]113 self._test_by_comparison(inputs, record_defaults=record_defaults)114 @combinations.generate(test_base.default_test_combinations())115 def testCsvDataset_int(self):116 record_defaults = [[0]] * 4117 inputs = [['1,2,3,4', '5,6,7,8']]118 self._test_by_comparison(inputs, record_defaults=record_defaults)119 @combinations.generate(test_base.default_test_combinations())120 def testCsvDataset_float(self):121 record_defaults = [[0.0]] * 4122 inputs = [['1.0,2.1,3.2,4.3', '5.4,6.5,7.6,8.7']]123 self._test_by_comparison(inputs, record_defaults=record_defaults)124 @combinations.generate(test_base.default_test_combinations())125 def testCsvDataset_string(self):126 record_defaults = [['']] * 4127 inputs = [['1.0,2.1,hello,4.3', '5.4,6.5,goodbye,8.7']]128 self._test_by_comparison(inputs, record_defaults=record_defaults)129 @combinations.generate(test_base.default_test_combinations())130 def testCsvDataset_withEmptyFields(self):131 record_defaults = [[0]] * 4132 inputs = [[',,,', '1,1,1,', ',2,2,2']]133 self._test_dataset(134 inputs, [[0, 0, 0, 0], [1, 1, 1, 0], [0, 2, 2, 2]],135 record_defaults=record_defaults)136 @combinations.generate(test_base.default_test_combinations())137 def testCsvDataset_errWithUnquotedQuotes(self):138 record_defaults = [['']] * 3139 inputs = [['1,2"3,4']]140 self._test_dataset(141 inputs,142 expected_err_re='Unquoted fields cannot have quotes inside',143 record_defaults=record_defaults)144 @combinations.generate(test_base.default_test_combinations())145 def testCsvDataset_errWithUnescapedQuotes(self):146 record_defaults = [['']] * 3147 inputs = [['"a"b","c","d"']]148 self._test_dataset(149 inputs,150 expected_err_re=151 'Quote inside a string has to be escaped by another quote',152 record_defaults=record_defaults)153 @combinations.generate(test_base.default_test_combinations())154 def testCsvDataset_ignoreErrWithUnescapedQuotes(self):155 record_defaults = [['']] * 3156 inputs = [['1,"2"3",4', '1,"2"3",4",5,5', 'a,b,"c"d"', 'e,f,g']]157 filenames = self._setup_files(inputs)158 dataset = readers.CsvDataset(filenames, record_defaults=record_defaults)159 dataset = dataset.apply(error_ops.ignore_errors())160 self._verify_output_or_err(dataset, [['e', 'f', 'g']])161 @combinations.generate(test_base.default_test_combinations())162 def testCsvDataset_ignoreErrWithUnquotedQuotes(self):163 record_defaults = [['']] * 3164 inputs = [['1,2"3,4', 'a,b,c"d', '9,8"7,6,5', 'e,f,g']]165 filenames = self._setup_files(inputs)166 dataset = readers.CsvDataset(filenames, record_defaults=record_defaults)167 dataset = dataset.apply(error_ops.ignore_errors())168 self._verify_output_or_err(dataset, [['e', 'f', 'g']])169 @combinations.generate(test_base.default_test_combinations())170 def testCsvDataset_withNoQuoteDelimAndUnquotedQuotes(self):171 record_defaults = [['']] * 3172 inputs = [['1,2"3,4']]173 self._test_by_comparison(174 inputs, record_defaults=record_defaults, use_quote_delim=False)175 @combinations.generate(test_base.default_test_combinations())176 def testCsvDataset_mixedTypes(self):177 record_defaults = [178 constant_op.constant([], dtype=dtypes.int32),179 constant_op.constant([], dtype=dtypes.float32),180 constant_op.constant([], dtype=dtypes.string),181 constant_op.constant([], dtype=dtypes.float64)182 ]183 inputs = [['1,2.1,3.2,4.3', '5,6.5,7.6,8.7']]184 self._test_by_comparison(inputs, record_defaults=record_defaults)185 @combinations.generate(test_base.default_test_combinations())186 def testCsvDataset_withUseQuoteDelimFalse(self):187 record_defaults = [['']] * 4188 inputs = [['1,2,"3,4"', '"5,6",7,8']]189 self._test_by_comparison(190 inputs, record_defaults=record_defaults, use_quote_delim=False)191 @combinations.generate(test_base.default_test_combinations())192 def testCsvDataset_withFieldDelim(self):193 record_defaults = [[0]] * 4194 inputs = [['1:2:3:4', '5:6:7:8']]195 self._test_by_comparison(196 inputs, record_defaults=record_defaults, field_delim=':')197 @combinations.generate(test_base.default_test_combinations())198 def testCsvDataset_withNaValue(self):199 record_defaults = [[0]] * 4200 inputs = [['1,NA,3,4', 'NA,6,7,8']]201 self._test_by_comparison(202 inputs, record_defaults=record_defaults, na_value='NA')203 @combinations.generate(test_base.default_test_combinations())204 def testCsvDataset_withSelectCols(self):205 record_defaults = [['']] * 2206 inputs = [['1,2,3,4', '"5","6","7","8"']]207 self._test_by_comparison(208 inputs, record_defaults=record_defaults, select_cols=[1, 2])209 @combinations.generate(test_base.default_test_combinations())210 def testCsvDataset_withSelectColsTooHigh(self):211 record_defaults = [[0]] * 2212 inputs = [['1,2,3,4', '5,6,7,8']]213 self._test_dataset(214 inputs,215 expected_err_re='Expect 2 fields but have 1 in record',216 record_defaults=record_defaults,217 select_cols=[3, 4])218 @combinations.generate(test_base.default_test_combinations())219 def testCsvDataset_withOneCol(self):220 record_defaults = [['NA']]221 inputs = [['0', '', '2']]222 self._test_dataset(223 inputs, [['0'], ['NA'], ['2']], record_defaults=record_defaults)224 @combinations.generate(test_base.default_test_combinations())225 def testCsvDataset_withMultipleFiles(self):226 record_defaults = [[0]] * 4227 inputs = [['1,2,3,4', '5,6,7,8'], ['5,6,7,8']]228 self._test_by_comparison(inputs, record_defaults=record_defaults)229 @combinations.generate(test_base.default_test_combinations())230 def testCsvDataset_withLeadingAndTrailingSpaces(self):231 record_defaults = [[0.0]] * 4232 inputs = [['0, 1, 2, 3']]233 expected = [[0.0, 1.0, 2.0, 3.0]]234 self._test_dataset(inputs, expected, record_defaults=record_defaults)235 @combinations.generate(test_base.default_test_combinations())236 def testCsvDataset_errorWithMissingDefault(self):237 record_defaults = [[]] * 2238 inputs = [['0,']]239 self._test_dataset(240 inputs,241 expected_err_re='Field 1 is required but missing in record!',242 record_defaults=record_defaults)243 @combinations.generate(test_base.default_test_combinations())244 def testCsvDataset_errorWithFewerDefaultsThanFields(self):245 record_defaults = [[0.0]] * 2246 inputs = [['0,1,2,3']]247 self._test_dataset(248 inputs,249 expected_err_re='Expect 2 fields but have more in record',250 record_defaults=record_defaults)251 @combinations.generate(test_base.default_test_combinations())252 def testCsvDataset_errorWithMoreDefaultsThanFields(self):253 record_defaults = [[0.0]] * 5254 inputs = [['0,1,2,3']]255 self._test_dataset(256 inputs,257 expected_err_re='Expect 5 fields but have 4 in record',258 record_defaults=record_defaults)259 @combinations.generate(test_base.default_test_combinations())260 def testCsvDataset_withHeader(self):261 record_defaults = [[0]] * 2262 inputs = [['col1,col2', '1,2']]263 expected = [[1, 2]]264 self._test_dataset(265 inputs,266 expected,267 record_defaults=record_defaults,268 header=True,269 )270 @combinations.generate(test_base.default_test_combinations())271 def testCsvDataset_withHeaderAndNoRecords(self):272 record_defaults = [[0]] * 2273 inputs = [['col1,col2']]274 expected = []275 self._test_dataset(276 inputs,277 expected,278 record_defaults=record_defaults,279 header=True,280 )281 @combinations.generate(test_base.default_test_combinations())282 def testCsvDataset_errorWithHeaderEmptyFile(self):283 record_defaults = [[0]] * 2284 inputs = [[]]285 expected_err_re = "Can't read header of file"286 self._test_dataset(287 inputs,288 expected_err_re=expected_err_re,289 record_defaults=record_defaults,290 header=True,291 )292 @combinations.generate(test_base.default_test_combinations())293 def testCsvDataset_withEmptyFile(self):294 record_defaults = [['']] * 2295 inputs = [['']] # Empty file296 self._test_dataset(297 inputs, expected_output=[], record_defaults=record_defaults)298 @combinations.generate(test_base.default_test_combinations())299 def testCsvDataset_errorWithEmptyRecord(self):300 record_defaults = [['']] * 2301 inputs = [['', '1,2']] # First record is empty302 self._test_dataset(303 inputs,304 expected_err_re='Expect 2 fields but have 1 in record',305 record_defaults=record_defaults)306 @combinations.generate(test_base.default_test_combinations())307 def testCsvDataset_withChainedOps(self):308 # Testing that one dataset can create multiple iterators fine.309 # `repeat` creates multiple iterators from the same C++ Dataset.310 record_defaults = [[0]] * 4311 inputs = [['1,,3,4', '5,6,,8']]312 ds_actual, ds_expected = self._make_test_datasets(313 inputs, record_defaults=record_defaults)314 self.assertDatasetsEqual(315 ds_actual.repeat(5).prefetch(1),316 ds_expected.repeat(5).prefetch(1))317 @combinations.generate(test_base.default_test_combinations())318 def testCsvDataset_withTypeDefaults(self):319 # Testing using dtypes as record_defaults for required fields320 record_defaults = [dtypes.float32, [0.0]]321 inputs = [['1.0,2.0', '3.0,4.0']]322 self._test_dataset(323 inputs,324 [[1.0, 2.0], [3.0, 4.0]],325 record_defaults=record_defaults,326 )327 @combinations.generate(test_base.default_test_combinations())328 def testMakeCsvDataset_fieldOrder(self):329 data = [[330 '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19',331 '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19'332 ]]333 file_path = self._setup_files(data)334 ds = readers.make_csv_dataset(335 file_path, batch_size=1, shuffle=False, num_epochs=1)336 nxt = self.getNext(ds)337 result = list(self.evaluate(nxt()).values())338 self.assertEqual(result, sorted(result))339## The following tests exercise parsing logic for quoted fields340 @combinations.generate(test_base.default_test_combinations())341 def testCsvDataset_withQuoted(self):342 record_defaults = [['']] * 4343 inputs = [['"a","b","c :)","d"', '"e","f","g :(","h"']]344 self._test_by_comparison(inputs, record_defaults=record_defaults)345 def testCsvDataset_withOneColAndQuotes(self):346 record_defaults = [['']]347 inputs = [['"0"', '"1"', '"2"']]348 self._test_dataset(349 inputs, [['0'], ['1'], ['2']], record_defaults=record_defaults)350 @combinations.generate(test_base.default_test_combinations())351 def testCsvDataset_withNewLine(self):352 # In this case, we expect it to behave differently from353 # TextLineDataset->map(decode_csv) since that flow has bugs354 record_defaults = [['']] * 4355 inputs = [['a,b,"""c""\n0","d\ne"', 'f,g,h,i']]356 expected = [['a', 'b', '"c"\n0', 'd\ne'], ['f', 'g', 'h', 'i']]357 self._test_dataset(inputs, expected, record_defaults=record_defaults)358 @combinations.generate(test_base.default_test_combinations())359 def testCsvDataset_withNewLineInUnselectedCol(self):360 record_defaults = [['']]361 inputs = [['1,"2\n3",4', '5,6,7']]362 self._test_dataset(363 inputs,364 expected_output=[['1'], ['5']],365 record_defaults=record_defaults,366 select_cols=[0])367 @combinations.generate(test_base.default_test_combinations())368 def testCsvDataset_withMultipleNewLines(self):369 # In this case, we expect it to behave differently from370 # TextLineDataset->map(decode_csv) since that flow has bugs371 record_defaults = [['']] * 4372 inputs = [['a,"b\n\nx","""c""\n \n0","d\ne"', 'f,g,h,i']]373 expected = [['a', 'b\n\nx', '"c"\n \n0', 'd\ne'], ['f', 'g', 'h', 'i']]374 self._test_dataset(inputs, expected, record_defaults=record_defaults)375 @combinations.generate(test_base.default_test_combinations())376 def testCsvDataset_errorWithTerminateMidRecord(self):377 record_defaults = [['']] * 4378 inputs = [['a,b,c,"a']]379 self._test_dataset(380 inputs,381 expected_err_re=382 'Reached end of file without closing quoted field in record',383 record_defaults=record_defaults)384 @combinations.generate(test_base.default_test_combinations())385 def testCsvDataset_withEscapedQuotes(self):386 record_defaults = [['']] * 4387 inputs = [['1.0,2.1,"she said: ""hello""",4.3', '5.4,6.5,goodbye,8.7']]388 self._test_by_comparison(inputs, record_defaults=record_defaults)389## Testing that parsing works with all buffer sizes, quoted/unquoted fields,390## and different types of line breaks391 @combinations.generate(test_base.default_test_combinations())392 def testCsvDataset_withInvalidBufferSize(self):393 record_defaults = [['']] * 4394 inputs = [['a,b,c,d']]395 self._test_dataset(396 inputs,397 expected_err_re='buffer_size should be positive',398 record_defaults=record_defaults,399 buffer_size=0)400 def _test_dataset_on_buffer_sizes(self,401 inputs,402 expected,403 linebreak,404 record_defaults,405 compression_type=None,406 num_sizes_to_test=20):407 # Testing reading with a range of buffer sizes that should all work.408 for i in list(range(1, 1 + num_sizes_to_test)) + [None]:409 self._test_dataset(410 inputs,411 expected,412 linebreak=linebreak,413 compression_type=compression_type,414 record_defaults=record_defaults,415 buffer_size=i)416 @combinations.generate(test_base.default_test_combinations())417 def testCsvDataset_withLF(self):418 record_defaults = [['NA']] * 3419 inputs = [['abc,def,ghi', '0,1,2', ',,']]420 expected = [['abc', 'def', 'ghi'], ['0', '1', '2'], ['NA', 'NA', 'NA']]421 self._test_dataset_on_buffer_sizes(422 inputs, expected, linebreak='\n', record_defaults=record_defaults)423 @combinations.generate(test_base.default_test_combinations())424 def testCsvDataset_withCR(self):425 # Test that when the line separator is '\r', parsing works with all buffer426 # sizes427 record_defaults = [['NA']] * 3428 inputs = [['abc,def,ghi', '0,1,2', ',,']]429 expected = [['abc', 'def', 'ghi'], ['0', '1', '2'], ['NA', 'NA', 'NA']]430 self._test_dataset_on_buffer_sizes(431 inputs, expected, linebreak='\r', record_defaults=record_defaults)432 @combinations.generate(test_base.default_test_combinations())433 def testCsvDataset_withCRLF(self):434 # Test that when the line separator is '\r\n', parsing works with all buffer435 # sizes436 record_defaults = [['NA']] * 3437 inputs = [['abc,def,ghi', '0,1,2', ',,']]438 expected = [['abc', 'def', 'ghi'], ['0', '1', '2'], ['NA', 'NA', 'NA']]439 self._test_dataset_on_buffer_sizes(440 inputs, expected, linebreak='\r\n', record_defaults=record_defaults)441 @combinations.generate(test_base.default_test_combinations())442 def testCsvDataset_withBufferSizeAndQuoted(self):443 record_defaults = [['NA']] * 3444 inputs = [['"\n\n\n","\r\r\r","abc"', '"0","1","2"', '"","",""']]445 expected = [['\n\n\n', '\r\r\r', 'abc'], ['0', '1', '2'],446 ['NA', 'NA', 'NA']]447 self._test_dataset_on_buffer_sizes(448 inputs, expected, linebreak='\n', record_defaults=record_defaults)449 @combinations.generate(test_base.default_test_combinations())450 def testCsvDataset_withCRAndQuoted(self):451 # Test that when the line separator is '\r', parsing works with all buffer452 # sizes453 record_defaults = [['NA']] * 3454 inputs = [['"\n\n\n","\r\r\r","abc"', '"0","1","2"', '"","",""']]455 expected = [['\n\n\n', '\r\r\r', 'abc'], ['0', '1', '2'],456 ['NA', 'NA', 'NA']]457 self._test_dataset_on_buffer_sizes(458 inputs, expected, linebreak='\r', record_defaults=record_defaults)459 @combinations.generate(test_base.default_test_combinations())460 def testCsvDataset_withCRLFAndQuoted(self):461 # Test that when the line separator is '\r\n', parsing works with all buffer462 # sizes463 record_defaults = [['NA']] * 3464 inputs = [['"\n\n\n","\r\r\r","abc"', '"0","1","2"', '"","",""']]465 expected = [['\n\n\n', '\r\r\r', 'abc'], ['0', '1', '2'],466 ['NA', 'NA', 'NA']]467 self._test_dataset_on_buffer_sizes(468 inputs, expected, linebreak='\r\n', record_defaults=record_defaults)469 @combinations.generate(test_base.default_test_combinations())470 def testCsvDataset_withGzipCompressionType(self):471 record_defaults = [['NA']] * 3472 inputs = [['"\n\n\n","\r\r\r","abc"', '"0","1","2"', '"","",""']]473 expected = [['\n\n\n', '\r\r\r', 'abc'], ['0', '1', '2'],474 ['NA', 'NA', 'NA']]475 self._test_dataset_on_buffer_sizes(476 inputs,477 expected,478 linebreak='\r\n',479 compression_type='GZIP',480 record_defaults=record_defaults)481 @combinations.generate(test_base.default_test_combinations())482 def testCsvDataset_withZlibCompressionType(self):483 record_defaults = [['NA']] * 3484 inputs = [['"\n\n\n","\r\r\r","abc"', '"0","1","2"', '"","",""']]485 expected = [['\n\n\n', '\r\r\r', 'abc'], ['0', '1', '2'],486 ['NA', 'NA', 'NA']]487 self._test_dataset_on_buffer_sizes(488 inputs,489 expected,490 linebreak='\r\n',491 compression_type='ZLIB',492 record_defaults=record_defaults)493 @combinations.generate(test_base.default_test_combinations())494 def testCsvDataset_withScalarDefaults(self):495 record_defaults = [constant_op.constant(0, dtype=dtypes.int64)] * 4496 inputs = [[',,,', '1,1,1,', ',2,2,2']]497 self._test_dataset(498 inputs, [[0, 0, 0, 0], [1, 1, 1, 0], [0, 2, 2, 2]],499 record_defaults=record_defaults)500 @combinations.generate(test_base.default_test_combinations())501 def testCsvDataset_with2DDefaults(self):502 record_defaults = [constant_op.constant([[0]], dtype=dtypes.int64)] * 4503 inputs = [[',,,', '1,1,1,', ',2,2,2']]504 if context.executing_eagerly():505 err_spec = errors.InvalidArgumentError, (506 'Each record default should be at '507 'most rank 1')508 else:509 err_spec = ValueError, 'Shape must be at most rank 1 but is rank 2'510 with self.assertRaisesWithPredicateMatch(*err_spec):511 self._test_dataset(512 inputs, [[0, 0, 0, 0], [1, 1, 1, 0], [0, 2, 2, 2]],513 record_defaults=record_defaults)514if __name__ == '__main__':...

Full Screen

Full Screen

notifIt.js

Source:notifIt.js Github

copy

Full Screen

1/*2 * notifIt! by @naoxink3 */4(function(root, factory) {5 if (typeof define === 'function' && define.amd) {6 // AMD. Register as an anonymous module.7 define(factory);8 } else {9 // Browser globals10 var package = factory(root.b);11 root.notif = package.notif;12 root.notif_confirm = package.notif_confirm;13 root.notif_prompt = package.notif_prompt;14 }15}(this, function() {16 // Notification17 function notif(config) {18 // Util stuff19 var create_close_button = function() {20 return $('<span>', {21 'id': 'notifIt_close',22 'html': '&times'23 });24 }25 var create_notification = function() {26 var div = $('<div>', {27 'id': 'ui_notifIt'28 });29 var p = $('<p>', {30 html: defaults.msg31 });32 div.append(p);33 return div;34 }35 // We love jQuery36 var $ = jQuery;37 var destroy = function() {38 $("#ui_notifIt").remove();39 clearTimeout(window.notifit_timeout);40 }41 var dismiss = function(){42 clearTimeout(window.notifit_timeout);43 if (!defaults.fade) {44 // Set animations45 if (defaults.animations && 46 defaults.animations[defaults.animation] && 47 defaults.animations[defaults.animation][defaults.position] && 48 defaults.animations[defaults.animation][defaults.position].out && 49 defaults.animations[defaults.animation][defaults.position].out.start && 50 defaults.animations[defaults.animation][defaults.position].out.end) {51 animation1 = defaults.animations[defaults.animation][defaults.position].out.start52 animation2 = defaults.animations[defaults.animation][defaults.position].out.end53 } else if (defaults.animations[defaults.available_animations[0]] && 54 defaults.animations[defaults.available_animations[0]][defaults.position] && 55 defaults.animations[defaults.available_animations[0]][defaults.position].out && 56 defaults.animations[defaults.available_animations[0]][defaults.position].out.start && 57 defaults.animations[defaults.available_animations[0]][defaults.position].out.end) {58 animation1 = defaults.animations[defaults.available_animations[0]][defaults.position].out.start59 animation2 = defaults.animations[defaults.available_animations[0]][defaults.position].out.end60 } else {61 throw new Error('Invalid animation')62 }63 // Execute animations 64 $("#ui_notifIt").animate(animation1, 100, function() {65 $("#ui_notifIt").animate(animation2, 100, function() {66 $("#ui_notifIt").remove();67 if (defaults.callback) {68 defaults.callback();69 }70 });71 });72 } else {73 // jQuery's fade, why create my own?74 $("#ui_notifIt").fadeOut("slow", function() {75 $("#ui_notifIt").remove();76 if (defaults.callback) {77 defaults.callback();78 }79 });80 }81 }82 destroy()83 // Global timeout84 window.notifit_timeout = null;85 // Mid position86 var mid = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) / 2;87 // Available positions88 var available_positions = ['left', 'center', 'right', 'bottom'];89 // Default config90 var defaults = {91 type: "default",92 width: 400,93 position: "right",94 autohide: 1,95 msg: "This is my default message",96 opacity: 1,97 multiline: 0,98 fade: 0,99 bgcolor: "",100 color: "",101 timeout: 5000,102 zindex: null,103 offset: 0,104 callback: null,105 clickable: false,106 animation: 'slide'107 };108 // Extend with new params109 $.extend(defaults, config);110 // Animation config111 // ** Maybe create an external js with only animations for easier customizing? **112 defaults.animations = {}113 // Slide animation [DEFAULT]114 defaults.animations.slide = {115 'center': {116 'css_start': {117 "top": parseInt(0 - (defaults.height + 10)),118 "left": mid - parseInt(defaults.width / 2)119 },120 'in': {121 'top': parseInt(10 + defaults.offset)122 },123 'out': {124 'start': {125 'top': parseInt(defaults.height - (defaults.height / 2))126 },127 'end': {128 'top': parseInt(0 - (defaults.height * 2))129 }130 }131 },132 'bottom': {133 'css_start': {134 "top": 'auto',135 "bottom": parseInt(0 - (defaults.height + 10)),136 "left": mid - parseInt(defaults.width / 2)137 },138 'in': {139 'bottom': parseInt(10 + defaults.offset)140 },141 'out': {142 'start': {143 'bottom': parseInt(defaults.height - (defaults.height / 2))144 },145 'end': {146 'bottom': parseInt(0 - (defaults.height * 2))147 }148 }149 },150 'right': {151 'css_start': {152 "right": parseInt(0 - (defaults.width + 10)),153 "right": parseInt(0 - (defaults.width * 2))154 },155 'in': {156 'right': parseInt(10 + defaults.offset)157 },158 'out': {159 'start': {160 'right': parseFloat(defaults.width - (defaults.width * 0.9))161 },162 'end': {163 'right': parseInt(0 - (defaults.width * 2))164 }165 }166 },167 'left': {168 'css_start': {169 "left": parseInt(0 - (defaults.width + 10))170 },171 'in': {172 'left': parseInt(10 + defaults.offset)173 },174 'out': {175 'start': {176 'left': parseFloat(defaults.width - (defaults.width * 0.9))177 },178 'end': {179 'left': parseInt(0 - (defaults.width * 2))180 }181 }182 }183 };184 // Zoom animation185 defaults.animations.zoom = {186 'center': { // Not working well187 'css_start': {188 "top": 10,189 "left": mid - parseInt(defaults.width / 2),190 "zoom": 0.01191 },192 'in': {193 'zoom': 1194 },195 'out': {196 'start': {197 'zoom': 1.3198 },199 'end': {200 'zoom': 0.01201 }202 }203 },204 'bottom': { // Not working well205 'css_start': {206 "top": 'auto',207 "bottom": 10,208 "left": mid - parseInt(defaults.width / 2),209 "zoom": 0.01210 },211 'in': {212 'zoom': 1213 },214 'out': {215 'start': {216 'zoom': 1.3217 },218 'end': {219 'zoom': 0.01220 }221 }222 },223 'right': {224 'css_start': {225 'right': 10,226 'zoom': 0.01227 },228 'in': {229 'right': parseInt(10 + defaults.offset),230 'zoom': 1231 },232 'out': {233 'start': {234 'zoom': 1.3235 },236 'end': {237 'zoom': 0.01238 }239 }240 },241 'left': {242 'css_start': {243 'left': 10,244 'zoom': 0.01245 },246 'in': {247 'zoom': 1248 },249 'out': {250 'start': {251 'zoom': 1.3252 },253 'end': {254 'zoom': 0.01255 }256 }257 }258 };259 // Check if animation exists260 defaults.available_animations = Object.keys(defaults.animations)261 if (!defaults.available_animations.length) {262 throw new Error('No animations')263 }264 if (!available_positions.length) {265 throw new Error('No available positions')266 }267 if (available_positions.indexOf(defaults.position) === -1) {268 defaults.position = available_positions[0]269 }270 if (defaults.available_animations.indexOf(defaults.animation) === -1) {271 defaults.animation = defaults.available_animations[0]272 }273 // Check callback274 if (typeof defaults.callback !== 'function') {275 defaults.callback = null;276 }277 // Width & Height278 if (defaults.width > 0) {279 defaults.width = defaults.width;280 } else if (defaults.width === "all") {281 defaults.width = screen.width - 60;282 } else {283 defaults.width = 400;284 }285 if (defaults.height > 100 || defaults.height < 0) {286 defaults.height = 60;287 }288 // Create notification itself289 var div = create_notification()290 // If clickable add close button291 if (defaults.clickable) {292 div.append(create_close_button())293 }294 $("body").append(div);295 // Set z-index296 if (defaults.zindex) {297 $("#ui_notifIt").css("z-index", defaults.zindex);298 }299 // If multiline we have to set the padding instead line-height300 if (defaults.multiline) {301 $("#ui_notifIt").css("padding", 15);302 } else {303 $("#ui_notifIt").css("height", defaults.height);304 $("#ui_notifIt p").css("line-height", defaults.height + "px");305 }306 // Basic css307 $("#ui_notifIt").css({308 "width": defaults.width,309 "opacity": defaults.opacity,310 "background-color": defaults.bgcolor,311 "color": defaults.color312 });313 $("#ui_notifIt p").css({314 "color": defaults.color315 })316 // Class 'success', 'error', 'warning', 'info'..317 $("#ui_notifIt").addClass(defaults.type);318 // Set entry animation 319 if (defaults.animations[defaults.animation][defaults.position].css_start) {320 $("#ui_notifIt").css(defaults.animations[defaults.animation][defaults.position].css_start);321 } else {322 $("#ui_notifIt").css(defaults.animations[defaults.available_animations[0]][defaults.position].css_start);323 }324 // Execute entry animation325 $("#ui_notifIt").animate(defaults.animations[defaults.animation][defaults.position].in);326 // Events327 if (!defaults.clickable) {328 $("#ui_notifIt").click(function(e) {329 e.stopPropagation();330 dismiss(defaults);331 });332 }333 $('body').on('click', '#ui_notifIt #notifIt_close', function() {334 dismiss(defaults);335 });336 if (defaults.autohide) {337 if (!isNaN(defaults.timeout)) {338 window.notifit_timeout = setTimeout(function() {339 dismiss(defaults);340 }, defaults.timeout);341 }342 }343 return {344 'destroy': destroy,345 'dismiss': dismiss346 }347 }348 // Confirm349 function notif_confirm(config){350 var $ = jQuery351 var _config = {352 'textaccept': 'Accept',353 'textcancel': 'Cancel',354 'message': 'Is that what you want to do?',355 'fullscreen': false,356 'callback': null357 }358 var settings = $.extend({ }, _config, config)359 var $confirm = $('.notifit_confirm')[0] ? $('.notifit_confirm') : null;360 var $bg = $('.notifit_confirm_bg')[0] ? $('.notifit_confirm_bg') : null;361 function _create(){362 if($confirm !== null){363 return $confirm364 }365 var $acceptButton = $('<button>', {366 'class': 'notifit_confirm_accept',367 'text': settings.textaccept368 })369 var $cancelButton = $('<button>', {370 'class': 'notifit_confirm_cancel',371 'text': settings.textcancel372 })373 var $message = $('<div>', {374 'class': 'notifit_confirm_message',375 'text': settings.message376 })377 $confirm = $('<div>', {378 'class': 'notifit_confirm'379 })380 $confirm381 .append($message)382 .append($acceptButton)383 .append($cancelButton)384 $bg = $('<div>', { 'class': 'notifit_confirm_bg' })385 return $confirm386 }387 function _show(){388 if($confirm){389 if(settings.fullscreen){390 $bg.hide()391 $confirm.hide()392 $('body').append($bg)393 $('body').append($confirm)394 $confirm.css({395 'top': $bg.outerHeight() / 2 - ($confirm.outerHeight() / 2),396 'left': $bg.outerWidth() / 2 - ($confirm.outerWidth() / 2)397 })398 $bg.fadeIn('fast', function(){ $confirm.slideDown('fast') })399 }else{400 $confirm.css({401 'top': '20px',402 'left': 'auto',403 'right': '20px',404 'display': 'none'405 })406 $('body').append($confirm)407 $confirm.slideDown('fast')408 }409 }410 }411 function _hide(){412 if($confirm){413 $confirm.slideUp('fast', function(){414 $confirm.remove()415 })416 }417 if($bg){418 $bg.fadeOut('fast', function(){419 $bg.remove()420 })421 }422 }423 function _callback(){424 _hide()425 var response = null426 if($(this).hasClass('notifit_confirm_accept')){427 response = true428 }else if($(this).hasClass('notifit_confirm_cancel')){429 response = false430 }431 if(typeof settings.callback === 'function'){432 return settings.callback(response)433 }434 return response435 }436 function _setListeners(){437 $('html').one('click', '.notifit_confirm_accept, .notifit_confirm_cancel', _callback)438 }439 // Get the party started! \o/440 _create()441 _show()442 _setListeners()443 }444 // Prompt445 function notif_prompt(config){446 var $ = jQuery447 var _config = {448 'message': 'Tell me something',449 'default_value': '',450 'textaccept': 'Accept',451 'textcancel': 'Cancel',452 'fullscreen': false,453 'callback': null454 }455 var settings = $.extend({ }, _config, config)456 var $prompt = $('.notifit_prompt')[0] ? $('.notifit_prompt') : null;457 var $bg = $('.notifit_prompt_bg')[0] ? $('.notifit_prompt_bg') : null;458 function _create(){459 if($prompt !== null){ return $prompt }460 var $acceptButton = $('<button>', {461 'class': 'notifit_prompt_accept',462 'text': settings.textaccept463 })464 var $cancelButton = $('<button>', {465 'class': 'notifit_prompt_cancel',466 'text': settings.textcancel467 })468 var $message = $('<p>', {469 'class': 'notifit_prompt_message',470 'text': settings.message471 })472 var $input = $('<input>', {473 'type': 'text',474 'class': 'notifit_prompt_input',475 'value': settings.default_value476 })477 $prompt = $('<div>', {478 'class': 'notifit_prompt'479 })480 $prompt481 .append($message)482 .append($input)483 .append($cancelButton)484 .append($acceptButton)485 $bg = $('<div>', { 'class': 'notifit_prompt_bg' })486 return $prompt487 }488 function _show(){489 if($prompt){490 if(settings.fullscreen){491 $bg.hide()492 $prompt.hide()493 $('body').append($bg)494 $('body').append($prompt)495 $prompt.css({496 'top': $bg.outerHeight() / 2 - ($prompt.outerHeight() / 2),497 'left': $bg.outerWidth() / 2 - ($prompt.outerWidth() / 2)498 })499 $bg.fadeIn('fast', function(){ $prompt.slideDown('fast', function(){ $(this).find('.notifit_prompt_input').focus() }) })500 }else{501 $prompt.css({502 'top': '20px',503 'left': 'auto',504 'right': '20px',505 'display': 'none'506 })507 $('body').append($prompt)508 $prompt.slideDown('fast', function(){ $(this).find('.notifit_prompt_input').focus() })509 }510 }511 }512 function _hide(){513 if($prompt){514 $prompt.slideUp('fast', function(){515 $prompt.remove()516 })517 }518 if($bg){519 $bg.fadeOut('fast', function(){520 $bg.remove()521 })522 }523 }524 function _callback(){525 _hide()526 var response = null527 if($(this).hasClass('notifit_prompt_accept')){528 response = $(this).parents('.notifit_prompt').find('.notifit_prompt_input').val()529 }else if($(this).hasClass('notifit_prompt_cancel')){530 response = false531 }532 if(typeof settings.callback === 'function'){533 return settings.callback(response)534 }535 return response536 }537 function _setListeners(){538 $('html').one('click', '.notifit_prompt_accept, .notifit_prompt_cancel', _callback)539 }540 // Get the party started! Again! \o/541 _create()542 _show()543 _setListeners()544 }545 return {546 notif: notif,547 notif_confirm: notif_confirm,548 notif_prompt: notif_prompt549 };...

Full Screen

Full Screen

pylab_backend.py

Source:pylab_backend.py Github

copy

Full Screen

...45def _choose(test, iftrue, iffalse=None):46 if test:47 return iftrue48 return iffalse49_errorbar_defaults = get_keyword_defaults(pylab.Axes.errorbar)50def clear_window():51 pylab.clf()52def set_window_redraw(redraw):53 if redraw:54 pylab.draw()55def point(x, y, overplot=True, clearwindow=False,56 symbol=None,57 color=None):58 if overplot:59 axes = pylab.gca()60 else:61 if clearwindow:62 clear_window()63 axes = pylab.gca()64 65 if color is None:66 str = '%s'%(symbol)67 else:68 str = '%s%s'%(color,symbol)69 point = axes.plot(numpy.array([x]),numpy.array([y]),str)[0]70 71 #pylab.draw()72def histo(xlo, xhi, y, yerr=None, title=None, xlabel=None, ylabel=None,73 overplot=False, clearwindow=True,74 yerrorbars=False,75 ecolor=_errorbar_defaults['ecolor'],76 capsize=_errorbar_defaults['capsize'],77 barsabove=_errorbar_defaults['barsabove'],78 xlog=False,79 ylog=False,80 linestyle='steps-mid',81 linecolor=None,82 color=None,83 marker='None',84 markerfacecolor=None,85 markersize=None):86 plot(0.5*(xlo+xhi), y, yerr, None, title, xlabel, ylabel, overplot, clearwindow,87 False, yerrorbars, ecolor, capsize, barsabove, xlog, ylog, linestyle,88 linecolor, color, marker, markerfacecolor, markersize, False, False)89_attr_map = {90 'linecolor' : 'color',91 'linestyle' : 'linestyle',92 'linewidth' : 'linewidth',93 }94_linestyle_map = {95 'noline' : ' ',96 'solid' : '-',97 'dot' : ':',98 'dash' : '--', 99 'dotdash' : '-.',100 }101def _check_hex_color(val):102 if type(val) in (str, numpy.string_) and val.startswith('0x'):103 val = '#'+str(val).replace('0x','').rjust(6,'0')104 return val105def vline(x, ymin=0, ymax=1,106 linecolor=None,107 linestyle=None,108 linewidth=None,109 overplot=False, clearwindow=True):110 if overplot:111 axes = pylab.gca()112 else:113 if clearwindow:114 clear_window()115 axes = pylab.gca()116 line = axes.axvline(x, ymin, ymax)117 for var in ('linecolor', 'linestyle', 'linewidth'):118 val = locals()[var]119 if val is not None:120 if 'style' in var:121 val = _linestyle_map[val]122 elif 'color' in var:123 val = _check_hex_color(val)124 getattr(line, 'set_' + _attr_map[var])(val)125def hline(y, xmin=0, xmax=1,126 linecolor=None,127 linestyle=None,128 linewidth=None,129 overplot=False, clearwindow=True):130 if overplot:131 axes = pylab.gca()132 else:133 if clearwindow:134 clear_window()135 axes = pylab.gca()136 line = axes.axhline(y, xmin, xmax)137 for var in ('linecolor', 'linestyle', 'linewidth'):138 val = locals()[var]139 if val is not None:140 if 'style' in var:141 val = _linestyle_map[val]142 elif 'color' in var:143 val = _check_hex_color(val)144 getattr(line, 'set_' + _attr_map[var])(val)145def plot(x, y, yerr=None, xerr=None, title=None, xlabel=None, ylabel=None,146 overplot=False, clearwindow=True,147 xerrorbars=False,148 yerrorbars=False,149 ecolor=_errorbar_defaults['ecolor'],150 capsize=_errorbar_defaults['capsize'],151 barsabove=_errorbar_defaults['barsabove'],152 xlog=False,153 ylog=False,154 linestyle='steps',155 linecolor=None,156 color=None,157 marker='None',158 markerfacecolor=None,159 markersize=None,160 xaxis=False,161 ratioline=False):162 if overplot:163 axes = pylab.gca()164 else:165 if clearwindow:166 clear_window()167 axes = pylab.gca()168 xscale = _choose(xlog, 'log', 'linear')169 yscale = _choose(ylog, 'log', 'linear')170 axes.set_xscale(xscale)171 axes.set_yscale(yscale)172 if title:173 axes.set_title(title)174 if xlabel:175 axes.set_xlabel(xlabel)176 if ylabel:177 axes.set_ylabel(ylabel)178 # Even if we're doing an error bar plot, we do a normal plot first so179 # that we can take advantage of the default color cycling180 line = axes.plot(x, y)[0]181 if xerrorbars or yerrorbars:182 line.set_visible(False)183 if color is None:184 color = line.get_color()185 if markerfacecolor is None:186 markerfacecolor = color187 if xerr is not None:188 xerr = xerr / 2.189 xerr = _choose(xerrorbars, xerr)190 yerr = _choose(yerrorbars, yerr)191 line = axes.errorbar(x, y, yerr, xerr, ecolor=ecolor, capsize=capsize,192 barsabove=barsabove, color=color,193 markerfacecolor=markerfacecolor)[0]194 for var in ('linestyle', 'color', 'marker', 'markerfacecolor',195 'markersize'):196 val = locals()[var]197 if val is not None:198 getattr(line, 'set_' + var)(val)199 if xaxis:200 axes.axhspan(ymin=0, ymax=0, xmin=0, xmax=1)201 202 if ratioline:203 axes.axhspan(ymin=1, ymax=1, xmin=0, xmax=1)204 #pylab.draw()205 206def contour(x0, x1, y, levels=None, title=None, xlabel=None, ylabel=None,207 overcontour=False, clearwindow=True,208 xlog=False,209 ylog=False,210 linewidths=None,211 colors=None):212 213 if overcontour:214 axes = pylab.gca()215 else:216 if clearwindow:217 clear_window()218 axes = pylab.gca()219 if title:220 axes.set_title(title)221 if xlabel:222 axes.set_xlabel(xlabel)223 if ylabel:224 axes.set_ylabel(ylabel)225 xscale = _choose(xlog, 'log', 'linear')226 yscale = _choose(ylog, 'log', 'linear')227 axes.set_xscale(xscale)228 axes.set_yscale(yscale)229 x0 = numpy.unique(x0)230 x1 = numpy.unique(x1)231 y = numpy.asarray(y)232 if x0.size * x1.size != y.size:233 raise NotImplementedErr('contourgrids')234 y = y.reshape(x1.size, x0.size)235 if levels is None:236 line = axes.contour(x0, x1, y, colors=colors, linewidths=linewidths)237 else:238 line = axes.contour(x0, x1, y, levels, colors=colors,239 linewidths=linewidths)240 #pylab.draw()241def set_subplot(row, col, nrows, ncols, clearaxes=True,242 left=None,243 right=None,244 bottom=None,245 top=None,246 wspace=0.3,247 hspace=0.4):248 pylab.subplots_adjust(left=left, right=right, bottom=bottom, top=top,249 wspace=wspace, hspace=hspace)250 num = row*ncols + col + 1251 # As of numpy 0.9.8, these need to be cast to int to prevent errors252 # in matplotlib253 nrows = int(nrows)254 ncols = int(ncols)255 num = int(num)256 257 pylab.subplot(nrows, ncols, num)258 if clearaxes:259 pylab.cla()260def set_jointplot(row, col, nrows, ncols, clearaxes=True,261 top=1,262 ratio=2):263 if not clearaxes:264 f, axarr = pylab.subplots(nrows, sharex=True, num=1)265 f.subplots_adjust(hspace=0.05)266 pylab.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)267 # need to set axes[0] as current axes.268 pylab.sca(axarr[0])269 else:270 271 # need to set axes[1] as current axes.272 axes = pylab.gca()273 ax2 = axes.figure.axes[-1]274 pylab.sca(ax2)275 #ax2.get_yticklabels()[-1].set_visible(False)276def get_split_plot_defaults():277 return get_keyword_defaults(set_subplot, 1)278 279def get_plot_defaults():280 return get_keyword_defaults(plot, 7)281def get_point_defaults():282 return get_keyword_defaults(point, 2)283def get_histo_defaults():284 return get_keyword_defaults(histo, 6)285def get_confid_point_defaults():286 d = get_point_defaults()287 d['symbol']='+'288 return d289def get_data_plot_defaults():290 d = get_plot_defaults()291 d['yerrorbars'] = True292 d['linestyle'] = 'None'293 d['marker'] = '.'294 return d295def get_model_histo_defaults():296 d = get_histo_defaults()297 return d298def get_model_plot_defaults():299 d = get_plot_defaults()300 d['linestyle'] = '-'301 d['marker'] = 'None'302 return d303def get_fit_plot_defaults():304 return {}305def get_resid_plot_defaults():306 d = get_data_plot_defaults()307 d['xerrorbars'] = True308 d['capsize'] = 0309 #d['marker'] = '_'310 d['xaxis'] = True311 return d312def get_ratio_plot_defaults():313 d = get_data_plot_defaults()314 d['xerrorbars'] = True315 d['capsize'] = 0316 #d['marker'] = '_'317 d['ratioline'] = True318 return d319def get_confid_plot_defaults():320 d = get_plot_defaults()321 d['linestyle'] = '-'322 d['marker'] = 'None'323 return d324def get_contour_defaults():325 return get_keyword_defaults(contour, 6)326get_data_contour_defaults = get_contour_defaults327get_model_contour_defaults = get_contour_defaults328def get_fit_contour_defaults():329 return {}330get_confid_contour_defaults = get_data_contour_defaults331get_resid_contour_defaults = get_data_contour_defaults332get_ratio_contour_defaults = get_data_contour_defaults333get_component_plot_defaults = get_model_plot_defaults334get_component_histo_defaults = get_model_histo_defaults335def get_cdf_plot_defaults():336 d = get_model_plot_defaults()337 d['linecolor'] = 'red'338 return d339def get_scatter_plot_defaults():340 d = get_data_plot_defaults()...

Full Screen

Full Screen

floatingAd.js

Source:floatingAd.js Github

copy

Full Screen

1/*2 * Description: 漂浮广告3 * Author: jjc4 * Date: 2012.07.045 */6;(function ( $, window, document, undefined ) {7 var pluginName = 'floatingAd';8 var defaults = {9 step: 1,10 delay: 50, 11 isLinkClosed: false,12 onClose: function(elem){}13 };14 var ads = {15 linkUrl: '#',16 'z-index': '100',17 'closed-icon': '',18 imgHeight: '',19 imgWidth: '',20 title: '',21 img: '#',22 linkWindow: '_blank',23 headFilter: 0.224 };25 function Plugin(element, options) {26 this.element = element;27 this.options = $.extend(28 {}, 29 defaults, 30 options, 31 {32 width: $(window).width(),33 height: $(window).height(),34 xPos: this.getRandomNum(0, $(window).width() - $(element).innerWidth()), 35 yPos: this.getRandomNum(0, 300),36 yOn: this.getRandomNum(0, 1),37 xOn: this.getRandomNum(0, 1),38 yPath: this.getRandomNum(0, 1),39 xPath: this.getRandomNum(0, 1),40 hOffset: $(element).innerHeight(),41 wOffset: $(element).innerWidth(),42 fn: function(){},43 interval: 044 }45 );46 this._defaults = defaults;47 this._name = pluginName;48 49 this.init();50 }51 Plugin.prototype = {52 init: function () {53 var elem = $(this.element);54 var defaults = this.options;55 var p = this;56 var xFlag = 0;57 var yFlag = 0;58 59 elem.css({"left": defaults.xPos + p.scrollX(), "top": defaults.yPos + p.scrollY()});60 defaults.fn = function(){61 defaults.width = $(window).width();62 defaults.height = $(window).height();63 64 if(xFlag == p.scrollX() && yFlag == p.scrollY()){65 elem.css({"left": defaults.xPos + p.scrollX(), "top": defaults.yPos + p.scrollY()});66 if (defaults.yOn)67 defaults.yPos = defaults.yPos + defaults.step;68 else69 defaults.yPos = defaults.yPos - defaults.step;70 71 if (defaults.yPos <= 0) {72 defaults.yOn = 1;73 defaults.yPos = 0;74 }75 if (defaults.yPos >= (defaults.height - defaults.hOffset)) {76 defaults.yOn = 0;77 defaults.yPos = (defaults.height - defaults.hOffset);78 }79 80 if (defaults.xOn) 81 defaults.xPos = defaults.xPos + defaults.step;82 else83 defaults.xPos = defaults.xPos - defaults.step;84 85 if (defaults.xPos <= 0) {86 defaults.xOn = 1;87 defaults.xPos = 0;88 }89 if (defaults.xPos >= (defaults.width - defaults.wOffset)) {90 defaults.xOn = 0;91 defaults.xPos = (defaults.width - defaults.wOffset);92 }93 }94 yFlag = $(window).scrollTop();95 xFlag = $(window).scrollLeft();96 };97 this.run(elem, defaults);98 },99 run: function(elem, defaults){100 this.start(elem, defaults);101 this.adEvent(elem,defaults);102 },103 start: function(elem, defaults){104 elem.find('div.close').hide();105 defaults.interval = window.setInterval(defaults.fn, defaults.delay);106 window.setTimeout(function(){elem.show();}, defaults.delay);107 },108 getRandomNum: function (Min, Max){ 109 var Range = Max - Min; 110 var Rand = Math.random(); 111 return(Min + Math.round(Rand * Range)); 112 },113 getPath: function(on){114 return on ? 0 : 1;115 },116 clear: function(elem, defaults){117 elem.find('div.close').show();118 window.clearInterval(defaults.interval);119 },120 close: function(elem, defaults, isClose){121 elem.unbind('hover');122 elem.hide();123 if(isClose)124 defaults.onClose.call(elem);125 },126 adEvent: function(elem, defaults){127 var obj = {128 elem: this,129 fn_close: function() {130 this.elem.close(elem, defaults, true);131 },132 fn_clear: function() {133 if(this.elem.options.isLinkClosed)134 this.elem.close(elem, defaults, false);135 }136 };137 138 elem.find('div.button').bind('click', jQuery.proxy(obj, "fn_close"));139 140 elem.find('a').bind('click', jQuery.proxy(obj, "fn_clear"));141 142 var stop = {143 elem: this,144 over: function(){145 this.elem.clear(elem, defaults);146 },147 out: function(){148 this.elem.start(elem, defaults);149 }150 };151 152 elem.hover(153 jQuery.proxy(stop, "over"),154 jQuery.proxy(stop, "out")155 );156 },157 scrollX: function(){158 var de = document.documentElement;159 return self.pageXOffset || (de && de.scrollLeft) || document.body.scrollLeft;160 },161 scrollY: function(){162 var de = document.documentElement;163 return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;164 }165 };166 $.fn.floatingAd = function(options) {167 return this.children("div").each(function (i, elem) {168 if (!$.data(this, 'plugin_' + pluginName)) {169 $.data(this, 'plugin_' + pluginName, new Plugin(this, options));170 }171 });172 };173 $.floatingAd = function(options){174 175 if(options){176 if(options.ad){177 var adDiv = $('#' + pluginName);178 179 if(adDiv.length <= 0)180 adDiv = $('<div>', {181 'id': pluginName,182 'class': pluginName183 }).appendTo('body');184 185 for(var i in options.ad){186 187 var ad = options.ad[i];188 ad = $.extend({}, ads, ad);189 //漂浮层190 var div = $('<div>', {191 'class': 'ad'192 });193 194 div.css("z-index", ad['z-index']);195 196 //关闭层197 var closeDiv = $('<div>', {198 'class': 'close',199 'style': (ad.imgWidth ? 'width:' + ad.imgWidth + 'px;' : '')200 });201 $('<div>', {202 'class': 'opacity',203 'style': 'opacity: ' + ad.headFilter + ';filter: alpha(opacity = ' + ad.headFilter*100 + ');'204 }).appendTo(closeDiv);205 206 $('<div>', {207 'class': 'text'208 }).append(209 $('<div>', {210 'class': 'title',211 'text': ad.title212 })213 ).append(214 $('<div>', {215 'class': 'button',216 'style': ad['closed-icon'] ? 'background:url("' + ad['closed-icon'] + '") no-repeat;' : ''217 })218 ).appendTo(closeDiv);219 220 closeDiv.appendTo(div);221 222 //内容层223 var content = $('<div>');224 225 $('<a>', {226 href: ad.linkUrl,227 target: ad.linkWindow,228 title: ad.title229 }).append(230 $('<img>', {231 'src': ad.img,232 'style': (ad.imgHeight ? 'height:' + ad.imgHeight + 'px;' : '') + 233 (ad.imgWidth ? 'width:' + ad.imgWidth + 'px;' : '')234 })235 ).appendTo(content);236 237 content.appendTo(div);238 239 div.appendTo(adDiv);240 }241 delete options.ad;242 $('#' + pluginName).floatingAd(options);243 }244 } 245 else246 $.error('漂浮广告错误!');247 };...

Full Screen

Full Screen

easyui-lang-zh_TW.js

Source:easyui-lang-zh_TW.js Github

copy

Full Screen

1<<<<<<< HEAD2if ($.fn.pagination){3 $.fn.pagination.defaults.beforePageText = '第';4 $.fn.pagination.defaults.afterPageText = '共{pages}頁';5 $.fn.pagination.defaults.displayMsg = '顯示{from}到{to},共{total}記錄';6}7if ($.fn.datagrid){8 $.fn.datagrid.defaults.loadMsg = '正在處理,請稍待。。。';9}10if ($.fn.treegrid && $.fn.datagrid){11 $.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;12}13if ($.messager){14 $.messager.defaults.ok = '確定';15 $.messager.defaults.cancel = '取消';16}17$.map(['validatebox','textbox','passwordbox','filebox','searchbox',18 'combo','combobox','combogrid','combotree',19 'datebox','datetimebox','numberbox',20 'spinner','numberspinner','timespinner','datetimespinner'], function(plugin){21 if ($.fn[plugin]){22 $.fn[plugin].defaults.missingMessage = '該輸入項為必輸項';23 }24});25if ($.fn.validatebox){26 $.fn.validatebox.defaults.rules.email.message = '請輸入有效的電子郵件地址';27 $.fn.validatebox.defaults.rules.url.message = '請輸入有效的URL地址';28 $.fn.validatebox.defaults.rules.length.message = '輸入內容長度必須介於{0}和{1}之間';29 $.fn.validatebox.defaults.rules.remote.message = '請修正此欄位';30}31if ($.fn.calendar){32 $.fn.calendar.defaults.weeks = ['日','一','二','三','四','五','六'];33 $.fn.calendar.defaults.months = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];34}35if ($.fn.datebox){36 $.fn.datebox.defaults.currentText = '今天';37 $.fn.datebox.defaults.closeText = '關閉';38 $.fn.datebox.defaults.okText = '確定';39}40if ($.fn.datetimebox && $.fn.datebox){41 $.extend($.fn.datetimebox.defaults,{42 currentText: $.fn.datebox.defaults.currentText,43 closeText: $.fn.datebox.defaults.closeText,44 okText: $.fn.datebox.defaults.okText45 });46}47if ($.fn.datetimespinner){48 $.fn.datetimespinner.defaults.selections = [[0,4],[5,7],[8,10],[11,13],[14,16],[17,19]]49}50=======51if ($.fn.pagination){52 $.fn.pagination.defaults.beforePageText = '第';53 $.fn.pagination.defaults.afterPageText = '共{pages}頁';54 $.fn.pagination.defaults.displayMsg = '顯示{from}到{to},共{total}記錄';55}56if ($.fn.datagrid){57 $.fn.datagrid.defaults.loadMsg = '正在處理,請稍待。。。';58}59if ($.fn.treegrid && $.fn.datagrid){60 $.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;61}62if ($.messager){63 $.messager.defaults.ok = '確定';64 $.messager.defaults.cancel = '取消';65}66$.map(['validatebox','textbox','passwordbox','filebox','searchbox',67 'combo','combobox','combogrid','combotree',68 'datebox','datetimebox','numberbox',69 'spinner','numberspinner','timespinner','datetimespinner'], function(plugin){70 if ($.fn[plugin]){71 $.fn[plugin].defaults.missingMessage = '該輸入項為必輸項';72 }73});74if ($.fn.validatebox){75 $.fn.validatebox.defaults.rules.email.message = '請輸入有效的電子郵件地址';76 $.fn.validatebox.defaults.rules.url.message = '請輸入有效的URL地址';77 $.fn.validatebox.defaults.rules.length.message = '輸入內容長度必須介於{0}和{1}之間';78 $.fn.validatebox.defaults.rules.remote.message = '請修正此欄位';79}80if ($.fn.calendar){81 $.fn.calendar.defaults.weeks = ['日','一','二','三','四','五','六'];82 $.fn.calendar.defaults.months = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];83}84if ($.fn.datebox){85 $.fn.datebox.defaults.currentText = '今天';86 $.fn.datebox.defaults.closeText = '關閉';87 $.fn.datebox.defaults.okText = '確定';88}89if ($.fn.datetimebox && $.fn.datebox){90 $.extend($.fn.datetimebox.defaults,{91 currentText: $.fn.datebox.defaults.currentText,92 closeText: $.fn.datebox.defaults.closeText,93 okText: $.fn.datebox.defaults.okText94 });95}96if ($.fn.datetimespinner){97 $.fn.datetimespinner.defaults.selections = [[0,4],[5,7],[8,10],[11,13],[14,16],[17,19]]98}...

Full Screen

Full Screen

dummy_backend.py

Source:dummy_backend.py Github

copy

Full Screen

...44set_subplot = point45set_jointplot = point46vline = point47hline = point48def get_split_plot_defaults():49 return get_keyword_defaults(set_subplot, 3)50def get_plot_defaults():51 return get_keyword_defaults(plot, 7)52def get_point_defaults():53 return get_keyword_defaults(point, 2)54def get_contour_defaults():55 return get_keyword_defaults(contour, 6)56def get_histo_defaults():57 return get_keyword_defaults(histo, 6)58def get_dummy_defaults():59 return {}60get_data_plot_defaults = get_dummy_defaults61get_model_plot_defaults = get_dummy_defaults62get_fit_plot_defaults = get_dummy_defaults63get_resid_plot_defaults = get_dummy_defaults64get_ratio_plot_defaults = get_dummy_defaults65get_data_contour_defaults = get_dummy_defaults66get_model_contour_defaults = get_dummy_defaults67get_fit_contour_defaults = get_dummy_defaults68get_resid_contour_defaults = get_dummy_defaults69get_ratio_contour_defaults = get_dummy_defaults70get_confid_point_defaults = get_dummy_defaults71get_confid_plot_defaults = get_dummy_defaults72get_confid_contour_defaults = get_dummy_defaults...

Full Screen

Full Screen

k5_options.js

Source:k5_options.js Github

copy

Full Screen

...15 source: 1,16 kshow_id: -1,17 quick_edit: true18 }19 defaults('allowedMediaTypes', this, options);20 defaults('sessionUrl', this, options);21 defaults('uploadUrl', this, options);22 defaults('entryUrl', this, options);23 defaults('uiconfUrl', this, options);24 defaults('partnerData', this.entryDefaults, options.entryDefaults)25 defaults('conversionProfile', this.entryDefaults, options.entryDefaults)26 defaults('source', this.entryDefaults, options.entryDefaults)27 defaults('kshow_id', this.entryDefaults, options.entryDefaults)28 defaults('quick_edit', this.entryDefaults, options.entryDefaults)29}30K5Options.prototype.asEntryParams = function() {31 return {32 entry1_partnerData: this.entryDefaults.partnerData,33 entry1_conversionProfile: this.entryDefaults.conversionProfile,34 entry1_source: this.entryDefaults.source,35 kshow_id: this.entryDefaults.kshow_id,36 quick_edit: this.entryDefaults.quick_edit37 }38};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('devicefarmer-stf-client');2var defaults = stf.defaults;3var client = defaults({4});5client.devices()6 .then(function(devices){7 console.log(devices);8 })9 .catch(function(error){10 console.log(error);11 });12var stf = require('devicefarmer-stf-client');13var client = stf({14});15client.devices()16 .then(function(devices){17 console.log(devices);18 })19 .catch(function(error){20 console.log(error);21 });

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful