Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50659 views
1
//----------------------------------------------------------------------------
2
// Copyright (C) 2008-2012 The IPython Development Team
3
//
4
// Distributed under the terms of the BSD License. The full license is in
5
// the file COPYING, distributed as part of this software.
6
//----------------------------------------------------------------------------
7
8
//============================================================================
9
// Utilities
10
//============================================================================
11
IPython.namespace('IPython.utils');
12
13
IPython.utils = (function (IPython) {
14
"use strict";
15
16
IPython.load_extensions = function () {
17
// load one or more IPython notebook extensions with requirejs
18
19
var extensions = [];
20
var extension_names = arguments;
21
for (var i = 0; i < extension_names.length; i++) {
22
extensions.push("nbextensions/" + arguments[i]);
23
}
24
25
require(extensions,
26
function () {
27
for (var i = 0; i < arguments.length; i++) {
28
var ext = arguments[i];
29
var ext_name = extension_names[i];
30
// success callback
31
console.log("Loaded extension: " + ext_name);
32
if (ext && ext.load_ipython_extension !== undefined) {
33
ext.load_ipython_extension();
34
}
35
}
36
},
37
function (err) {
38
// failure callback
39
console.log("Failed to load extension(s):", err.requireModules, err);
40
}
41
);
42
};
43
44
//============================================================================
45
// Cross-browser RegEx Split
46
//============================================================================
47
48
// This code has been MODIFIED from the code licensed below to not replace the
49
// default browser split. The license is reproduced here.
50
51
// see http://blog.stevenlevithan.com/archives/cross-browser-split for more info:
52
/*!
53
* Cross-Browser Split 1.1.1
54
* Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
55
* Available under the MIT License
56
* ECMAScript compliant, uniform cross-browser split method
57
*/
58
59
/**
60
* Splits a string into an array of strings using a regex or string
61
* separator. Matches of the separator are not included in the result array.
62
* However, if `separator` is a regex that contains capturing groups,
63
* backreferences are spliced into the result each time `separator` is
64
* matched. Fixes browser bugs compared to the native
65
* `String.prototype.split` and can be used reliably cross-browser.
66
* @param {String} str String to split.
67
* @param {RegExp|String} separator Regex or string to use for separating
68
* the string.
69
* @param {Number} [limit] Maximum number of items to include in the result
70
* array.
71
* @returns {Array} Array of substrings.
72
* @example
73
*
74
* // Basic use
75
* regex_split('a b c d', ' ');
76
* // -> ['a', 'b', 'c', 'd']
77
*
78
* // With limit
79
* regex_split('a b c d', ' ', 2);
80
* // -> ['a', 'b']
81
*
82
* // Backreferences in result array
83
* regex_split('..word1 word2..', /([a-z]+)(\d+)/i);
84
* // -> ['..', 'word', '1', ' ', 'word', '2', '..']
85
*/
86
var regex_split = function (str, separator, limit) {
87
// If `separator` is not a regex, use `split`
88
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
89
return split.call(str, separator, limit);
90
}
91
var output = [],
92
flags = (separator.ignoreCase ? "i" : "") +
93
(separator.multiline ? "m" : "") +
94
(separator.extended ? "x" : "") + // Proposed for ES6
95
(separator.sticky ? "y" : ""), // Firefox 3+
96
lastLastIndex = 0,
97
// Make `global` and avoid `lastIndex` issues by working with a copy
98
separator = new RegExp(separator.source, flags + "g"),
99
separator2, match, lastIndex, lastLength;
100
str += ""; // Type-convert
101
102
var compliantExecNpcg = typeof(/()??/.exec("")[1]) === "undefined";
103
if (!compliantExecNpcg) {
104
// Doesn't need flags gy, but they don't hurt
105
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
106
}
107
/* Values for `limit`, per the spec:
108
* If undefined: 4294967295 // Math.pow(2, 32) - 1
109
* If 0, Infinity, or NaN: 0
110
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
111
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
112
* If other: Type-convert, then use the above rules
113
*/
114
limit = typeof(limit) === "undefined" ?
115
-1 >>> 0 : // Math.pow(2, 32) - 1
116
limit >>> 0; // ToUint32(limit)
117
while (match = separator.exec(str)) {
118
// `separator.lastIndex` is not reliable cross-browser
119
lastIndex = match.index + match[0].length;
120
if (lastIndex > lastLastIndex) {
121
output.push(str.slice(lastLastIndex, match.index));
122
// Fix browsers whose `exec` methods don't consistently return `undefined` for
123
// nonparticipating capturing groups
124
if (!compliantExecNpcg && match.length > 1) {
125
match[0].replace(separator2, function () {
126
for (var i = 1; i < arguments.length - 2; i++) {
127
if (typeof(arguments[i]) === "undefined") {
128
match[i] = undefined;
129
}
130
}
131
});
132
}
133
if (match.length > 1 && match.index < str.length) {
134
Array.prototype.push.apply(output, match.slice(1));
135
}
136
lastLength = match[0].length;
137
lastLastIndex = lastIndex;
138
if (output.length >= limit) {
139
break;
140
}
141
}
142
if (separator.lastIndex === match.index) {
143
separator.lastIndex++; // Avoid an infinite loop
144
}
145
}
146
if (lastLastIndex === str.length) {
147
if (lastLength || !separator.test("")) {
148
output.push("");
149
}
150
} else {
151
output.push(str.slice(lastLastIndex));
152
}
153
return output.length > limit ? output.slice(0, limit) : output;
154
};
155
156
//============================================================================
157
// End contributed Cross-browser RegEx Split
158
//============================================================================
159
160
161
var uuid = function () {
162
// http://www.ietf.org/rfc/rfc4122.txt
163
var s = [];
164
var hexDigits = "0123456789ABCDEF";
165
for (var i = 0; i < 32; i++) {
166
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
167
}
168
s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
169
s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
170
171
var uuid = s.join("");
172
return uuid;
173
};
174
175
176
//Fix raw text to parse correctly in crazy XML
177
function xmlencode(string) {
178
return string.replace(/\&/g,'&'+'amp;')
179
.replace(/</g,'&'+'lt;')
180
.replace(/>/g,'&'+'gt;')
181
.replace(/\'/g,'&'+'apos;')
182
.replace(/\"/g,'&'+'quot;')
183
.replace(/`/g,'&'+'#96;');
184
}
185
186
187
//Map from terminal commands to CSS classes
188
var ansi_colormap = {
189
"01":"ansibold",
190
191
"30":"ansiblack",
192
"31":"ansired",
193
"32":"ansigreen",
194
"33":"ansiyellow",
195
"34":"ansiblue",
196
"35":"ansipurple",
197
"36":"ansicyan",
198
"37":"ansigray",
199
200
"40":"ansibgblack",
201
"41":"ansibgred",
202
"42":"ansibggreen",
203
"43":"ansibgyellow",
204
"44":"ansibgblue",
205
"45":"ansibgpurple",
206
"46":"ansibgcyan",
207
"47":"ansibggray"
208
};
209
210
function _process_numbers(attrs, numbers) {
211
// process ansi escapes
212
var n = numbers.shift();
213
if (ansi_colormap[n]) {
214
if ( ! attrs["class"] ) {
215
attrs["class"] = ansi_colormap[n];
216
} else {
217
attrs["class"] += " " + ansi_colormap[n];
218
}
219
} else if (n == "38" || n == "48") {
220
// VT100 256 color or 24 bit RGB
221
if (numbers.length < 2) {
222
console.log("Not enough fields for VT100 color", numbers);
223
return;
224
}
225
226
var index_or_rgb = numbers.shift();
227
var r,g,b;
228
if (index_or_rgb == "5") {
229
// 256 color
230
var idx = parseInt(numbers.shift());
231
if (idx < 16) {
232
// indexed ANSI
233
// ignore bright / non-bright distinction
234
idx = idx % 8;
235
var ansiclass = ansi_colormap[n[0] + (idx % 8).toString()];
236
if ( ! attrs["class"] ) {
237
attrs["class"] = ansiclass;
238
} else {
239
attrs["class"] += " " + ansiclass;
240
}
241
return;
242
} else if (idx < 232) {
243
// 216 color 6x6x6 RGB
244
idx = idx - 16;
245
b = idx % 6;
246
g = Math.floor(idx / 6) % 6;
247
r = Math.floor(idx / 36) % 6;
248
// convert to rgb
249
r = (r * 51);
250
g = (g * 51);
251
b = (b * 51);
252
} else {
253
// grayscale
254
idx = idx - 231;
255
// it's 1-24 and should *not* include black or white,
256
// so a 26 point scale
257
r = g = b = Math.floor(idx * 256 / 26);
258
}
259
} else if (index_or_rgb == "2") {
260
// Simple 24 bit RGB
261
if (numbers.length > 3) {
262
console.log("Not enough fields for RGB", numbers);
263
return;
264
}
265
r = numbers.shift();
266
g = numbers.shift();
267
b = numbers.shift();
268
} else {
269
console.log("unrecognized control", numbers);
270
return;
271
}
272
if (r !== undefined) {
273
// apply the rgb color
274
var line;
275
if (n == "38") {
276
line = "color: ";
277
} else {
278
line = "background-color: ";
279
}
280
line = line + "rgb(" + r + "," + g + "," + b + ");"
281
if ( !attrs["style"] ) {
282
attrs["style"] = line;
283
} else {
284
attrs["style"] += " " + line;
285
}
286
}
287
}
288
}
289
290
function ansispan(str) {
291
// ansispan function adapted from github.com/mmalecki/ansispan (MIT License)
292
// regular ansi escapes (using the table above)
293
return str.replace(/\033\[(0?[01]|22|39)?([;\d]+)?m/g, function(match, prefix, pattern) {
294
if (!pattern) {
295
// [(01|22|39|)m close spans
296
return "</span>";
297
}
298
// consume sequence of color escapes
299
var numbers = pattern.match(/\d+/g);
300
var attrs = {};
301
while (numbers.length > 0) {
302
_process_numbers(attrs, numbers);
303
}
304
305
var span = "<span ";
306
for (var attr in attrs) {
307
var value = attrs[attr];
308
span = span + " " + attr + '="' + attrs[attr] + '"';
309
}
310
return span + ">";
311
});
312
};
313
314
// Transform ANSI color escape codes into HTML <span> tags with css
315
// classes listed in the above ansi_colormap object. The actual color used
316
// are set in the css file.
317
function fixConsole(txt) {
318
txt = xmlencode(txt);
319
var re = /\033\[([\dA-Fa-f;]*?)m/;
320
var opened = false;
321
var cmds = [];
322
var opener = "";
323
var closer = "";
324
325
// Strip all ANSI codes that are not color related. Matches
326
// all ANSI codes that do not end with "m".
327
var ignored_re = /(?=(\033\[[\d;=]*[a-ln-zA-Z]{1}))\1(?!m)/g;
328
txt = txt.replace(ignored_re, "");
329
330
// color ansi codes
331
txt = ansispan(txt);
332
return txt;
333
}
334
335
// Remove chunks that should be overridden by the effect of
336
// carriage return characters
337
function fixCarriageReturn(txt) {
338
var tmp = txt;
339
do {
340
txt = tmp;
341
tmp = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
342
tmp = tmp.replace(/^.*\r+/gm, ''); // Other \r --> clear line
343
} while (tmp.length < txt.length);
344
return txt;
345
}
346
347
// Locate any URLs and convert them to a anchor tag
348
function autoLinkUrls(txt) {
349
return txt.replace(/(^|\s)(https?|ftp)(:[^'">\s]+)/gi,
350
"$1<a target=\"_blank\" href=\"$2$3\">$2$3</a>");
351
}
352
353
var points_to_pixels = function (points) {
354
// A reasonably good way of converting between points and pixels.
355
var test = $('<div style="display: none; width: 10000pt; padding:0; border:0;"></div>');
356
$(body).append(test);
357
var pixel_per_point = test.width()/10000;
358
test.remove();
359
return Math.floor(points*pixel_per_point);
360
};
361
362
var always_new = function (constructor) {
363
// wrapper around contructor to avoid requiring `var a = new constructor()`
364
// useful for passing constructors as callbacks,
365
// not for programmer laziness.
366
// from http://programmers.stackexchange.com/questions/118798
367
return function () {
368
var obj = Object.create(constructor.prototype);
369
constructor.apply(obj, arguments);
370
return obj;
371
};
372
};
373
374
var url_path_join = function () {
375
// join a sequence of url components with '/'
376
var url = '';
377
for (var i = 0; i < arguments.length; i++) {
378
if (arguments[i] === '') {
379
continue;
380
}
381
if (url.length > 0 && url[url.length-1] != '/') {
382
url = url + '/' + arguments[i];
383
} else {
384
url = url + arguments[i];
385
}
386
}
387
url = url.replace(/\/\/+/, '/');
388
return url;
389
};
390
391
var parse_url = function (url) {
392
// an `a` element with an href allows attr-access to the parsed segments of a URL
393
// a = parse_url("http://localhost:8888/path/name#hash")
394
// a.protocol = "http:"
395
// a.host = "localhost:8888"
396
// a.hostname = "localhost"
397
// a.port = 8888
398
// a.pathname = "/path/name"
399
// a.hash = "#hash"
400
var a = document.createElement("a");
401
a.href = url;
402
return a;
403
};
404
405
var encode_uri_components = function (uri) {
406
// encode just the components of a multi-segment uri,
407
// leaving '/' separators
408
return uri.split('/').map(encodeURIComponent).join('/');
409
};
410
411
var url_join_encode = function () {
412
// join a sequence of url components with '/',
413
// encoding each component with encodeURIComponent
414
return encode_uri_components(url_path_join.apply(null, arguments));
415
};
416
417
418
var splitext = function (filename) {
419
// mimic Python os.path.splitext
420
// Returns ['base', '.ext']
421
var idx = filename.lastIndexOf('.');
422
if (idx > 0) {
423
return [filename.slice(0, idx), filename.slice(idx)];
424
} else {
425
return [filename, ''];
426
}
427
};
428
429
430
var escape_html = function (text) {
431
// escape text to HTML
432
return $("<div/>").text(text).html();
433
}
434
435
436
var get_body_data = function(key) {
437
// get a url-encoded item from body.data and decode it
438
// we should never have any encoded URLs anywhere else in code
439
// until we are building an actual request
440
return decodeURIComponent($('body').data(key));
441
};
442
443
444
// http://stackoverflow.com/questions/2400935/browser-detection-in-javascript
445
var browser = (function() {
446
if (typeof navigator === 'undefined') {
447
// navigator undefined in node
448
return 'None';
449
}
450
var N= navigator.appName, ua= navigator.userAgent, tem;
451
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
452
if (M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
453
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
454
return M;
455
})();
456
457
// http://stackoverflow.com/questions/11219582/how-to-detect-my-browser-version-and-operating-system-using-javascript
458
var platform = (function () {
459
if (typeof navigator === 'undefined') {
460
// navigator undefined in node
461
return 'None';
462
}
463
var OSName="None";
464
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
465
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
466
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
467
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
468
return OSName
469
})();
470
471
var is_or_has = function (a, b) {
472
// Is b a child of a or a itself?
473
return a.has(b).length !==0 || a.is(b);
474
}
475
476
var is_focused = function (e) {
477
// Is element e, or one of its children focused?
478
e = $(e);
479
var target = $(document.activeElement);
480
if (target.length > 0) {
481
if (is_or_has(e, target)) {
482
return true;
483
} else {
484
return false;
485
}
486
} else {
487
return false;
488
}
489
}
490
491
var ajax_error_msg = function (jqXHR) {
492
// Return a JSON error message if there is one,
493
// otherwise the basic HTTP status text.
494
if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
495
return jqXHR.responseJSON.message;
496
} else {
497
return jqXHR.statusText;
498
}
499
}
500
var log_ajax_error = function (jqXHR, status, error) {
501
// log ajax failures with informative messages
502
var msg = "API request failed (" + jqXHR.status + "): ";
503
console.log(jqXHR);
504
msg += ajax_error_msg(jqXHR);
505
console.log(msg);
506
};
507
508
return {
509
regex_split : regex_split,
510
uuid : uuid,
511
fixConsole : fixConsole,
512
fixCarriageReturn : fixCarriageReturn,
513
autoLinkUrls : autoLinkUrls,
514
points_to_pixels : points_to_pixels,
515
get_body_data : get_body_data,
516
parse_url : parse_url,
517
url_path_join : url_path_join,
518
url_join_encode : url_join_encode,
519
encode_uri_components : encode_uri_components,
520
splitext : splitext,
521
escape_html : escape_html,
522
always_new : always_new,
523
browser : browser,
524
platform: platform,
525
is_or_has : is_or_has,
526
is_focused : is_focused,
527
ajax_error_msg : ajax_error_msg,
528
log_ajax_error : log_ajax_error,
529
};
530
531
}(IPython));
532
533
534