code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# zyc documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import zyc
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', 'recommonmark']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = {'.rst': 'restructuredtext', '.md': 'markdown'}
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'zyc'
copyright = u"2019, XESS Corp."
author = u"XESS Corp."
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = zyc.pckg_info.__version__
# The full version, including alpha/beta/rc tags.
release = zyc.pckg_info.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'zycdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'zyc.tex',
u'zyc Documentation',
u'XESS Corp.', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'zyc',
u'zyc Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'zyc',
u'zyc Documentation',
author,
'zyc',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# autodoc options.
autodoc_member_order = 'bysource'
autoclass_content = "both"
autodoc_default_flags = {"members", "undoc-members", "private-members", "special-members"}
autodoc_default_options = {"exclude-members": "__dict__, __module__, __weakref__"}
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/conf.py
|
conf.py
|
.. include:: ../HISTORY.rst
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/history.rst
|
history.rst
|
var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
VERSION: '1.0.0',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
BUILDER: 'singlehtml',
FILE_SUFFIX: '.html',
LINK_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt',
NAVIGATION_WITH_KEYS: false
};
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/documentation_options.js
|
documentation_options.js
|
/*
* doctools.js
* ~~~~~~~~~~~
*
* Sphinx JavaScript utilities for all documentation.
*
* :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
/**
* select a different prefix for underscore
*/
$u = _.noConflict();
/**
* make the code below compatible with browsers without
* an installed firebug like debugger
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
"profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {};
}
*/
/**
* small helper function to urldecode strings
*
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#Decoding_query_parameters_from_a_URL
*/
jQuery.urldecode = function(x) {
if (!x) {
return x
}
return decodeURIComponent(x.replace(/\+/g, ' '));
};
/**
* small helper function to urlencode strings
*/
jQuery.urlencode = encodeURIComponent;
/**
* This function returns the parsed url parameters of the
* current request. Multiple values per key are supported,
* it will always return arrays of strings for the value parts.
*/
jQuery.getQueryParameters = function(s) {
if (typeof s === 'undefined')
s = document.location.search;
var parts = s.substr(s.indexOf('?') + 1).split('&');
var result = {};
for (var i = 0; i < parts.length; i++) {
var tmp = parts[i].split('=', 2);
var key = jQuery.urldecode(tmp[0]);
var value = jQuery.urldecode(tmp[1]);
if (key in result)
result[key].push(value);
else
result[key] = [value];
}
return result;
};
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node, addItems) {
if (node.nodeType === 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 &&
!jQuery(node.parentNode).hasClass(className) &&
!jQuery(node.parentNode).hasClass("nohighlight")) {
var span;
var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg");
if (isInSVG) {
span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
} else {
span = document.createElement("span");
span.className = className;
}
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
if (isInSVG) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
var bbox = node.parentElement.getBBox();
rect.x.baseVal.value = bbox.x;
rect.y.baseVal.value = bbox.y;
rect.width.baseVal.value = bbox.width;
rect.height.baseVal.value = bbox.height;
rect.setAttribute('class', className);
addItems.push({
"parent": node.parentNode,
"target": rect});
}
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this, addItems);
});
}
}
var addItems = [];
var result = this.each(function() {
highlight(this, addItems);
});
for (var i = 0; i < addItems.length; ++i) {
jQuery(addItems[i].parent).before(addItems[i].target);
}
return result;
};
/*
* backward compatibility for jQuery.browser
* This will be supported until firefox bug is fixed.
*/
if (!jQuery.browser) {
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
jQuery.browser = {};
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}
/**
* Small JavaScript module for the documentation.
*/
var Documentation = {
init : function() {
this.fixFirefoxAnchorBug();
this.highlightSearchWords();
this.initIndexTable();
if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) {
this.initOnKeyListeners();
}
},
/**
* i18n support
*/
TRANSLATIONS : {},
PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; },
LOCALE : 'unknown',
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext : function(string) {
var translated = Documentation.TRANSLATIONS[string];
if (typeof translated === 'undefined')
return string;
return (typeof translated === 'string') ? translated : translated[0];
},
ngettext : function(singular, plural, n) {
var translated = Documentation.TRANSLATIONS[singular];
if (typeof translated === 'undefined')
return (n == 1) ? singular : plural;
return translated[Documentation.PLURALEXPR(n)];
},
addTranslations : function(catalog) {
for (var key in catalog.messages)
this.TRANSLATIONS[key] = catalog.messages[key];
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
this.LOCALE = catalog.locale;
},
/**
* add context elements like header anchor links
*/
addContextElements : function() {
$('div[id] > :header:first').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this headline')).
appendTo(this);
});
$('dt[id]').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this definition')).
appendTo(this);
});
},
/**
* workaround a firefox stupidity
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
*/
fixFirefoxAnchorBug : function() {
if (document.location.hash && $.browser.mozilla)
window.setTimeout(function() {
document.location.href += '';
}, 10);
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
.appendTo($('#searchbox'));
}
},
/**
* init the domain index toggle buttons
*/
initIndexTable : function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) === 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
},
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
},
/**
* make the url absolute
*/
makeURL : function(relativeURL) {
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
},
/**
* get the current relative url
*/
getCurrentURL : function() {
var path = document.location.pathname;
var parts = path.split(/\//);
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
if (this === '..')
parts.pop();
});
var url = parts.join('/');
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
},
initOnKeyListeners: function() {
$(document).keydown(function(event) {
var activeElementType = document.activeElement.tagName;
// don't navigate when in search box, textarea, dropdown or button
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT'
&& activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey
&& !event.shiftKey) {
switch (event.keyCode) {
case 37: // left
var prevHref = $('link[rel="prev"]').prop('href');
if (prevHref) {
window.location.href = prevHref;
return false;
}
break;
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
break;
}
}
});
}
};
// quick alias for translations
_ = Documentation.gettext;
$(document).ready(function() {
Documentation.init();
});
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/doctools.js
|
doctools.js
|
/*
* language_data.js
* ~~~~~~~~~~~~~~~~
*
* This script contains the language-specific data used by searchtools.js,
* namely the list of stopwords, stemmer, scorer and splitter.
*
* :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
/* Non-minified version is copied as a separate JS file, is available */
/**
* Porter Stemmer
*/
var Stemmer = function() {
var step2list = {
ational: 'ate',
tional: 'tion',
enci: 'ence',
anci: 'ance',
izer: 'ize',
bli: 'ble',
alli: 'al',
entli: 'ent',
eli: 'e',
ousli: 'ous',
ization: 'ize',
ation: 'ate',
ator: 'ate',
alism: 'al',
iveness: 'ive',
fulness: 'ful',
ousness: 'ous',
aliti: 'al',
iviti: 'ive',
biliti: 'ble',
logi: 'log'
};
var step3list = {
icate: 'ic',
ative: '',
alize: 'al',
iciti: 'ic',
ical: 'ic',
ful: '',
ness: ''
};
var c = "[^aeiou]"; // consonant
var v = "[aeiouy]"; // vowel
var C = c + "[^aeiouy]*"; // consonant sequence
var V = v + "[aeiou]*"; // vowel sequence
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
var s_v = "^(" + C + ")?" + v; // vowel in stem
this.stemWord = function (w) {
var stem;
var suffix;
var firstch;
var origword = w;
if (w.length < 3)
return w;
var re;
var re2;
var re3;
var re4;
firstch = w.substr(0,1);
if (firstch == "y")
w = firstch.toUpperCase() + w.substr(1);
// Step 1a
re = /^(.+?)(ss|i)es$/;
re2 = /^(.+?)([^s])s$/;
if (re.test(w))
w = w.replace(re,"$1$2");
else if (re2.test(w))
w = w.replace(re2,"$1$2");
// Step 1b
re = /^(.+?)eed$/;
re2 = /^(.+?)(ed|ing)$/;
if (re.test(w)) {
var fp = re.exec(w);
re = new RegExp(mgr0);
if (re.test(fp[1])) {
re = /.$/;
w = w.replace(re,"");
}
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
re2 = new RegExp(s_v);
if (re2.test(stem)) {
w = stem;
re2 = /(at|bl|iz)$/;
re3 = new RegExp("([^aeiouylsz])\\1$");
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re2.test(w))
w = w + "e";
else if (re3.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
else if (re4.test(w))
w = w + "e";
}
}
// Step 1c
re = /^(.+?)y$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(s_v);
if (re.test(stem))
w = stem + "i";
}
// Step 2
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step2list[suffix];
}
// Step 3
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step3list[suffix];
}
// Step 4
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
re2 = /^(.+?)(s|t)(ion)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
if (re.test(stem))
w = stem;
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1] + fp[2];
re2 = new RegExp(mgr1);
if (re2.test(stem))
w = stem;
}
// Step 5
re = /^(.+?)e$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
re2 = new RegExp(meq1);
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
w = stem;
}
re = /ll$/;
re2 = new RegExp(mgr1);
if (re.test(w) && re2.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
// and turn initial Y back to y
if (firstch == "y")
w = firstch.toLowerCase() + w.substr(1);
return w;
}
}
var splitChars = (function() {
var result = {};
var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648,
1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702,
2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971,
2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345,
3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761,
3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823,
4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125,
8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695,
11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587,
43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141];
var i, j, start, end;
for (i = 0; i < singles.length; i++) {
result[singles[i]] = true;
}
var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709],
[722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161],
[1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568],
[1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807],
[1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047],
[2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383],
[2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450],
[2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547],
[2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673],
[2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820],
[2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946],
[2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023],
[3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173],
[3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332],
[3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481],
[3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718],
[3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791],
[3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095],
[4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205],
[4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687],
[4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968],
[4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869],
[5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102],
[6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271],
[6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592],
[6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822],
[6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167],
[7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959],
[7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143],
[8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318],
[8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483],
[8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101],
[10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567],
[11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292],
[12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444],
[12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783],
[12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311],
[19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511],
[42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774],
[42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071],
[43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263],
[43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519],
[43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647],
[43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967],
[44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295],
[57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274],
[64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007],
[65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381],
[65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]];
for (i = 0; i < ranges.length; i++) {
start = ranges[i][0];
end = ranges[i][1];
for (j = start; j <= end; j++) {
result[j] = true;
}
}
return result;
})();
function splitQuery(query) {
var result = [];
var start = -1;
for (var i = 0; i < query.length; i++) {
if (splitChars[query.charCodeAt(i)]) {
if (start !== -1) {
result.push(query.slice(start, i));
start = -1;
}
} else if (start === -1) {
start = i;
}
}
if (start !== -1) {
result.push(query.slice(start));
}
return result;
}
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/language_data.js
|
language_data.js
|
!function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define("underscore",r):(n="undefined"!=typeof globalThis?globalThis:n||self,function(){var t=n._,e=n._=r();e.noConflict=function(){return n._=t,e}}())}(this,(function(){
// Underscore.js 1.13.1
// https://underscorejs.org
// (c) 2009-2021 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
var n="1.13.1",r="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},t=Array.prototype,e=Object.prototype,u="undefined"!=typeof Symbol?Symbol.prototype:null,o=t.push,i=t.slice,a=e.toString,f=e.hasOwnProperty,c="undefined"!=typeof ArrayBuffer,l="undefined"!=typeof DataView,s=Array.isArray,p=Object.keys,v=Object.create,h=c&&ArrayBuffer.isView,y=isNaN,d=isFinite,g=!{toString:null}.propertyIsEnumerable("toString"),b=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],m=Math.pow(2,53)-1;function j(n,r){return r=null==r?n.length-1:+r,function(){for(var t=Math.max(arguments.length-r,0),e=Array(t),u=0;u<t;u++)e[u]=arguments[u+r];switch(r){case 0:return n.call(this,e);case 1:return n.call(this,arguments[0],e);case 2:return n.call(this,arguments[0],arguments[1],e)}var o=Array(r+1);for(u=0;u<r;u++)o[u]=arguments[u];return o[r]=e,n.apply(this,o)}}function _(n){var r=typeof n;return"function"===r||"object"===r&&!!n}function w(n){return void 0===n}function A(n){return!0===n||!1===n||"[object Boolean]"===a.call(n)}function x(n){var r="[object "+n+"]";return function(n){return a.call(n)===r}}var S=x("String"),O=x("Number"),M=x("Date"),E=x("RegExp"),B=x("Error"),N=x("Symbol"),I=x("ArrayBuffer"),T=x("Function"),k=r.document&&r.document.childNodes;"function"!=typeof/./&&"object"!=typeof Int8Array&&"function"!=typeof k&&(T=function(n){return"function"==typeof n||!1});var D=T,R=x("Object"),F=l&&R(new DataView(new ArrayBuffer(8))),V="undefined"!=typeof Map&&R(new Map),P=x("DataView");var q=F?function(n){return null!=n&&D(n.getInt8)&&I(n.buffer)}:P,U=s||x("Array");function W(n,r){return null!=n&&f.call(n,r)}var z=x("Arguments");!function(){z(arguments)||(z=function(n){return W(n,"callee")})}();var L=z;function $(n){return O(n)&&y(n)}function C(n){return function(){return n}}function K(n){return function(r){var t=n(r);return"number"==typeof t&&t>=0&&t<=m}}function J(n){return function(r){return null==r?void 0:r[n]}}var G=J("byteLength"),H=K(G),Q=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var X=c?function(n){return h?h(n)&&!q(n):H(n)&&Q.test(a.call(n))}:C(!1),Y=J("length");function Z(n,r){r=function(n){for(var r={},t=n.length,e=0;e<t;++e)r[n[e]]=!0;return{contains:function(n){return r[n]},push:function(t){return r[t]=!0,n.push(t)}}}(r);var t=b.length,u=n.constructor,o=D(u)&&u.prototype||e,i="constructor";for(W(n,i)&&!r.contains(i)&&r.push(i);t--;)(i=b[t])in n&&n[i]!==o[i]&&!r.contains(i)&&r.push(i)}function nn(n){if(!_(n))return[];if(p)return p(n);var r=[];for(var t in n)W(n,t)&&r.push(t);return g&&Z(n,r),r}function rn(n,r){var t=nn(r),e=t.length;if(null==n)return!e;for(var u=Object(n),o=0;o<e;o++){var i=t[o];if(r[i]!==u[i]||!(i in u))return!1}return!0}function tn(n){return n instanceof tn?n:this instanceof tn?void(this._wrapped=n):new tn(n)}function en(n){return new Uint8Array(n.buffer||n,n.byteOffset||0,G(n))}tn.VERSION=n,tn.prototype.value=function(){return this._wrapped},tn.prototype.valueOf=tn.prototype.toJSON=tn.prototype.value,tn.prototype.toString=function(){return String(this._wrapped)};var un="[object DataView]";function on(n,r,t,e){if(n===r)return 0!==n||1/n==1/r;if(null==n||null==r)return!1;if(n!=n)return r!=r;var o=typeof n;return("function"===o||"object"===o||"object"==typeof r)&&function n(r,t,e,o){r instanceof tn&&(r=r._wrapped);t instanceof tn&&(t=t._wrapped);var i=a.call(r);if(i!==a.call(t))return!1;if(F&&"[object Object]"==i&&q(r)){if(!q(t))return!1;i=un}switch(i){case"[object RegExp]":case"[object String]":return""+r==""+t;case"[object Number]":return+r!=+r?+t!=+t:0==+r?1/+r==1/t:+r==+t;case"[object Date]":case"[object Boolean]":return+r==+t;case"[object Symbol]":return u.valueOf.call(r)===u.valueOf.call(t);case"[object ArrayBuffer]":case un:return n(en(r),en(t),e,o)}var f="[object Array]"===i;if(!f&&X(r)){if(G(r)!==G(t))return!1;if(r.buffer===t.buffer&&r.byteOffset===t.byteOffset)return!0;f=!0}if(!f){if("object"!=typeof r||"object"!=typeof t)return!1;var c=r.constructor,l=t.constructor;if(c!==l&&!(D(c)&&c instanceof c&&D(l)&&l instanceof l)&&"constructor"in r&&"constructor"in t)return!1}o=o||[];var s=(e=e||[]).length;for(;s--;)if(e[s]===r)return o[s]===t;if(e.push(r),o.push(t),f){if((s=r.length)!==t.length)return!1;for(;s--;)if(!on(r[s],t[s],e,o))return!1}else{var p,v=nn(r);if(s=v.length,nn(t).length!==s)return!1;for(;s--;)if(p=v[s],!W(t,p)||!on(r[p],t[p],e,o))return!1}return e.pop(),o.pop(),!0}(n,r,t,e)}function an(n){if(!_(n))return[];var r=[];for(var t in n)r.push(t);return g&&Z(n,r),r}function fn(n){var r=Y(n);return function(t){if(null==t)return!1;var e=an(t);if(Y(e))return!1;for(var u=0;u<r;u++)if(!D(t[n[u]]))return!1;return n!==hn||!D(t[cn])}}var cn="forEach",ln="has",sn=["clear","delete"],pn=["get",ln,"set"],vn=sn.concat(cn,pn),hn=sn.concat(pn),yn=["add"].concat(sn,cn,ln),dn=V?fn(vn):x("Map"),gn=V?fn(hn):x("WeakMap"),bn=V?fn(yn):x("Set"),mn=x("WeakSet");function jn(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=n[r[u]];return e}function _n(n){for(var r={},t=nn(n),e=0,u=t.length;e<u;e++)r[n[t[e]]]=t[e];return r}function wn(n){var r=[];for(var t in n)D(n[t])&&r.push(t);return r.sort()}function An(n,r){return function(t){var e=arguments.length;if(r&&(t=Object(t)),e<2||null==t)return t;for(var u=1;u<e;u++)for(var o=arguments[u],i=n(o),a=i.length,f=0;f<a;f++){var c=i[f];r&&void 0!==t[c]||(t[c]=o[c])}return t}}var xn=An(an),Sn=An(nn),On=An(an,!0);function Mn(n){if(!_(n))return{};if(v)return v(n);var r=function(){};r.prototype=n;var t=new r;return r.prototype=null,t}function En(n){return _(n)?U(n)?n.slice():xn({},n):n}function Bn(n){return U(n)?n:[n]}function Nn(n){return tn.toPath(n)}function In(n,r){for(var t=r.length,e=0;e<t;e++){if(null==n)return;n=n[r[e]]}return t?n:void 0}function Tn(n,r,t){var e=In(n,Nn(r));return w(e)?t:e}function kn(n){return n}function Dn(n){return n=Sn({},n),function(r){return rn(r,n)}}function Rn(n){return n=Nn(n),function(r){return In(r,n)}}function Fn(n,r,t){if(void 0===r)return n;switch(null==t?3:t){case 1:return function(t){return n.call(r,t)};case 3:return function(t,e,u){return n.call(r,t,e,u)};case 4:return function(t,e,u,o){return n.call(r,t,e,u,o)}}return function(){return n.apply(r,arguments)}}function Vn(n,r,t){return null==n?kn:D(n)?Fn(n,r,t):_(n)&&!U(n)?Dn(n):Rn(n)}function Pn(n,r){return Vn(n,r,1/0)}function qn(n,r,t){return tn.iteratee!==Pn?tn.iteratee(n,r):Vn(n,r,t)}function Un(){}function Wn(n,r){return null==r&&(r=n,n=0),n+Math.floor(Math.random()*(r-n+1))}tn.toPath=Bn,tn.iteratee=Pn;var zn=Date.now||function(){return(new Date).getTime()};function Ln(n){var r=function(r){return n[r]},t="(?:"+nn(n).join("|")+")",e=RegExp(t),u=RegExp(t,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,r):n}}var $n={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Cn=Ln($n),Kn=Ln(_n($n)),Jn=tn.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Gn=/(.)^/,Hn={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Qn=/\\|'|\r|\n|\u2028|\u2029/g;function Xn(n){return"\\"+Hn[n]}var Yn=/^\s*(\w|\$)+\s*$/;var Zn=0;function nr(n,r,t,e,u){if(!(e instanceof r))return n.apply(t,u);var o=Mn(n.prototype),i=n.apply(o,u);return _(i)?i:o}var rr=j((function(n,r){var t=rr.placeholder,e=function(){for(var u=0,o=r.length,i=Array(o),a=0;a<o;a++)i[a]=r[a]===t?arguments[u++]:r[a];for(;u<arguments.length;)i.push(arguments[u++]);return nr(n,e,this,this,i)};return e}));rr.placeholder=tn;var tr=j((function(n,r,t){if(!D(n))throw new TypeError("Bind must be called on a function");var e=j((function(u){return nr(n,e,r,this,t.concat(u))}));return e})),er=K(Y);function ur(n,r,t,e){if(e=e||[],r||0===r){if(r<=0)return e.concat(n)}else r=1/0;for(var u=e.length,o=0,i=Y(n);o<i;o++){var a=n[o];if(er(a)&&(U(a)||L(a)))if(r>1)ur(a,r-1,t,e),u=e.length;else for(var f=0,c=a.length;f<c;)e[u++]=a[f++];else t||(e[u++]=a)}return e}var or=j((function(n,r){var t=(r=ur(r,!1,!1)).length;if(t<1)throw new Error("bindAll must be passed function names");for(;t--;){var e=r[t];n[e]=tr(n[e],n)}return n}));var ir=j((function(n,r,t){return setTimeout((function(){return n.apply(null,t)}),r)})),ar=rr(ir,tn,1);function fr(n){return function(){return!n.apply(this,arguments)}}function cr(n,r){var t;return function(){return--n>0&&(t=r.apply(this,arguments)),n<=1&&(r=null),t}}var lr=rr(cr,2);function sr(n,r,t){r=qn(r,t);for(var e,u=nn(n),o=0,i=u.length;o<i;o++)if(r(n[e=u[o]],e,n))return e}function pr(n){return function(r,t,e){t=qn(t,e);for(var u=Y(r),o=n>0?0:u-1;o>=0&&o<u;o+=n)if(t(r[o],o,r))return o;return-1}}var vr=pr(1),hr=pr(-1);function yr(n,r,t,e){for(var u=(t=qn(t,e,1))(r),o=0,i=Y(n);o<i;){var a=Math.floor((o+i)/2);t(n[a])<u?o=a+1:i=a}return o}function dr(n,r,t){return function(e,u,o){var a=0,f=Y(e);if("number"==typeof o)n>0?a=o>=0?o:Math.max(o+f,a):f=o>=0?Math.min(o+1,f):o+f+1;else if(t&&o&&f)return e[o=t(e,u)]===u?o:-1;if(u!=u)return(o=r(i.call(e,a,f),$))>=0?o+a:-1;for(o=n>0?a:f-1;o>=0&&o<f;o+=n)if(e[o]===u)return o;return-1}}var gr=dr(1,vr,yr),br=dr(-1,hr);function mr(n,r,t){var e=(er(n)?vr:sr)(n,r,t);if(void 0!==e&&-1!==e)return n[e]}function jr(n,r,t){var e,u;if(r=Fn(r,t),er(n))for(e=0,u=n.length;e<u;e++)r(n[e],e,n);else{var o=nn(n);for(e=0,u=o.length;e<u;e++)r(n[o[e]],o[e],n)}return n}function _r(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=Array(u),i=0;i<u;i++){var a=e?e[i]:i;o[i]=r(n[a],a,n)}return o}function wr(n){var r=function(r,t,e,u){var o=!er(r)&&nn(r),i=(o||r).length,a=n>0?0:i-1;for(u||(e=r[o?o[a]:a],a+=n);a>=0&&a<i;a+=n){var f=o?o[a]:a;e=t(e,r[f],f,r)}return e};return function(n,t,e,u){var o=arguments.length>=3;return r(n,Fn(t,u,4),e,o)}}var Ar=wr(1),xr=wr(-1);function Sr(n,r,t){var e=[];return r=qn(r,t),jr(n,(function(n,t,u){r(n,t,u)&&e.push(n)})),e}function Or(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(!r(n[i],i,n))return!1}return!0}function Mr(n,r,t){r=qn(r,t);for(var e=!er(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(r(n[i],i,n))return!0}return!1}function Er(n,r,t,e){return er(n)||(n=jn(n)),("number"!=typeof t||e)&&(t=0),gr(n,r,t)>=0}var Br=j((function(n,r,t){var e,u;return D(r)?u=r:(r=Nn(r),e=r.slice(0,-1),r=r[r.length-1]),_r(n,(function(n){var o=u;if(!o){if(e&&e.length&&(n=In(n,e)),null==n)return;o=n[r]}return null==o?o:o.apply(n,t)}))}));function Nr(n,r){return _r(n,Rn(r))}function Ir(n,r,t){var e,u,o=-1/0,i=-1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=er(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e>o&&(o=e);else r=qn(r,t),jr(n,(function(n,t,e){((u=r(n,t,e))>i||u===-1/0&&o===-1/0)&&(o=n,i=u)}));return o}function Tr(n,r,t){if(null==r||t)return er(n)||(n=jn(n)),n[Wn(n.length-1)];var e=er(n)?En(n):jn(n),u=Y(e);r=Math.max(Math.min(r,u),0);for(var o=u-1,i=0;i<r;i++){var a=Wn(i,o),f=e[i];e[i]=e[a],e[a]=f}return e.slice(0,r)}function kr(n,r){return function(t,e,u){var o=r?[[],[]]:{};return e=qn(e,u),jr(t,(function(r,u){var i=e(r,u,t);n(o,r,i)})),o}}var Dr=kr((function(n,r,t){W(n,t)?n[t].push(r):n[t]=[r]})),Rr=kr((function(n,r,t){n[t]=r})),Fr=kr((function(n,r,t){W(n,t)?n[t]++:n[t]=1})),Vr=kr((function(n,r,t){n[t?0:1].push(r)}),!0),Pr=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function qr(n,r,t){return r in t}var Ur=j((function(n,r){var t={},e=r[0];if(null==n)return t;D(e)?(r.length>1&&(e=Fn(e,r[1])),r=an(n)):(e=qr,r=ur(r,!1,!1),n=Object(n));for(var u=0,o=r.length;u<o;u++){var i=r[u],a=n[i];e(a,i,n)&&(t[i]=a)}return t})),Wr=j((function(n,r){var t,e=r[0];return D(e)?(e=fr(e),r.length>1&&(t=r[1])):(r=_r(ur(r,!1,!1),String),e=function(n,t){return!Er(r,t)}),Ur(n,e,t)}));function zr(n,r,t){return i.call(n,0,Math.max(0,n.length-(null==r||t?1:r)))}function Lr(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[0]:zr(n,n.length-r)}function $r(n,r,t){return i.call(n,null==r||t?1:r)}var Cr=j((function(n,r){return r=ur(r,!0,!0),Sr(n,(function(n){return!Er(r,n)}))})),Kr=j((function(n,r){return Cr(n,r)}));function Jr(n,r,t,e){A(r)||(e=t,t=r,r=!1),null!=t&&(t=qn(t,e));for(var u=[],o=[],i=0,a=Y(n);i<a;i++){var f=n[i],c=t?t(f,i,n):f;r&&!t?(i&&o===c||u.push(f),o=c):t?Er(o,c)||(o.push(c),u.push(f)):Er(u,f)||u.push(f)}return u}var Gr=j((function(n){return Jr(ur(n,!0,!0))}));function Hr(n){for(var r=n&&Ir(n,Y).length||0,t=Array(r),e=0;e<r;e++)t[e]=Nr(n,e);return t}var Qr=j(Hr);function Xr(n,r){return n._chain?tn(r).chain():r}function Yr(n){return jr(wn(n),(function(r){var t=tn[r]=n[r];tn.prototype[r]=function(){var n=[this._wrapped];return o.apply(n,arguments),Xr(this,t.apply(tn,n))}})),tn}jr(["pop","push","reverse","shift","sort","splice","unshift"],(function(n){var r=t[n];tn.prototype[n]=function(){var t=this._wrapped;return null!=t&&(r.apply(t,arguments),"shift"!==n&&"splice"!==n||0!==t.length||delete t[0]),Xr(this,t)}})),jr(["concat","join","slice"],(function(n){var r=t[n];tn.prototype[n]=function(){var n=this._wrapped;return null!=n&&(n=r.apply(n,arguments)),Xr(this,n)}}));var Zr=Yr({__proto__:null,VERSION:n,restArguments:j,isObject:_,isNull:function(n){return null===n},isUndefined:w,isBoolean:A,isElement:function(n){return!(!n||1!==n.nodeType)},isString:S,isNumber:O,isDate:M,isRegExp:E,isError:B,isSymbol:N,isArrayBuffer:I,isDataView:q,isArray:U,isFunction:D,isArguments:L,isFinite:function(n){return!N(n)&&d(n)&&!isNaN(parseFloat(n))},isNaN:$,isTypedArray:X,isEmpty:function(n){if(null==n)return!0;var r=Y(n);return"number"==typeof r&&(U(n)||S(n)||L(n))?0===r:0===Y(nn(n))},isMatch:rn,isEqual:function(n,r){return on(n,r)},isMap:dn,isWeakMap:gn,isSet:bn,isWeakSet:mn,keys:nn,allKeys:an,values:jn,pairs:function(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=[r[u],n[r[u]]];return e},invert:_n,functions:wn,methods:wn,extend:xn,extendOwn:Sn,assign:Sn,defaults:On,create:function(n,r){var t=Mn(n);return r&&Sn(t,r),t},clone:En,tap:function(n,r){return r(n),n},get:Tn,has:function(n,r){for(var t=(r=Nn(r)).length,e=0;e<t;e++){var u=r[e];if(!W(n,u))return!1;n=n[u]}return!!t},mapObject:function(n,r,t){r=qn(r,t);for(var e=nn(n),u=e.length,o={},i=0;i<u;i++){var a=e[i];o[a]=r(n[a],a,n)}return o},identity:kn,constant:C,noop:Un,toPath:Bn,property:Rn,propertyOf:function(n){return null==n?Un:function(r){return Tn(n,r)}},matcher:Dn,matches:Dn,times:function(n,r,t){var e=Array(Math.max(0,n));r=Fn(r,t,1);for(var u=0;u<n;u++)e[u]=r(u);return e},random:Wn,now:zn,escape:Cn,unescape:Kn,templateSettings:Jn,template:function(n,r,t){!r&&t&&(r=t),r=On({},r,tn.templateSettings);var e=RegExp([(r.escape||Gn).source,(r.interpolate||Gn).source,(r.evaluate||Gn).source].join("|")+"|$","g"),u=0,o="__p+='";n.replace(e,(function(r,t,e,i,a){return o+=n.slice(u,a).replace(Qn,Xn),u=a+r.length,t?o+="'+\n((__t=("+t+"))==null?'':_.escape(__t))+\n'":e?o+="'+\n((__t=("+e+"))==null?'':__t)+\n'":i&&(o+="';\n"+i+"\n__p+='"),r})),o+="';\n";var i,a=r.variable;if(a){if(!Yn.test(a))throw new Error("variable is not a bare identifier: "+a)}else o="with(obj||{}){\n"+o+"}\n",a="obj";o="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{i=new Function(a,"_",o)}catch(n){throw n.source=o,n}var f=function(n){return i.call(this,n,tn)};return f.source="function("+a+"){\n"+o+"}",f},result:function(n,r,t){var e=(r=Nn(r)).length;if(!e)return D(t)?t.call(n):t;for(var u=0;u<e;u++){var o=null==n?void 0:n[r[u]];void 0===o&&(o=t,u=e),n=D(o)?o.call(n):o}return n},uniqueId:function(n){var r=++Zn+"";return n?n+r:r},chain:function(n){var r=tn(n);return r._chain=!0,r},iteratee:Pn,partial:rr,bind:tr,bindAll:or,memoize:function(n,r){var t=function(e){var u=t.cache,o=""+(r?r.apply(this,arguments):e);return W(u,o)||(u[o]=n.apply(this,arguments)),u[o]};return t.cache={},t},delay:ir,defer:ar,throttle:function(n,r,t){var e,u,o,i,a=0;t||(t={});var f=function(){a=!1===t.leading?0:zn(),e=null,i=n.apply(u,o),e||(u=o=null)},c=function(){var c=zn();a||!1!==t.leading||(a=c);var l=r-(c-a);return u=this,o=arguments,l<=0||l>r?(e&&(clearTimeout(e),e=null),a=c,i=n.apply(u,o),e||(u=o=null)):e||!1===t.trailing||(e=setTimeout(f,l)),i};return c.cancel=function(){clearTimeout(e),a=0,e=u=o=null},c},debounce:function(n,r,t){var e,u,o,i,a,f=function(){var c=zn()-u;r>c?e=setTimeout(f,r-c):(e=null,t||(i=n.apply(a,o)),e||(o=a=null))},c=j((function(c){return a=this,o=c,u=zn(),e||(e=setTimeout(f,r),t&&(i=n.apply(a,o))),i}));return c.cancel=function(){clearTimeout(e),e=o=a=null},c},wrap:function(n,r){return rr(r,n)},negate:fr,compose:function(){var n=arguments,r=n.length-1;return function(){for(var t=r,e=n[r].apply(this,arguments);t--;)e=n[t].call(this,e);return e}},after:function(n,r){return function(){if(--n<1)return r.apply(this,arguments)}},before:cr,once:lr,findKey:sr,findIndex:vr,findLastIndex:hr,sortedIndex:yr,indexOf:gr,lastIndexOf:br,find:mr,detect:mr,findWhere:function(n,r){return mr(n,Dn(r))},each:jr,forEach:jr,map:_r,collect:_r,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:xr,foldr:xr,filter:Sr,select:Sr,reject:function(n,r,t){return Sr(n,fr(qn(r)),t)},every:Or,all:Or,some:Mr,any:Mr,contains:Er,includes:Er,include:Er,invoke:Br,pluck:Nr,where:function(n,r){return Sr(n,Dn(r))},max:Ir,min:function(n,r,t){var e,u,o=1/0,i=1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=er(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e<o&&(o=e);else r=qn(r,t),jr(n,(function(n,t,e){((u=r(n,t,e))<i||u===1/0&&o===1/0)&&(o=n,i=u)}));return o},shuffle:function(n){return Tr(n,1/0)},sample:Tr,sortBy:function(n,r,t){var e=0;return r=qn(r,t),Nr(_r(n,(function(n,t,u){return{value:n,index:e++,criteria:r(n,t,u)}})).sort((function(n,r){var t=n.criteria,e=r.criteria;if(t!==e){if(t>e||void 0===t)return 1;if(t<e||void 0===e)return-1}return n.index-r.index})),"value")},groupBy:Dr,indexBy:Rr,countBy:Fr,partition:Vr,toArray:function(n){return n?U(n)?i.call(n):S(n)?n.match(Pr):er(n)?_r(n,kn):jn(n):[]},size:function(n){return null==n?0:er(n)?n.length:nn(n).length},pick:Ur,omit:Wr,first:Lr,head:Lr,take:Lr,initial:zr,last:function(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[n.length-1]:$r(n,Math.max(0,n.length-r))},rest:$r,tail:$r,drop:$r,compact:function(n){return Sr(n,Boolean)},flatten:function(n,r){return ur(n,r,!1)},without:Kr,uniq:Jr,unique:Jr,union:Gr,intersection:function(n){for(var r=[],t=arguments.length,e=0,u=Y(n);e<u;e++){var o=n[e];if(!Er(r,o)){var i;for(i=1;i<t&&Er(arguments[i],o);i++);i===t&&r.push(o)}}return r},difference:Cr,unzip:Hr,transpose:Hr,zip:Qr,object:function(n,r){for(var t={},e=0,u=Y(n);e<u;e++)r?t[n[e]]=r[e]:t[n[e][0]]=n[e][1];return t},range:function(n,r,t){null==r&&(r=n||0,n=0),t||(t=r<n?-1:1);for(var e=Math.max(Math.ceil((r-n)/t),0),u=Array(e),o=0;o<e;o++,n+=t)u[o]=n;return u},chunk:function(n,r){if(null==r||r<1)return[];for(var t=[],e=0,u=n.length;e<u;)t.push(i.call(n,e,e+=r));return t},mixin:Yr,default:tn});return Zr._=Zr,Zr}));
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/underscore.js
|
underscore.js
|
// Underscore.js 1.3.1
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
// Current version.
_.VERSION = '1.3.1';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = _.toArray(obj).reverse();
if (context && !initial) iterator = _.bind(iterator, context);
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
found = any(obj, function(value) {
return value === target;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var shuffled = [], rand;
each(obj, function(value, index, list) {
if (index == 0) {
shuffled[0] = value;
} else {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
}
});
return shuffled;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, val) {
var result = {};
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especcialy useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var result = [];
_.reduce(initial, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
memo[memo.length] = el;
result[result.length] = array[i];
}
return memo;
}, []);
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = _.flatten(slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.include(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (i in array && array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
func.apply(context, args);
}
whenDone();
throttling = true;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments, 0));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function.
function eq(a, b, stack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
// Objects with different constructors are not equivalent.
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
stack.pop();
return result;
}
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return toString.call(obj) == '[object Arguments]';
};
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Is a given value a function?
_.isFunction = function(obj) {
return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
return toString.call(obj) == '[object Number]';
};
// Is the given value `NaN`?
_.isNaN = function(obj) {
// `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value a date?
_.isDate = function(obj) {
return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Has own property?
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Escape a string for HTML interpolation.
_.escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /.^/;
// Within an interpolation, evaluation, or escaping, remove HTML escaping
// that had been previously added.
var unescape = function(code) {
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.escape || noMatch, function(match, code) {
return "',_.escape(" + unescape(code) + "),'";
})
.replace(c.interpolate || noMatch, function(match, code) {
return "'," + unescape(code) + ",'";
})
.replace(c.evaluate || noMatch, function(match, code) {
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', '_', tmpl);
if (data) return func(data, _);
return function(data) {
return func.call(this, data, _);
};
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
var wrapped = this._wrapped;
method.apply(wrapped, arguments);
var length = wrapped.length;
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
return result(wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
}).call(this);
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/underscore-1.3.1.js
|
underscore-1.3.1.js
|
/*
* searchtools.js
* ~~~~~~~~~~~~~~~~
*
* Sphinx JavaScript utilities for the full-text search.
*
* :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
if (!Scorer) {
/**
* Simple result scoring code.
*/
var Scorer = {
// Implement the following function to further tweak the score for each result
// The function takes a result array [filename, title, anchor, descr, score]
// and returns the new score.
/*
score: function(result) {
return result[4];
},
*/
// query matches the full name of an object
objNameMatch: 11,
// or matches in the last dotted part of the object name
objPartialMatch: 6,
// Additive scores depending on the priority of the object
objPrio: {0: 15, // used to be importantResults
1: 5, // used to be objectResults
2: -5}, // used to be unimportantResults
// Used when the priority is not in the mapping.
objPrioDefault: 0,
// query found in title
title: 15,
partialTitle: 7,
// query found in terms
term: 5,
partialTerm: 2
};
}
if (!splitQuery) {
function splitQuery(query) {
return query.split(/\s+/);
}
}
/**
* Search Module
*/
var Search = {
_index : null,
_queued_query : null,
_pulse_status : -1,
htmlToText : function(htmlString) {
var virtualDocument = document.implementation.createHTMLDocument('virtual');
var htmlElement = $(htmlString, virtualDocument);
htmlElement.find('.headerlink').remove();
docContent = htmlElement.find('[role=main]')[0];
if(docContent === undefined) {
console.warn("Content block not found. Sphinx search tries to obtain it " +
"via '[role=main]'. Could you check your theme or template.");
return "";
}
return docContent.textContent || docContent.innerText;
},
init : function() {
var params = $.getQueryParameters();
if (params.q) {
var query = params.q[0];
$('input[name="q"]')[0].value = query;
this.performSearch(query);
}
},
loadIndex : function(url) {
$.ajax({type: "GET", url: url, data: null,
dataType: "script", cache: true,
complete: function(jqxhr, textstatus) {
if (textstatus != "success") {
document.getElementById("searchindexloader").src = url;
}
}});
},
setIndex : function(index) {
var q;
this._index = index;
if ((q = this._queued_query) !== null) {
this._queued_query = null;
Search.query(q);
}
},
hasIndex : function() {
return this._index !== null;
},
deferQuery : function(query) {
this._queued_query = query;
},
stopPulse : function() {
this._pulse_status = 0;
},
startPulse : function() {
if (this._pulse_status >= 0)
return;
function pulse() {
var i;
Search._pulse_status = (Search._pulse_status + 1) % 4;
var dotString = '';
for (i = 0; i < Search._pulse_status; i++)
dotString += '.';
Search.dots.text(dotString);
if (Search._pulse_status > -1)
window.setTimeout(pulse, 500);
}
pulse();
},
/**
* perform a search for something (or wait until index is loaded)
*/
performSearch : function(query) {
// create the required interface elements
this.out = $('#search-results');
this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
this.dots = $('<span></span>').appendTo(this.title);
this.status = $('<p class="search-summary"> </p>').appendTo(this.out);
this.output = $('<ul class="search"/>').appendTo(this.out);
$('#search-progress').text(_('Preparing search...'));
this.startPulse();
// index already loaded, the browser was quick!
if (this.hasIndex())
this.query(query);
else
this.deferQuery(query);
},
/**
* execute search (requires search index to be loaded)
*/
query : function(query) {
var i;
// stem the searchterms and add them to the correct list
var stemmer = new Stemmer();
var searchterms = [];
var excluded = [];
var hlterms = [];
var tmp = splitQuery(query);
var objectterms = [];
for (i = 0; i < tmp.length; i++) {
if (tmp[i] !== "") {
objectterms.push(tmp[i].toLowerCase());
}
if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i] === "") {
// skip this "word"
continue;
}
// stem the word
var word = stemmer.stemWord(tmp[i].toLowerCase());
// prevent stemmer from cutting word smaller than two chars
if(word.length < 3 && tmp[i].length >= 3) {
word = tmp[i];
}
var toAppend;
// select the correct list
if (word[0] == '-') {
toAppend = excluded;
word = word.substr(1);
}
else {
toAppend = searchterms;
hlterms.push(tmp[i].toLowerCase());
}
// only add if not already in the list
if (!$u.contains(toAppend, word))
toAppend.push(word);
}
var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
// console.debug('SEARCH: searching for:');
// console.info('required: ', searchterms);
// console.info('excluded: ', excluded);
// prepare search
var terms = this._index.terms;
var titleterms = this._index.titleterms;
// array of [filename, title, anchor, descr, score]
var results = [];
$('#search-progress').empty();
// lookup as object
for (i = 0; i < objectterms.length; i++) {
var others = [].concat(objectterms.slice(0, i),
objectterms.slice(i+1, objectterms.length));
results = results.concat(this.performObjectSearch(objectterms[i], others));
}
// lookup as search terms in fulltext
results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
// let the scorer override scores with a custom scoring function
if (Scorer.score) {
for (i = 0; i < results.length; i++)
results[i][4] = Scorer.score(results[i]);
}
// now sort the results by score (in opposite order of appearance, since the
// display function below uses pop() to retrieve items) and then
// alphabetically
results.sort(function(a, b) {
var left = a[4];
var right = b[4];
if (left > right) {
return 1;
} else if (left < right) {
return -1;
} else {
// same score: sort alphabetically
left = a[1].toLowerCase();
right = b[1].toLowerCase();
return (left > right) ? -1 : ((left < right) ? 1 : 0);
}
});
// for debugging
//Search.lastresults = results.slice(); // a copy
//console.info('search results:', Search.lastresults);
// print the results
var resultCount = results.length;
function displayNextItem() {
// results left, load the summary and display it
if (results.length) {
var item = results.pop();
var listItem = $('<li></li>');
var requestUrl = "";
var linkUrl = "";
if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {
// dirhtml builder
var dirname = item[0] + '/';
if (dirname.match(/\/index\/$/)) {
dirname = dirname.substring(0, dirname.length-6);
} else if (dirname == 'index/') {
dirname = '';
}
requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;
linkUrl = requestUrl;
} else {
// normal html builders
requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;
linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX;
}
listItem.append($('<a/>').attr('href',
linkUrl +
highlightstring + item[2]).html(item[1]));
if (item[3]) {
listItem.append($('<span> (' + item[3] + ')</span>'));
Search.output.append(listItem);
setTimeout(function() {
displayNextItem();
}, 5);
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
$.ajax({url: requestUrl,
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
if (data !== '' && data !== undefined) {
listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
}
Search.output.append(listItem);
setTimeout(function() {
displayNextItem();
}, 5);
}});
} else {
// no source available, just display title
Search.output.append(listItem);
setTimeout(function() {
displayNextItem();
}, 5);
}
}
// search finished, update title and status message
else {
Search.stopPulse();
Search.title.text(_('Search Results'));
if (!resultCount)
Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
else
Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
Search.status.fadeIn(500);
}
}
displayNextItem();
},
/**
* search for object names
*/
performObjectSearch : function(object, otherterms) {
var filenames = this._index.filenames;
var docnames = this._index.docnames;
var objects = this._index.objects;
var objnames = this._index.objnames;
var titles = this._index.titles;
var i;
var results = [];
for (var prefix in objects) {
for (var name in objects[prefix]) {
var fullname = (prefix ? prefix + '.' : '') + name;
var fullnameLower = fullname.toLowerCase()
if (fullnameLower.indexOf(object) > -1) {
var score = 0;
var parts = fullnameLower.split('.');
// check for different match types: exact matches of full name or
// "last name" (i.e. last dotted part)
if (fullnameLower == object || parts[parts.length - 1] == object) {
score += Scorer.objNameMatch;
// matches in last name
} else if (parts[parts.length - 1].indexOf(object) > -1) {
score += Scorer.objPartialMatch;
}
var match = objects[prefix][name];
var objname = objnames[match[1]][2];
var title = titles[match[0]];
// If more than one term searched for, we require other words to be
// found in the name/title/description
if (otherterms.length > 0) {
var haystack = (prefix + ' ' + name + ' ' +
objname + ' ' + title).toLowerCase();
var allfound = true;
for (i = 0; i < otherterms.length; i++) {
if (haystack.indexOf(otherterms[i]) == -1) {
allfound = false;
break;
}
}
if (!allfound) {
continue;
}
}
var descr = objname + _(', in ') + title;
var anchor = match[3];
if (anchor === '')
anchor = fullname;
else if (anchor == '-')
anchor = objnames[match[1]][1] + '-' + fullname;
// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2])) {
score += Scorer.objPrio[match[2]];
} else {
score += Scorer.objPrioDefault;
}
results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
}
}
}
return results;
},
/**
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
*/
escapeRegExp : function(string) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
},
/**
* search for full-text terms in the index
*/
performTermsSearch : function(searchterms, excluded, terms, titleterms) {
var docnames = this._index.docnames;
var filenames = this._index.filenames;
var titles = this._index.titles;
var i, j, file;
var fileMap = {};
var scoreMap = {};
var results = [];
// perform the search on the required terms
for (i = 0; i < searchterms.length; i++) {
var word = searchterms[i];
var files = [];
var _o = [
{files: terms[word], score: Scorer.term},
{files: titleterms[word], score: Scorer.title}
];
// add support for partial matches
if (word.length > 2) {
var word_regex = this.escapeRegExp(word);
for (var w in terms) {
if (w.match(word_regex) && !terms[word]) {
_o.push({files: terms[w], score: Scorer.partialTerm})
}
}
for (var w in titleterms) {
if (w.match(word_regex) && !titleterms[word]) {
_o.push({files: titleterms[w], score: Scorer.partialTitle})
}
}
}
// no match but word was a required one
if ($u.every(_o, function(o){return o.files === undefined;})) {
break;
}
// found search word in contents
$u.each(_o, function(o) {
var _files = o.files;
if (_files === undefined)
return
if (_files.length === undefined)
_files = [_files];
files = files.concat(_files);
// set score for the word in each file to Scorer.term
for (j = 0; j < _files.length; j++) {
file = _files[j];
if (!(file in scoreMap))
scoreMap[file] = {};
scoreMap[file][word] = o.score;
}
});
// create the mapping
for (j = 0; j < files.length; j++) {
file = files[j];
if (file in fileMap && fileMap[file].indexOf(word) === -1)
fileMap[file].push(word);
else
fileMap[file] = [word];
}
}
// now check if the files don't contain excluded terms
for (file in fileMap) {
var valid = true;
// check if all requirements are matched
var filteredTermCount = // as search terms with length < 3 are discarded: ignore
searchterms.filter(function(term){return term.length > 2}).length
if (
fileMap[file].length != searchterms.length &&
fileMap[file].length != filteredTermCount
) continue;
// ensure that none of the excluded terms is in the search result
for (i = 0; i < excluded.length; i++) {
if (terms[excluded[i]] == file ||
titleterms[excluded[i]] == file ||
$u.contains(terms[excluded[i]] || [], file) ||
$u.contains(titleterms[excluded[i]] || [], file)) {
valid = false;
break;
}
}
// if we have still a valid result we can add it to the result list
if (valid) {
// select one (max) score for the file.
// for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
}
}
return results;
},
/**
* helper function to return a node containing the
* search summary for a given text. keywords is a list
* of stemmed words, hlwords is the list of normal, unstemmed
* words. the first one is used to find the occurrence, the
* latter for highlighting it.
*/
makeSearchSummary : function(htmlText, keywords, hlwords) {
var text = Search.htmlToText(htmlText);
var textLower = text.toLowerCase();
var start = 0;
$.each(keywords, function() {
var i = textLower.indexOf(this.toLowerCase());
if (i > -1)
start = i;
});
start = Math.max(start - 120, 0);
var excerpt = ((start > 0) ? '...' : '') +
$.trim(text.substr(start, 240)) +
((start + 240 - text.length) ? '...' : '');
var rv = $('<p class="context"></p>').text(excerpt);
$.each(hlwords, function() {
rv = rv.highlightText(this, 'highlighted');
});
return rv;
}
};
$(document).ready(function() {
Search.init();
});
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/docs/_build/singlehtml/_static/searchtools.js
|
searchtools.js
|
# -*- coding: utf-8 -*-
"""Unit test package for zyc."""
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/tests/__init__.py
|
__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `zyc` package."""
import unittest
from zyc import zyc
class TestZyc(unittest.TestCase):
"""Tests for `zyc` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures, if any."""
def test_000_something(self):
"""Test something."""
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/tests/test_zyc.py
|
test_zyc.py
|
* zyc version:
* Python version:
* Operating System:
### Description
Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.
### What I Did
```
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
```
|
zyc
|
/zyc-1.0.0.tar.gz/zyc-1.0.0/.github/ISSUE_TEMPLATE.md
|
ISSUE_TEMPLATE.md
|
# ansiformat
ANSI Formatted Text for Terminals.
## AnsiFormat for Custom Formatting
### Colors
```python
from zycelium.ansiformat import AnsiFormat
af = AnsiFormat()
print(af("Red text on default background").red)
print(af("Default text on lime background").on.lime)
print(af("Black text on yellow background").black.on.yellow)
print(af("Black text on cyan background").black.on.color("#00ffff"))
print(af("Red text on yellow background").color("#ff0000").on.color("#ffff00"))
```
### Effects
```python
from zycelium.ansiformat import AnsiFormat
af = AnsiFormat()
print(af("Bold").bold)
print(af("Dim").dim)
print(af("Italic").italic)
print(af("Underline").underline)
print(af("Blink").blink)
print(af("Inverse").inverse)
print(af("Hidden").hidden)
print(af("Strike").strike)
```
### Using Colors and Effects Together
```python
from zycelium.ansiformat import AnsiFormat
af = AnsiFormat()
print(af("Red text on default background, bold").red.bold)
print(af("Same, but with shortcut (b) for bold").red.b)
print(af("Same, but with shortcut (i) for italic").red.i)
print(af("Default text on lime background, with strike-through").on.lime.strike)
print(af("Black text on yellow background, underlined").black.on.yellow.underline)
print(af("Black text on cyan background, blinking").black.on.color("#00ffff").blink)
print(af("Red text on yellow background, inversed").color("#ff0000").on.color("#ffff00").inverse)
```
## AnsiMarkup for Quick Formatting
```python
from zycelium.ansiformat import AnsiMarkup, palette
m = AnsiMarkup(palette=palette.midnight_ablaze)
print(m.debug("debug"))
print(m.info("info"))
print(m.ok("ok"))
print(m.warning("warning"))
print(m.error("error"))
print(m.critical("critical"))
print(m.p("paragraph"))
print(m.aside("aside"))
print(m.note("note"))
print(m.alert("alert"))
print(m.h1("heading one"))
print(m.h2("heading two"))
print(m.h3("heading three"))
print(m.h4("heading four"))
print(m.h5("heading five"))
print(m.h6("heading six"))
with m.indent():
print(m.li("list item 1"))
print(m.li("list item 2"))
with m.indent():
print(m.li("list item 2.1"))
print(m.li("list item 2.2"))
```
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/README.md
|
README.md
|
from setuptools import setup, find_namespace_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="zycelium.ansiformat",
version="0.1.1",
description="ANSI Formatted Text for Terminals.",
author="Harshad Sharma",
author_email="[email protected]",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/zycelium/python-ansiformat",
project_urls={
"Bug Tracker": "https://github.com/zycelium/python-ansiformat/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
],
packages=['zycelium.ansiformat'],
package_dir={"": "src"},
zip_safe=False,
python_requires=">=3.7",
install_requires=[
"sty>=1.0.0rc1",
"colour>=0.1.5",
],
extras_require={
"devel": [
"bump2version>=1.0",
"pytest>=6.2",
],
},
)
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/setup.py
|
setup.py
|
from collections import defaultdict
from typing import Optional, Union
import sty
from .color import Color, terminal_colors
from .string import AnsiString
class AnsiFormat(object):
def __init__(
self, palette: Optional[list] = None, term_colors: Optional[int] = None
):
self._terminal_colors = (
term_colors if term_colors is not None else terminal_colors()
)
self._custom_palette = palette
def __call__(self, text=""):
return AnsiString(text, self._terminal_colors, self._custom_palette)
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/format.py
|
format.py
|
import logging
import os
import platform
import sys
from math import sqrt
from typing import Optional, Tuple, Union
import sty
from colour import Color as _Color
from colour import COLOR_NAME_TO_RGB
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
IntervalValue = Union[int, float]
RGB255Tuple = Tuple[int, ...]
RGBTuple = Tuple[float, ...]
# Constants
CUBE_INTENSITIES = [
0x80,
0x5F,
0x87,
0xAF,
0xD7,
0xFF,
]
ANSI_8_PALETTE = [
"#000000", # black
"#ff0000", # red
"#00ff00", # lime
"#ffff00", # yellow
"#0000ff", # blue
"#ff00ff", # magenta
"#00ffff", # cyan
"#ffffff", # white
]
ANSI_16_PALETTE = [
"#000000", # black
"#880000", # darkred
"#008800", # darkgreen
"#888800", # orange
"#000088", # darkblue
"#880088", # darkmagenta
"#008888", # darkcyan
"#888888", # silver
"#000000", # gray
"#ff0000", # red
"#00ff00", # lime
"#ffff00", # yellow
"#0000ff", # blue
"#ff00ff", # magenta
"#00ffff", # cyan
"#ffffff", # white
]
def generate_256color(index):
if index < 16:
return ANSI_16_PALETTE[index]
elif index < 232:
q1, _b = divmod(index - 16, 6)
q2, _g = divmod(q1, 6)
_, _r = divmod(q2, 6)
r = CUBE_INTENSITIES[_r]
g = CUBE_INTENSITIES[_g]
b = CUBE_INTENSITIES[_b]
return f"#{hex(r)[2:]}{hex(g)[2:]}{hex(b)[2:]}"
else:
i = 10 * (index - 232) + 8
h = hex(i)[2:]
if len(h) == 1:
h = "0" + h
return f"#{h}{h}{h}"
ANSI_256_PALETTE = [generate_256color(i) for i in range(256)]
def map_interval(
from_start: IntervalValue,
from_end: IntervalValue,
to_start: IntervalValue,
to_end: IntervalValue,
value: IntervalValue,
) -> IntervalValue:
"""
Map numbers from an interval to another.
>>> map_interval(0, 1, 0, 255, 0.5)
127.5
>>> map_interval(0, 255, 0, 1, 128) # doctest: +ELLIPSIS
0.50...
:param from_start: lower bound of source interval.
:param from_end: upper bound of source interval.
:param to_start: lower bound of target interval.
:param to_end: upper bound of target interval.
:param value: source value to map to target interval.
:return: value in target interval.
"""
return (value - from_start) * (to_end - to_start) / (
from_end - from_start
) + to_start
def rgb_to_RGB255(rgb: RGBTuple) -> RGB255Tuple:
"""
Convert from Color.rgb's 0-1 range to ANSI RGB (0-255) range.
>>> rgb_to_RGB255((1, 0.5, 0))
(255, 128, 0)
"""
return tuple([int(round(map_interval(0, 1, 0, 255, c))) for c in rgb])
def color_hex_to_int(color):
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
def distance(color_1, color_2):
r1, g1, b1 = color_hex_to_int(color_1)
r2, g2, b2 = color_hex_to_int(color_2)
return sqrt((r2 - r1) ** 2 + (g2 - g1) ** 2 + (b2 - b1) ** 2)
def match_index(color, palette):
min_index = -1
min_distance = 1000000000
for i, c in enumerate(palette):
d = distance(color, c)
if d < min_distance:
min_index = i
min_distance = d
return min_index
def match_color(color, palette):
index = match_index(color, palette)
return palette[index]
def terminal_colors(stream=sys.stdout) -> int:
"""
Get number of supported ANSI colors for a stream.
Defaults to sys.stdout.
>>> terminal_colors(sys.stderr)
0
"""
colors = 0
if stream.isatty():
if platform.system() == "Windows":
# colorama supports 8 ANSI colors
# (and dim is same as normal)
colors = 8
elif os.environ.get("NO_COLOR", None) is not None:
colors = 0
elif os.environ.get("COLORTERM", "").lower() in {"truecolor", "24bit"}:
colors = 16_777_216
elif os.environ.get("TERM", "") in {"vt100", "vt200", "vt220"}:
colors = 0
elif os.environ.get("TERM", "") in {"xterm"}:
colors = 8
elif os.environ.get("TERM", "") in {"xterm-color", "rxvt", "rxvt-88color"}:
colors = 16
elif os.environ.get("TERM", "") in {"ansi", "xterm-256color"}:
colors = 256
elif os.environ.get("TERM", "").lower() in {"truecolor", "24bit"}:
colors = 16_777_216
else:
# curses is used to autodetect terminal colors on *nix.
try:
from curses import setupterm, tigetnum
setupterm()
colors = max(0, tigetnum("colors"))
except ImportError:
pass
except:
pass
return colors
class Color(_Color):
@property
def RGB(self):
return rgb_to_RGB255(self.rgb)
@property
def ansi8(self):
return (match_index(self.hex_l, ANSI_8_PALETTE),)
@property
def ansi16(self):
return (match_index(self.hex_l, ANSI_16_PALETTE),)
@property
def ansi256(self):
return (match_index(self.hex_l, ANSI_256_PALETTE),)
def match_palette(self, palette):
return Color(match_color(self.hex_l, palette)).RGB
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/color.py
|
color.py
|
from collections import defaultdict
from typing import Optional, Union
import sty
from .color import Color, terminal_colors
SHORTCUTS = {
"b": "ef_bold",
"bold": "ef_bold",
"dim": "ef_dim",
"blink": "ef_blink",
"hidden": "ef_hidden",
"inverse": "ef_inverse",
"strike": "ef_strike",
"i": "ef_italic",
"italic": "ef_italic",
"u": "ef_underl",
"underline": "ef_underl",
}
class AnsiString(str):
def __new__(
cls, text: str, terminal_colors: int = 0, custom_palette: Optional[list] = None
):
return super().__new__(cls, text)
def __init__(
self, text: str, terminal_colors: int = 0, custom_palette: Optional[list] = None
):
self._text = text
self._terminal_colors = terminal_colors
self._custom_palette = custom_palette
self._buffer = []
self._fg_is_set = False
def __str__(self):
if self._buffer:
text = "".join(self._buffer) + self._text
if self._terminal_colors > 0:
text += sty.rs.all
return text
else:
return self._text
def __call__(self, text: str):
if self._text:
self._buffer.append(self._text)
self._text = text
self._fg_is_set = False
return self
def __getattr__(self, name):
if name.startswith("fg_"):
return self.fg(name[3:])
elif name.startswith("bg_"):
return self.bg(name[3:])
elif name.startswith("rs_"):
return self.rs(name[3:])
elif name.startswith("ef_"):
return self.ef(name[3:])
elif name in SHORTCUTS:
return getattr(self, SHORTCUTS[name])
elif name == "color":
return self.color
else:
if self._fg_is_set:
return self.bg(name)
else:
return self.fg(name)
def color(self, name: str):
if self._fg_is_set:
return self.bg(name)
else:
return self.fg(name)
def render_color(self, color: Color):
if self._terminal_colors <= 0:
return None
if isinstance(color, str):
color = Color(color)
else:
color = Color(*color)
if self._terminal_colors == 8:
return color.ansi8
elif self._terminal_colors == 16:
return color.ansi16
elif self._terminal_colors == 256:
return color.ansi256
else:
if self._custom_palette:
return color.match_palette(self._custom_palette)
else:
return color.RGB
def fg(self, color: Union[str, list, tuple]):
if self._terminal_colors == 0:
return self
color = self.render_color(color)
if color is None:
return self
self._buffer.append(sty.fg(*color))
return self
def bg(self, color: Union[str, list, tuple]):
if self._terminal_colors == 0:
return self
color = self.render_color(color)
if color is None:
return self
self._buffer.append(sty.bg(*color))
return self
def rs(self, name: str):
if self._terminal_colors == 0:
return self
ansi = getattr(sty.rs, name)
self._buffer.append(self._text)
self._text = ""
self._buffer.append(ansi)
return self
def ef(self, name: str):
if self._terminal_colors == 0:
return self
ansi = getattr(sty.ef, name)
self._buffer.append(ansi)
return self
@property
def on(self):
self._fg_is_set = True
return self
@property
def raw(self):
return repr(str(self))
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/string.py
|
string.py
|
class AnsiPalette(object):
@property
def versitile_16(self):
"""
https://lospec.com/palette-list/versitle-16
"""
return [
"#0c0b0f",
"#af3f52",
"#5f3959",
"#2e2937",
"#905c9a",
"#d78d42",
"#93593b",
"#8d92ac",
"#d47fb0",
"#dddd50",
"#75b546",
"#4a6db2",
"#f3cb94",
"#eff0e9",
"#a7d6da",
"#56a1c8",
]
@property
def mega_drive_blue(self):
"""
https://lospec.com/palette-list/mega-drive-blue
"""
return [
"#2b120d",
"#9f1211",
"#fc1400",
"#fc6a00",
"#fcfc00",
"#000000",
"#330445",
"#9c0c9c",
"#ff099d",
"#00072c",
"#040085",
"#0000ff",
"#0066ff",
"#67cdfc",
"#004849",
"#067826",
"#00c908",
"#52ff00",
"#c6f022",
"#352c2e",
"#754944",
"#ad5950",
"#f6757a",
"#fac59b",
"#693623",
"#b0572b",
"#e98e42",
"#fcb448",
"#fffcff",
"#666688",
"#9892ad",
"#b8b8d1",
"#ddd9e6",
"#fcfcfc",
]
@property
def vinik_24(self):
"""
https://lospec.com/palette-list/vinik24
"""
return [
"#000000",
"#6f6776",
"#9a9a97",
"#c5ccb8",
"#8b5580",
"#c38890",
"#a593a5",
"#666092",
"#9a4f50",
"#c28d75",
"#7ca1c0",
"#416aa3",
"#8d6268",
"#be955c",
"#68aca9",
"#387080",
"#6e6962",
"#93a167",
"#6eaa78",
"#557064",
"#9d9f7f",
"#7e9e99",
"#5d6872",
"#433455",
]
@property
def endesga_32(self):
"""
https://lospec.com/palette-list/endesga-32
"""
return [
"#be4a2f",
"#d77643",
"#ead4aa",
"#e4a672",
"#b86f50",
"#733e39",
"#3e2731",
"#a22633",
"#e43b44",
"#f77622",
"#feae34",
"#fee761",
"#63c74d",
"#3e8948",
"#265c42",
"#193c3e",
"#124e89",
"#0099db",
"#2ce8f5",
"#ffffff",
"#c0cbdc",
"#8b9bb4",
"#5a6988",
"#3a4466",
"#262b44",
"#181425",
"#ff0044",
"#68386c",
"#b55088",
"#f6757a",
"#e8b796",
"#c28569",
]
@property
def pear36(self):
"""
https://lospec.com/palette-list/pear36
"""
return [
"#5e315b",
"#8c3f5d",
"#ba6156",
"#f2a65e",
"#ffe478",
"#cfff70",
"#8fde5d",
"#3ca370",
"#3d6e70",
"#323e4f",
"#322947",
"#473b78",
"#4b5bab",
"#4da6ff",
"#66ffe3",
"#ffffeb",
"#c2c2d1",
"#7e7e8f",
"#606070",
"#43434f",
"#272736",
"#3e2347",
"#57294b",
"#964253",
"#e36956",
"#ffb570",
"#ff9166",
"#eb564b",
"#b0305c",
"#73275c",
"#422445",
"#5a265e",
"#80366b",
"#bd4882",
"#ff6b97",
"#ffb5b5",
]
@property
def pollen8(self):
"""
https://lospec.com/palette-list/pollen8
"""
return [
"#73464c",
"#ab5675",
"#ee6a7c",
"#ffa7a5",
"#ffe07e",
"#ffe7d6",
"#72dcbb",
"#34acba",
]
@property
def bubblegum16(self):
"""
https://lospec.com/palette-list/bubblegum-16
"""
return [
"#16171a",
"#7f0622",
"#d62411",
"#ff8426",
"#ffd100",
"#fafdff",
"#ff80a4",
"#ff2674",
"#94216a",
"#430067",
"#234975",
"#68aed4",
"#bfff3c",
"#10d275",
"#007899",
"#002859",
]
@property
def nostalgia(self):
"""
https://lospec.com/palette-list/nostalgia
"""
return [
"#d0d058",
"#a0a840",
"#708028",
"#405010",
]
@property
def midnight_ablaze(self):
"""
https://lospec.com/palette-list/midnight-ablaze
"""
return [
"#ff8274",
"#d53c6a",
"#7c183c",
"#460e2b",
"#31051e",
"#1f0510",
"#130208",
]
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/palette.py
|
palette.py
|
from contextlib import contextmanager
from textwrap import indent
from typing import Optional
from zycelium.ansiformat import AnsiFormat
class AnsiMarkup(object):
def __init__(self, palette=None, term_colors=None):
self.af = AnsiFormat(palette=palette, term_colors=term_colors)
self._indent = 0
def debug(self, text):
return self.af().gray(text)
def info(self, text):
return self.af().blue(text)
def ok(self, text):
return self.af().green(text)
def warning(self, text):
return self.af().orange(text)
def error(self, text):
return self.af().red(text)
def critical(self, text):
return self.af().yellow.on.red(text)
def p(self, text):
return self.af().black(text)
def aside(self, text):
return self.af("[~]").black.on.lightgray.rs_all(" ")(text)
def note(self, text):
return self.af("[>]").black.on.lime.rs_all(" ")(text)
def alert(self, text):
return self.af("[!]").black.on.orange.rs_all(" ")(text)
def h1(self, text):
return self.af("# ").red.b.u(text)
def h2(self, text):
return self.af("## ").darkorange.b.u(text)
def h3(self, text):
return self.af("### ").blue.b.u(text)
def h4(self, text):
return self.af("#### ").black.b.u(text)
def h5(self, text):
return self.af("##### ").black.b.u(text)
def h6(self, text):
return self.af("###### ").black.b.u(text)
def li(self, text):
_text = str(self.af("- ").blue(text))
_text = indent(_text, " " * self._indent)
return _text
@contextmanager
def indent(self, text=""):
self._indent = self._indent + 2
yield
self._indent = self._indent - 2
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/markup.py
|
markup.py
|
from .color import Color, ANSI_8_PALETTE, ANSI_16_PALETTE, ANSI_256_PALETTE
from .format import AnsiFormat
from .markup import AnsiMarkup
from .palette import AnsiPalette
from .string import AnsiString
__version__ = "0.1.1"
palette = AnsiPalette()
__all__ = [
"ANSI_8_PALETTE",
"ANSI_16_PALETTE",
"ANSI_256_PALETTE"
"AnsiFormat",
"AnsiMarkup",
"AnsiPalette"
"AnsiString",
"Color",
"palette",
]
|
zycelium.ansiformat
|
/zycelium.ansiformat-0.1.1.tar.gz/zycelium.ansiformat-0.1.1/src/zycelium/ansiformat/__init__.py
|
__init__.py
|
# zycelium.dataconfig
Create [dataclasses](https://docs.python.org/3/library/dataclasses.html) backed by configuration files.
[](https://github.com/zycelium/dataconfig/actions/workflows/python-package.yml)
- `Development Status :: 3 - Alpha`
## Usage
### Use defaults:
Create a new python script and name it `example.py`
```python
from zycelium.dataconfig import dataconfig
@dataconfig
class Config:
name: str = "World"
config = Config().load()
print(f"Hello, {config.name}!")
```
Create a `config.ini` file in the same directory as `example.py`
```ini
name = "DataConfig"
```
Finally, from the same directory, run `python example.py` ,
your console session should look something like this:
```console
$ python example.py
Hello, DataConfig!
```
The defaults here are:
- Config file name: `"config.ini"`
- Paths to look for the config file (current working directory): `["."]`
### Specify file-name for configuration:
```python
from zycelium.dataconfig import dataconfig
@dataconfig(file="custom_config.ini")
class Config:
name: str = "World"
config = Config().load()
print(f"Hello, {config.name}!")
```
In this example, we specify the file-name on this line:
`@dataconfig(file="custom_config.ini")` with keyword arguments
`file="custom_config.ini"` passed to `@dataconfig()`.
### Specify file-lookup-paths:
```python
from zycelium.dataconfig import dataconfig
@dataconfig(paths=[".", "examples", "/usr/local/etc"])
class Config:
name: str = "World"
config = Config().load()
print(f"Hello, {config.name}!")
```
Here, we pass `paths=[".", "examples"]` to `@dataconfig()`
to specify the paths on filesystem where `dataconfig` should
look for the default `"config.ini"` file. We can also specify
the filename along with the paths. Paths can be relative
to current working directory or absolute.
### Save configuration to file:
```python
from zycelium.dataconfig import dataconfig
FILE_NAME = "newconfig.ini"
@dataconfig(file=FILE_NAME)
class Config:
name: str = "World"
config = Config()
config.save()
print(f"Saved config to file: {FILE_NAME}.")
```
Here, we set the config-file-name while creating the class,
when `save()` is called, it will create the file and save
contents of `Config`.
If we try running the same example again, we will get an error:
`FileExistsError: File newconfig.ini exists, refusing to overwrite.`
This is to protect us from accidentally overwriting an existing config file.
To overwrite it, pass `overwrite=True` to `save()` like this:
`config.save(overwrite=True)`
### Frozen configuration:
```python
from zycelium.dataconfig import dataconfig
@dataconfig(frozen=True)
class Config:
name: str = "World"
config = Config().load(replace=True)
print(f"Hello, {config.name}!")
```
To load a frozen config, we need to pass `replace=True` to `load()`,
if we forget, we get the error:
`dataclasses.FrozenInstanceError: cannot assign to field 'name'`
Once loaded, we cannot overwrite the configuration.
### Use with Click Integration for CLI apps:
Here, dataconfig will generate options for click CLI framework,
one to add defaults to all options with names that exist in
the dataconfig class, overridden by values found in the configuration
file. These options can be overridden by passing values as usual
to the command line.
There's also a new option added to the command: "--conf", which
can be used to specify a different configuration file to load
defaults.
And finally, any changes made in the command line are applied to
the dataconfig object, but not saved to the configuration file
unless the `save()` method is called later.
Frozen dataconfig does not work with commandline integration.
```python
import click
from zycelium.dataconfig import dataconfig
@dataconfig
class Config:
name: str = "World"
config = Config()
# No need to load() config when using click_option()
@click.command()
@click.option("--name")
@config.click_option()
def main(name):
print(f"Hello, {name}!")
print(f"Hello, {config.name}!")
main()
```
### For more examples:
Read through the `tests/` directory, where you will find the
expected usage and how and why dataconfig can fail.
## Install
From [PyPI](https://pypi.org/)
```console
pip install zycelium.dataconfig
```
From source:
```console
git clone https://github.com/zycelium/dataconfig.git
cd dataconfig
pip install -e .
```
|
zycelium.dataconfig
|
/zycelium.dataconfig-0.1.1.tar.gz/zycelium.dataconfig-0.1.1/README.md
|
README.md
|
from setuptools import setup, find_namespace_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="zycelium.dataconfig",
version="0.1.1",
description="Create dataclasses backed by configuration files.",
author="Harshad Sharma",
author_email="[email protected]",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/zycelium/python-dataconfig",
project_urls={
"Bug Tracker": "https://github.com/zycelium/python-dataconfig/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
],
packages=['zycelium.dataconfig'],
package_dir={"": "src"},
zip_safe=False,
python_requires=">=3.7",
install_requires=[
"click>=8.0",
"configobj>=5.0",
],
extras_require={
"devel": [
"bump2version>=1.0",
"pytest>=6.2",
],
},
)
|
zycelium.dataconfig
|
/zycelium.dataconfig-0.1.1.tar.gz/zycelium.dataconfig-0.1.1/setup.py
|
setup.py
|
from dataclasses import asdict, dataclass, FrozenInstanceError
from dataclasses import replace as replace_dataclass
from functools import partial
from pathlib import Path
import click
from configobj import ConfigObj
__version__ = "0.1.1"
DEFAULT_FILE = "config.ini"
def locate(file, paths, auto, file_path=""):
if file_path:
return Path(file_path)
elif auto:
for _path in paths:
path = Path(_path).joinpath(file)
if path.exists():
return path
return Path(".").joinpath(file)
else:
raise FileNotFoundError(f"File {file!r} not found at {paths}.")
def load(obj, path="", unrepr=True, replace=False):
path = locate(
file=obj._file, paths=obj._paths, auto=obj._auto, file_path=path
)
config_obj = ConfigObj(str(path), unrepr=unrepr)
return obj.from_dict(config_obj, replace=replace)
def from_dict(obj, data, replace=False):
if not replace:
for k, v in data.items():
if hasattr(obj, k):
setattr(obj, k, v)
return obj
else:
fields = {k: v for k, v in data.items() if hasattr(obj, k)}
return replace_dataclass(obj, **fields)
def to_dict(obj):
fields = asdict(obj)
return fields
def save(obj, path="", unrepr=True, overwrite=False):
path = locate(
file=obj._file, paths=obj._paths, auto=obj._auto, file_path=path
)
config_obj = ConfigObj(unrepr=unrepr)
config_obj.update(asdict(obj))
if path.exists() and not overwrite:
raise FileExistsError(f"File {path} exists, refusing to overwrite.")
with path.open("wb") as outfile:
config_obj.write(outfile)
return obj
def click_option(obj, *param_decls, **attrs):
param_decls = param_decls or ("--conf",)
def wrap(func):
attrs.setdefault("is_eager", True)
attrs.setdefault("help", "Read configuration from FILE")
attrs.setdefault("expose_value", False)
path = attrs.pop("path", obj._file)
attrs["callback"] = partial(_file_option_callback, obj, path=path)
config_update_option = click.option(
"--config-update",
is_eager=False,
expose_value=False,
hidden=True,
callback=partial(_config_update_callback, obj),
)
return config_update_option(click.option(*param_decls, **attrs)(func))
return wrap
def _file_option_callback(obj, ctx, option, value, path):
ctx.default_map = ctx.default_map or {}
path = value or path
obj.load(path=path)
options = obj.to_dict()
ctx.default_map.update(options)
def _config_update_callback(obj, ctx, option, value):
data = {k: v for k, v in ctx.params.items() if v is not None}
obj.from_dict(data)
def dataconfig(
_cls=None,
*,
file=DEFAULT_FILE,
paths=None,
auto=True,
init=True,
repr=True,
eq=True,
order=False,
unsafe_hash=False,
frozen=False,
):
def wrap(cls):
setattr(cls, "_file", file)
setattr(cls, "_paths", paths or ["."])
setattr(cls, "_auto", auto)
setattr(cls, "load", load)
setattr(cls, "save", save)
setattr(cls, "from_dict", from_dict)
setattr(cls, "to_dict", to_dict)
setattr(cls, "click_option", click_option)
wrapped_cls = dataclass(
cls,
init=init,
repr=repr,
eq=eq,
order=order,
unsafe_hash=unsafe_hash,
frozen=frozen,
)
return wrapped_cls
if _cls is None:
return wrap
return wrap(_cls)
|
zycelium.dataconfig
|
/zycelium.dataconfig-0.1.1.tar.gz/zycelium.dataconfig-0.1.1/src/zycelium/dataconfig/__init__.py
|
__init__.py
|
import xlrd
def read_excel(file_path, sheet_name):
# 读取Excel表格数据
workxls = xlrd.open_workbook(file_path)
worksheet = workxls.sheet_by_name(sheet_name)
row = worksheet.nrows # 总行数
# print("Excel行数:{}".format(row))
return worksheet, row
def obtainexcelinfo(filePath, sheetName):
workSheet, rows = read_excel(filePath, sheetName)
keys = workSheet.row_values(0)
data_list=[]
for row in range(1, rows):
rowData = workSheet.row_values(row)
item = dict(zip(keys, rowData))
data_list.append(item)
return data_list
|
zyctool
|
/zyctool-1.1.5-py3-none-any.whl/zycspidertool/Spidertool.py
|
Spidertool.py
|
from distutils.core import setup
setup(
name = 'zydis',
packages = ['zydis'],
version = '0.0.1',
description = 'Future home of official Zydis Python bindings',
author = 'Joel Höner',
author_email = '[email protected]',
url = 'https://github.com/zyantific/zydis-rs',
download_url = 'https://github.com/zyantific/zydis-rs',
keywords = [],
classifiers = [],
)
|
zydis
|
/zydis-0.0.1.tar.gz/zydis-0.0.1/setup.py
|
setup.py
|
# pamda
This is a repo try to copy <https://github.com/ramda/ramda> in python.
## install
For whom wants to use this package.
```bash
> pip install zydmayday-pamda
> pip install zydmayday-pamda -U # get the latest
```
## Usage
```python
>>> from pamda import curry
>>> def sum(a, b, c): return a + b + c
>>> curry(sum)(1)(2, 3)
6
```
```python
>>> import pamda as R # similar to ramda syntax
>>> def sum(a, b, c): return a + b + c
>>> R.curry(sum)(1)(2, 3)
6
```
## Contribute
For whom wants to contribute to this repo.
```bash
# see: https://pre-commit.com/ for more details
$ pre-commit install # install hooks
```
Check the latest branch to be released in [here](https://github.com/zydmayday/pamda/branches).
Checkout new branch from that release branch and create PR.
## CheckList
Functions supported now.
- [x] __
- [x] add
```python
# different from ramda, ramda treat null as 0
>>> R.add(None, None) # float('nan)
```
- [ ] addIndex
- [x] adjust
- [x] all
- Transducer part is not fully tested.
- [ ] allPass
- [x] always
- [x] And (`and` is a keyword in python)
- [ ] andThen
- [x] any
- [ ] anyPass
- [ ] ap
- [ ] aperture
- [x] append
- [ ] apply
- [ ] applySpec
- [ ] applyTo
- [ ] ascend
- [ ] assoc
- [ ] assocPath
- [ ] binary
- [ ] bind
- [ ] both
- [ ] call
- [ ] chain
- [ ] clamp
- [ ] clone
- [ ] collectBy
- [x] comparator
- [ ] complement
- [x] compose
- [ ] composeWith
- [x] concat
- [ ] cond
- [ ] construct
- [ ] constructN
- [ ] converge
- [ ] count
- [x] countBy
- [x] curry
- [x] curryN
- [ ] dec
- [ ] defaultTo
- [ ] descend
- [x] difference
- [x] differenceWith
- [ ] dissoc
- [ ] dissocPath
- [x] divide
- [ ] drop
- [ ] dropLast
- [ ] dropLastWhile
- [ ] dropRepeats
- [ ] dropRepeatsWith
- [ ] dropWhile
- [ ] either
- [ ] empty
- [ ] endsWith
- [ ] eqBy
- [ ] eqProps
- [x] equals
- [ ] evolve
- [ ] F
- [x] filter
- [x] find
- [ ] findIndex
- [ ] findLast
- [ ] findLastIndex
- [ ] flatten
- [ ] flip
- [ ] forEach
- [ ] forEachObjIndexed
- [ ] fromPairs
- [ ] groupBy
- [ ] groupWith
- [ ] gt
- [ ] gte
- [ ] has
- [ ] hasIn
- [ ] hasPath
- [ ] head
- [ ] identical
- [x] identity
- [ ] ifElse
- [ ] inc
- [ ] includes
- [ ] indexBy
- [ ] indexOf
- [ ] init
- [ ] innerJoin
- [ ] insert
- [ ] insertAll
- [ ] intersection
- [ ] intersperse
- [x] into
- [ ] invert
- [ ] invertObj
- [ ] invoker
- [ ] is
- [ ] isEmpty
- [ ] isNil
- [ ] join
- [ ] juxt
- [x] keys
```python
# When using R.keys(obj) and obj is a class instance, we use obj.__dict__ as keys.
class A:
c = 'not included'
def __init__(self):
self.a = 1
self.b = 2
a = A()
R.keys(a) # ['a', 'b']
```
- [ ] keysIn
- [ ] last
- [ ] lastIndexOf
- [ ] length
- [ ] lens
- [ ] lensIndex
- [ ] lensPath
- [ ] lensProp
- [ ] lift
- [ ] liftN
- [ ] lt
- [ ] lte
- [x] Map (`map` is a keyword in python)
- [ ] mapAccum
- [ ] mapAccumRight
- [ ] mapObjIndexed
- [ ] match
- [ ] mathMod
- [ ] max
- [ ] maxBy
- [ ] mean
- [ ] median
- [ ] memoizeWith
- [ ] mergeAll
- [ ] mergeDeepLeft
- [ ] mergeDeepRight
- [ ] mergeDeepWith
- [ ] mergeDeepWithKey
- [ ] mergeLeft
- [ ] mergeRight
- [ ] mergeWith
- [ ] mergeWithKey
- [ ] min
- [ ] minBy
- [ ] modify
- [ ] modifyPath
- [ ] modulo
- [ ] move
- [x] multiply
- [ ] nAry
- [ ] negate
- [ ] none
- [ ] not
- [x] nth
- [ ] nthArg
- [ ] o
- [x] objOf
- [ ] of
- [ ] omit
- [ ] on
- [ ] once
- [ ] or
- [ ] otherwise
- [ ] over
- [ ] pair
- [ ] partial
- [ ] partialObject
- [ ] partialRight
- [ ] partition
- [ ] path
- [ ] pathEq
- [ ] pathOr
- [ ] paths
- [ ] pathSatisfies
- [ ] pick
- [ ] pickAll
- [ ] pickBy
- [x] pipe
- [ ] pipeWith
- [ ] pluck
- [ ] prepend
- [ ] product
- [ ] project
- [ ] promap
- [x] prop
- [ ] propEq
- [ ] propIs
- [ ] propOr
- [ ] props
- [ ] propSatisfies
- [ ] range
- [x] reduce
- [x] reduceBy
- [x] reduced
- [ ] reduceRight
- [ ] reduceWhile
- [x] reject
- [ ] remove
- [ ] repeat
- [ ] replace
- [x] reverse
- [ ] scan
- [ ] sequence
- [ ] set
- [x] slice
- [x] sort
- [ ] sortBy
- [ ] sortWith
- [ ] split
- [ ] splitAt
- [ ] splitEvery
- [ ] splitWhen
- [ ] splitWhenever
- [ ] startsWith
- [ ] subtract
- [ ] sum
- [ ] symmetricDifference
- [ ] symmetricDifferenceWith
- [ ] T
- [x] tail
- [ ] take
- [ ] takeLast
- [ ] takeLastWhile
- [ ] takeWhile
- [ ] tap
- [ ] test
- [ ] thunkify
- [ ] times
- [ ] toLower
- [ ] toPairs
- [ ] toPairsIn
- [ ] toString
- [ ] toUpper
- [ ] transduce
- [ ] transpose
- [ ] traverse
- [ ] trim
- [ ] tryCatch
- [ ] type
- [ ] unapply
- [ ] unary
- [ ] uncurryN
- [ ] unfold
- [ ] union
- [ ] unionWith
- [ ] uniq
- [ ] uniqBy
- [ ] uniqWith
- [ ] unless
- [ ] unnest
- [ ] until
- [ ] unwind
- [ ] update
- [ ] useWith
- [ ] values
- [ ] valuesIn
- [ ] view
- [ ] when
- [ ] where
- [ ] whereAny
- [ ] whereEq
- [ ] without
- [ ] xor
- [ ] xprod
- [ ] zip
- [ ] zipObj
- [ ] zipWith
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/README.md
|
README.md
|
from os.path import abspath, dirname, join
from setuptools import find_packages, setup
# Fetches the content from README.md
# This will be used for the "long_description" field.
README_MD = open(join(dirname(abspath(__file__)), "README.md")).read()
setup(
# The name of your project that we discussed earlier.
# This name will decide what users will type when they install your package.
# In my case it will be:
# pip install pydash-arnu515
# This field is REQUIRED
name="zydmayday-pamda",
# The version of your project.
# Usually, it would be in the form of:
# major.minor.patch
# eg: 1.0.0, 1.0.1, 3.0.2, 5.0-beta, etc.
# You CANNOT upload two versions of your package with the same version number
# This field is REQUIRED
version="0.0.9",
# The packages that constitute your project.
# For my project, I have only one - "pydash".
# Either you could write the name of the package, or
# alternatively use setuptools.findpackages()
#
# If you only have one file, instead of a package,
# you can instead use the py_modules field instead.
# EITHER py_modules OR packages should be present.
packages=find_packages(exclude="tests"),
# The description that will be shown on PyPI.
# Keep it short and concise
# This field is OPTIONAL
description="A small clone of ramda",
# The content that will be shown on your project page.
# In this case, we're displaying whatever is there in our README.md file
# This field is OPTIONAL
long_description=README_MD,
# Now, we'll tell PyPI what language our README file is in.
# In my case it is in Markdown, so I'll write "text/markdown"
# Some people use reStructuredText instead, so you should write "text/x-rst"
# If your README is just a text file, you have to write "text/plain"
# This field is OPTIONAL
long_description_content_type="text/markdown",
# The url field should contain a link to a git repository, the project's website
# or the project's documentation. I'll leave a link to this project's Github repository.
# This field is OPTIONAL
url="https://github.com/zydmayday/pamda",
# The author name and email fields are self explanatory.
# These fields are OPTIONAL
author_name="zydmayday",
author_email="[email protected]",
# Classifiers help categorize your project.
# For a complete list of classifiers, visit:
# https://pypi.org/classifiers
# This is OPTIONAL
classifiers=[
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.9"
],
# Keywords are tags that identify your project and help searching for it
# This field is OPTIONAL
keywords="functional programming, ramda",
# For additional fields, check:
# https://github.com/pypa/sampleproject/blob/master/setup.py
)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/setup.py
|
setup.py
|
import unittest
from test.helpers.listXf import listXf
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/any.js
"""
def odd(n): return n % 2 == 1
def T(): return True
intoArray = R.into([])
class TestAny(unittest.TestCase):
def test_returns_true_if_any_elements_satisfy_the_predicate(self):
self.assertEqual(True, R.any(odd, [2, 4, 6, 8, 10, 11, 12]))
def test_returns_false_if_all_elements_fails_to_satisfy_the_predicate(self):
self.assertEqual(False, R.any(odd, [2, 4, 6, 8, 10, 12]))
def test_returns_true_into_array_if_any_elements_satisfy_the_predicate(self):
self.assertEqual([True], intoArray(R.any(odd), [2, 4, 6, 8, 10, 11, 12]))
def test_returns_false_if_all_elements_fails_to_satisfy_the_predicate(self):
self.assertEqual([False], intoArray(R.any(odd), [2, 4, 6, 8, 10, 12]))
def test_works_with_more_complex_objects(self):
people = [{'first': 'Paul', 'last': 'Grenier'}, {'first': 'Mike', 'last': 'Hurley'}, {'first': 'Will', 'last': 'Klein'}]
def alliterative(person): return person.get('first')[0] == person.get('last')[0]
self.assertEqual(False, R.any(alliterative, people))
people.append({'first': 'Scott', 'last': 'Sauyet'})
self.assertEqual(True, R.any(alliterative, people))
def test_returns_false_for_an_empty_list(self):
self.assertEqual(False, R.any(T, []))
def test_returns_false_into_array_for_an_empty_list(self):
self.assertEqual([False], intoArray(R.any(T), []))
def test_dispatches_when_given_a_transformer_in_list_position(self):
res = R.any(odd, listXf)
self.assertEqual(res.any, False)
self.assertEqual(res.f, odd)
self.assertEqual(res.xf, listXf)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_any.py
|
test_any.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/slice.js
"""
class TestSlice(unittest.TestCase):
def test_retrieves_the_proper_sublist_of_a_list(self):
list = [8, 6, 7, 5, 3, 0, 9]
self.assertEqual([7, 5, 3], R.slice(2, 5, list))
def test_can_operate_on_tuple(self):
list = (8, 6, 7, 5, 3, 0, 9)
self.assertEqual((7, 5, 3), R.slice(2, 5, list))
def test_can_operate_on_strings(self):
self.assertEqual(R.slice(0, 0, 'abc'), '')
self.assertEqual(R.slice(0, 1, 'abc'), 'a')
self.assertEqual(R.slice(0, 2, 'abc'), 'ab')
self.assertEqual(R.slice(0, 3, 'abc'), 'abc')
self.assertEqual(R.slice(0, 4, 'abc'), 'abc')
self.assertEqual(R.slice(1, 0, 'abc'), '')
self.assertEqual(R.slice(1, 1, 'abc'), '')
self.assertEqual(R.slice(1, 2, 'abc'), 'b')
self.assertEqual(R.slice(1, 3, 'abc'), 'bc')
self.assertEqual(R.slice(1, 4, 'abc'), 'bc')
self.assertEqual(R.slice(0, -4, 'abc'), '')
self.assertEqual(R.slice(0, -3, 'abc'), '')
self.assertEqual(R.slice(0, -2, 'abc'), 'a')
self.assertEqual(R.slice(0, -1, 'abc'), 'ab')
self.assertEqual(R.slice(0, -0, 'abc'), '')
self.assertEqual(R.slice(-2, -4, 'abc'), '')
self.assertEqual(R.slice(-2, -3, 'abc'), '')
self.assertEqual(R.slice(-2, -2, 'abc'), '')
self.assertEqual(R.slice(-2, -1, 'abc'), 'b')
self.assertEqual(R.slice(-2, -0, 'abc'), '')
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_slice.py
|
test_slice.py
|
import unittest
from test.helpers.listXf import listXf
import pamda as R
from pamda.private._has import _has
"""
https://github.com/ramda/ramda/blob/master/test/find.js
"""
obj1 = {'x': 100}
obj2 = {'x': 200}
a = [11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0]
def even(x): return x % 2 == 0 if isinstance(x, int) else False
def gt100(x): return x > 100 if isinstance(x, int) else False
def isStr(x): return isinstance(x, str)
def xGt100(o): return o.get('x') > 100 if _has(o, 'get') else False
intoArray = R.into([])
class TestFind(unittest.TestCase):
def test_returns_the_first_elemenet_that_satisfies_the_predicate(self):
self.assertEqual(10, R.find(even, a))
self.assertEqual(200, R.find(gt100, a))
self.assertEqual('cow', R.find(isStr, a))
self.assertEqual(obj2, R.find(xGt100, a))
def test_transduces_the_first_element_that_satisfies_the_predicate_into_an_array(self):
self.assertEqual([10], intoArray(R.find(even), a))
self.assertEqual([200], intoArray(R.find(gt100), a))
self.assertEqual(['cow'], intoArray(R.find(isStr), a))
self.assertEqual([obj2], intoArray(R.find(xGt100), a))
def test_returns_None_when_no_element_statisfies_the_predicate(self):
self.assertEqual(None, R.find(even, ['zing']))
def test_returns_None_in_array_when_no_element_statisfies_the_predicate(self):
self.assertEqual([None], intoArray(R.find(even), ['zing']))
def test_returns_None_when_given_an_empty_list(self):
self.assertEqual(None, R.find(even, []))
def test_returns_None_into_an_array_when_given_an_empty_list(self):
self.assertEqual([None], intoArray(R.find(even), []))
def test_dispatches_to_transformer_objects(self):
res = R.find(R.identity, listXf)
self.assertEqual(res.f, R.identity)
self.assertEqual(res.found, False)
self.assertEqual(res.xf, listXf)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_find.py
|
test_find.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/filter.js
"""
def even(x): return x % 2 == 0 if isinstance(x, int) else False
class FilterObject:
def filter(self, f):
return f('called f.filter')
class Obj:
def fn(self):
return 'called fn'
class TestFilter(unittest.TestCase):
def test_reduces_an_array_to_those_matching_a_filter(self):
self.assertEqual([2, 4], R.filter(even, [1, 2, 3, 4, 5]))
def test_returns_an_empty_array_if_no_element_matches(self):
self.assertEqual([], R.filter(lambda x: x > 100, [1, 9, 99]))
def test_returnsreduces_an_empty_array_if_asked_to_filter_an_empty_array(self):
self.assertEqual([], R.filter(lambda x: x > 100, []))
def test_filter_dict(self):
def positive(x): return x > 0
self.assertEqual({}, R.filter(positive, {}))
self.assertEqual({}, R.filter(positive, {'x': 0, 'y': 0, 'z': 0}))
self.assertEqual({'x': 1}, R.filter(positive, {'x': 1, 'y': 0, 'z': 0}))
self.assertEqual({'x': 1, 'y': 2}, R.filter(positive, {'x': 1, 'y': 2, 'z': 0}))
self.assertEqual({'x': 1, 'y': 2, 'z': 3}, R.filter(positive, {'x': 1, 'y': 2, 'z': 3}))
def test_filter_objects(self):
def positive(x): return x > 0
o1 = Obj()
o1.x = 0
o1.y = 0
o1.z = 0
o1_expected = Obj()
self.assertEqual(o1_expected.__dict__, R.filter(positive, o1).__dict__)
o2 = Obj()
o2.x = 1
o2.y = 0
o2.z = 0
o2_expected = Obj()
o2_expected.x = 1
self.assertEqual(o2_expected.__dict__, R.filter(positive, o2).__dict__)
o3 = Obj()
o3.x = 1
o3.y = 2
o3.z = 0
o3_expected = Obj()
o3_expected.x = 1
o3_expected.y = 2
self.assertEqual(o3_expected.__dict__, R.filter(positive, o3).__dict__)
o4 = Obj()
o4.x = 1
o4.y = 2
o4.z = 3
o4_expected = Obj()
o4_expected.x = 1
o4_expected.y = 2
o4_expected.z = 3
self.assertEqual(o4_expected.__dict__, R.filter(positive, o4).__dict__)
def test_filter_objects_keep_functions(self):
o = Obj()
o_filtered = R.filter(lambda x: x > 0, o)
self.assertEqual('called fn', o_filtered.fn())
def test_dispatches_to_passedin_nonArray_object_with_a_filter_method(self):
f = FilterObject()
self.assertEqual('called f.filter', R.filter(lambda s: s, f))
def test_correctly_uses_fantasy_land_implementations(self):
# TODO: add Maybe
pass
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_filter.py
|
test_filter.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/and.js
"""
class TestAnd(unittest.TestCase):
def test_compares_two_values_with_python_and(self):
self.assertEqual(True, R.And(True, True))
self.assertEqual(False, R.And(True, False))
self.assertEqual(False, R.And(False, True))
self.assertEqual(False, R.And(False, False))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_And.py
|
test_And.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/prop.js
"""
fred = {'name': 'Fred', 'age': 23}
class TestProp(unittest.TestCase):
def test_returns_a_function_that_fetches_the_appropriate_property(self):
nm = R.prop('name')
self.assertEqual('Fred', nm(fred))
def test_handles_number_as_property(self):
deities = ['Cthulhu', 'Dagon', 'Yog-Sothoth']
self.assertEqual('Cthulhu', R.prop(0, deities))
self.assertEqual('Dagon', R.prop(1, deities))
self.assertEqual('Yog-Sothoth', R.prop(2, deities))
self.assertEqual('Yog-Sothoth', R.prop(-1, deities))
def test_shows_the_same_behaviour_as_path_for_a_nonexistent_property(self):
# TODO: implement path
pass
def test_shows_the_same_behaviour_as_path_for_a_None_property(self):
# TODO: implement path
pass
def test_shows_the_same_behaviour_as_path_for_a_valid_property_and_object(self):
# TODO: implement path
pass
def test_shows_the_same_behaviour_as_path_for_a_None_object(self):
# TODO: implement path
pass
def test_returns_that_value_associated_to_a_property_given_valid_one(self):
# TODO: implement path
pass
# TODO: add any(string, anthing, object) related tests
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_prop.py
|
test_prop.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/identity.js
"""
class TestIdentity(unittest.TestCase):
def test_returns_its_first_argument(self):
self.assertEqual(None, R.identity(None))
self.assertEqual('foo', R.identity('foo'))
self.assertEqual('foo', R.identity('foo', 'bar'))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_identity.py
|
test_identity.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/reduce.js
"""
def add(a, b): return a + b
def mult(a, b): return a * b
def gen_int():
yield 1
yield 2
yield 3
yield 4
class ReduceObj:
def reduce(self, step, acc):
return 'override'
class TestReduce(unittest.TestCase):
def test_folds_simple_functions_over_arrays_with_the_supplied_accumulator(self):
self.assertEqual(10, R.reduce(add, 0, [1, 2, 3, 4]))
self.assertEqual(24, R.reduce(mult, 1, [1, 2, 3, 4]))
def test_dispatches_to_objects_that_implement_reduce(self):
obj = ReduceObj()
self.assertEqual('override', R.reduce(add, 0, obj))
self.assertEqual('override', R.reduce(add, 10, obj))
def test_returns_the_accumulator_for_an_empty_array(self):
self.assertEqual(0, R.reduce(add, 0, []))
self.assertEqual(1, R.reduce(mult, 1, []))
# TODO: add test case for concat
def test_returns_the_accumulator_for_an_None_list(self):
self.assertEqual(0, R.reduce(add, 0, None))
# TODO: add test case for concat
def test_short_circuits_with_reduced(self):
def addWithMaxOf10(acc, val): return R.reduced(acc) if acc + val > 10 else acc + val
self.assertEqual(10, R.reduce(addWithMaxOf10, 0, [1, 2, 3, 4]))
self.assertEqual(6, R.reduce(addWithMaxOf10, 0, [2, 4, 6, 8]))
class TestPythonStyleReduce(unittest.TestCase):
def test_with_yield(self):
self.assertEqual(10, R.reduce(add, 0, gen_int()))
self.assertEqual(24, R.reduce(mult, 1, gen_int()))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_reduce.py
|
test_reduce.py
|
import unittest
from random import randint
import pamda as R
def source(a, b, c):
return a * b * c
'''
https://github.com/ramda/ramda/blob/master/test/curryN.js
'''
class TestCurryN(unittest.TestCase):
def test_accepts_an_arity(self):
curried = R.curryN(3, source)
self.assertEqual(6, curried(1)(2)(3))
self.assertEqual(6, curried(1, 2)(3))
self.assertEqual(6, curried(1)(2, 3))
self.assertEqual(6, curried(1, 2, 3))
def test_can_be_partially_applied(self):
curry3 = R.curryN(3)
curried = curry3(source)
self.assertEqual(6, curried(1)(2)(3))
self.assertEqual(6, curried(1, 2)(3))
self.assertEqual(6, curried(1)(2, 3))
self.assertEqual(6, curried(1, 2, 3))
def test_supports_R_placeholder(self):
def f(*arguments):
return list(arguments)
g = R.curryN(3, f)
_ = R.__
self.assertEqual([1, 2, 3], g(1)(2)(3))
self.assertEqual([1, 2, 3], g(1)(2, 3))
self.assertEqual([1, 2, 3], g(1, 2)(3))
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, 2, 3)(1))
self.assertEqual([1, 2, 3], g(1, _, 3)(2))
self.assertEqual([1, 2, 3], g(1, 2, _)(3))
self.assertEqual([1, 2, 3], g(1, _, _)(2)(3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1)(3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1)(2))
self.assertEqual([1, 2, 3], g(1, _, _)(2, 3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1, 3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1, 2))
self.assertEqual([1, 2, 3], g(1, _, _)(_, 3)(2))
self.assertEqual([1, 2, 3], g(_, 2, _)(_, 3)(1))
self.assertEqual([1, 2, 3], g(_, _, 3)(_, 2)(1))
self.assertEqual([1, 2, 3], g(_, _, _)(_, _)(_)(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, _, _)(1, _, _)(_, _)(2, _)(_)(3))
def test_supports_functional_placeholder(self):
def f(*arguments):
return list(arguments)
g = R.curryN(3, f)
_ = {'@@functional/placeholder': True, 'x': randint(0, 100)}
self.assertEqual([1, 2, 3], g(1)(2)(3))
self.assertEqual([1, 2, 3], g(1)(2, 3))
self.assertEqual([1, 2, 3], g(1, 2)(3))
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, 2, 3)(1))
self.assertEqual([1, 2, 3], g(1, _, 3)(2))
self.assertEqual([1, 2, 3], g(1, 2, _)(3))
self.assertEqual([1, 2, 3], g(1, _, _)(2)(3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1)(3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1)(2))
self.assertEqual([1, 2, 3], g(1, _, _)(2, 3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1, 3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1, 2))
self.assertEqual([1, 2, 3], g(1, _, _)(_, 3)(2))
self.assertEqual([1, 2, 3], g(_, 2, _)(_, 3)(1))
self.assertEqual([1, 2, 3], g(_, _, 3)(_, 2)(1))
self.assertEqual([1, 2, 3], g(_, _, _)(_, _)(_)(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, _, _)(1, _, _)(_, _)(2, _)(_)(3))
def test_forwards_extra_arguments(self):
def f(*arguments):
return list(arguments)
g = R.curryN(3, f)
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3, 4], g(1, 2, 3, 4))
self.assertEqual([1, 2, 3, 4], g(1, 2)(3, 4))
self.assertEqual([1, 2, 3, 4], g(1)(2, 3, 4))
self.assertEqual([1, 2, 3, 4], g(1)(2)(3, 4))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_curryN.py
|
test_curryN.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/concat.js
"""
class Z1:
x = 'z1'
def concat(self, that):
return self.x + ' ' + that.x
class Z2:
x = 'z2'
z1 = Z1()
z2 = Z2()
class TestConcat(unittest.TestCase):
def test_adds_combines_the_elements_of_two_lists(self):
self.assertEqual(['a', 'b', 'c', 'd'], R.concat(['a', 'b'], ['c', 'd']))
self.assertEqual(['c', 'd'], R.concat([], ['c', 'd']))
def test_works_with_strings(self):
self.assertEqual('foobar', R.concat('foo', 'bar'))
self.assertEqual('x', R.concat('', 'x'))
self.assertEqual('x', R.concat('x', ''))
self.assertEqual('', R.concat('', ''))
def test_delegates_to_non_strings_object_with_a_concat_method_as_second_param(self):
self.assertEqual('z1 z2', R.concat(z1, z2))
def test_throws_if_attemping_to_combine_an_array_with_a_non_array(self):
with self.assertRaises(Exception):
R.concat([1], 2)
def test_throws_if_not_an_array_or_object_with_a_concat_method(self):
with self.assertRaises(Exception):
R.concat(z2, z1)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_concat.py
|
test_concat.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/difference.js
"""
M = [1, 2, 3, 4]
M2 = [1, 2, 3, 4, 1, 2, 3, 4]
N = [3, 4, 5, 6]
N2 = [3, 3, 4, 4, 5, 5, 6, 6]
Z = [3, 4, 5, 6, 10]
Z2 = [1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8]
class TestDifference(unittest.TestCase):
def test_finds_the_set_of_all_elements_in_the_first_list_not_contained_in_the_second(self):
self.assertEqual([1, 2], R.difference(M, N))
def test_does_not_allow_duplicates_in_the_output_even_if_the_input_lists_had_duplicates(self):
self.assertEqual([1, 2], R.difference(M2, N2))
def test_has_R_equals_semantics(self):
class Just():
def __init__(self, x):
self.value = x
def equals(self, x):
return isinstance(x, Just) and R.equals(x.value, self.value)
# TODO: ignore neg-zero and pos-zero check for now, due to simlicity
# self.assertEqual(1, len(R.difference([0], [-0])))
self.assertEqual(0, len(R.difference([float('nan')], [float('nan')])))
self.assertEqual(0, len(R.difference([Just([42])], [Just([42])])))
def test_works_for_array_of_different_lengths(self):
self.assertEqual([10], R.difference(Z, Z2))
self.assertEqual([1, 2, 7, 8], R.difference(Z2, Z))
def test_returns_an_empty_array_if_there_are_no_different_elements(self):
self.assertEqual([], R.difference(M2, M))
self.assertEqual([], R.difference(M, M2))
self.assertEqual([], R.difference([], M2))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_difference.py
|
test_difference.py
|
import unittest
from test.helpers.listXf import listXf
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/all.js
"""
def even(n): return n % 2 == 0
def T(): return True
def isFalse(x): return x == False
intoArray = R.into([])
class TestAll(unittest.TestCase):
def test_returns_true_if_all_elements_satisfy_the_predicate(self):
self.assertEqual(True, R.all(even, [2, 4, 6, 8, 10, 12]))
self.assertEqual(True, R.all(isFalse, [False, False, False]))
def test_false_if_any_element_fails_to_satisfy_the_predicate(self):
self.assertEqual(False, R.all(even, [2, 4, 6, 8, 9, 10]))
def test_true_for_an_empty_list(self):
self.assertEqual(True, R.all(T, []))
def test_true_into_array_if_all_elements_satisfy_the_predicate(self):
self.assertEqual([True], intoArray(R.all(even), [2, 4, 6, 8, 10, 12]))
self.assertEqual([True], intoArray(R.all(isFalse), [False, False, False]))
def test_false_into_array_if_any_element_failes_to_satisfy_the_predicate(self):
self.assertEqual([False], intoArray(R.all(even), [2, 4, 6, 8, 9, 10]))
def test_true_into_array_for_an_empty_list(self):
self.assertEqual([True], intoArray(R.all(T), []))
def test_works_with_more_complex_objects(self):
xs = [{'x': 'abc'}, {'x': 'ade'}, {'x': 'fghiajk'}]
def len3(o): return len(o.get('x')) == 3
def hasA(o): return 'a' in o.get('x')
self.assertEqual(False, R.all(len3, xs))
self.assertEqual(True, R.all(hasA, xs))
def test_dispatches_when_given_a_transformer_in_list_position(self):
res = R.all(even, listXf)
self.assertEqual(res.all, True)
self.assertEqual(res.f, even)
self.assertEqual(res.xf, listXf)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_all.py
|
test_all.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/reject.js
"""
def even(x): return x % 2 == 0 if isinstance(x, int) else False
class FilterObject:
def filter(self, f):
return f('called f.filter')
class Obj:
def fn(self):
return 'called fn'
class TestReject(unittest.TestCase):
def test_reduces_an_array_to_those_not_matching_a_filter(self):
self.assertEqual([1,3,5], R.reject(even, [1, 2, 3, 4, 5]))
def test_reduces_an_empty_array_if_no_element_matches(self):
self.assertEqual([], R.reject(lambda x: x < 100, [1, 9, 99]))
def test_reduces_an_empty_array_if_asked_to_filter_an_empty_array(self):
self.assertEqual([], R.reject(lambda x: x > 100, []))
def test_filter_dict(self):
def equals0(x): return x == 0
self.assertEqual({}, R.reject(equals0, {}))
self.assertEqual({}, R.reject(equals0, {'x': 0, 'y': 0, 'z': 0}))
self.assertEqual({'x': 1}, R.reject(equals0, {'x': 1, 'y': 0, 'z': 0}))
self.assertEqual({'x': 1, 'y': 2}, R.reject(equals0, {'x': 1, 'y': 2, 'z': 0}))
self.assertEqual({'x': 1, 'y': 2, 'z': 3}, R.reject(equals0, {'x': 1, 'y': 2, 'z': 3}))
def test_filter_objects(self):
def equals0(x): return x == 0
o1 = Obj()
o1.x = 0
o1.y = 0
o1.z = 0
o1_expected = Obj()
self.assertEqual(o1_expected.__dict__, R.reject(equals0, o1).__dict__)
o2 = Obj()
o2.x = 1
o2.y = 0
o2.z = 0
o2_expected = Obj()
o2_expected.x = 1
self.assertEqual(o2_expected.__dict__, R.reject(equals0, o2).__dict__)
o3 = Obj()
o3.x = 1
o3.y = 2
o3.z = 0
o3_expected = Obj()
o3_expected.x = 1
o3_expected.y = 2
self.assertEqual(o3_expected.__dict__, R.reject(equals0, o3).__dict__)
o4 = Obj()
o4.x = 1
o4.y = 2
o4.z = 3
o4_expected = Obj()
o4_expected.x = 1
o4_expected.y = 2
o4_expected.z = 3
self.assertEqual(o4_expected.__dict__, R.reject(equals0, o4).__dict__)
def test_filter_objects_keep_functions(self):
o = Obj()
o_filtered = R.reject(lambda x: x > 0, o)
self.assertEqual('called fn', o_filtered.fn())
def test_correctly_uses_fantasy_land_implementations(self):
# TODO: add Maybe
pass
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_reject.py
|
test_reject.py
|
import unittest
from functools import cmp_to_key
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/comparator.js
"""
class TestComparator(unittest.TestCase):
def test_builds_a_comparator_function_for_sorting_out_of_a_simple_predicate_that_reports_whether_the_first_param_is_smaller(self):
self.assertEqual([1, 1, 2, 3, 5, 8], sorted([3, 1, 8, 1, 2, 5], key=cmp_to_key(R.comparator(lambda a, b: a < b))))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_comparator.py
|
test_comparator.py
|
import math
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/divide.js
"""
class TestDivide(unittest.TestCase):
def test_divides_two_numbers(self):
self.assertEqual(4, R.divide(28, 7))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_divide.py
|
test_divide.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/countBy.js
"""
albums = [
{"title": 'Art of the Fugue', "artist": 'Glenn Gould', "genre": 'Baroque'},
{"title": 'A Farewell to Kings', "artist": 'Rush', "genre": 'Rock'},
{"title": 'Timeout', "artist": 'Dave Brubeck Quartet', "genre": 'Jazz'},
{"title": 'Fly By Night', "artist": 'Rush', "genre": 'Rock'},
{"title": 'Goldberg Variations', "artist": 'Daniel Barenboim', "genre": 'Baroque'},
{"title": 'New World Symphony', "artist": 'Leonard Bernstein', "genre": 'Romantic'},
{"title": 'Romance with the Unseen', "artist": 'Don Byron', "genre": 'Jazz'},
{"title": 'Somewhere In Time', "artist": 'Iron Maiden', "genre": 'Metal'},
{"title": 'In Times of Desparation', "artist": 'Danny Holt', "genre": 'Modern'},
{"title": 'Evita', "artist": 'Various', "genre": 'Broadway'},
{"title": 'Five Leaves Left', "artist": 'Nick Drake', "genre": 'Folk'},
{"title": 'The Magic Flute', "artist": 'John Eliot Gardiner', "genre": 'Classical'}
]
def deriveGenre():
remap = {
"Baroque": 'Classical',
"Modern": 'Classical',
"Romantic": 'Classical',
"Metal": 'Rock'
}
def f(album):
genre = R.prop('genre', album)
return remap.get(genre) or genre
return f
derivedGenre = deriveGenre()
class TestCountBy(unittest.TestCase):
def test_counts_by_a_simple_property_of_the_objects(self):
self.assertEqual(
{"Baroque": 2, "Rock": 2, "Jazz": 2, "Romantic": 1, "Metal": 1, "Modern": 1, "Broadway": 1, "Folk": 1, "Classical": 1},
R.countBy(R.prop('genre'), albums)
)
def test_counts_by_a_more_complex_function_on_the_objects(self):
self.assertEqual(
{"Classical": 5, "Rock": 3, "Jazz": 2, "Broadway": 1, "Folk": 1},
R.countBy(derivedGenre, albums)
)
def test_ignores_inherited_properties(self):
result = R.countBy(R.identity, ['abc', '__dict__'])
self.assertEqual(1, result['abc'])
self.assertEqual(1, result['__dict__'])
def test_can_act_as_transducer(self):
transducer = R.compose(
R.countBy(R.prop('genre')),
R.Map(R.adjust(1, lambda x: -x))
)
self.assertEqual(
{"Baroque": -2, "Rock": -2, "Jazz": -2, "Romantic": -1, "Metal": -1, "Modern": -1, "Broadway": -1, "Folk": -1, "Classical": -1},
R.into({}, transducer, albums)
)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_countBy.py
|
test_countBy.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/equals.js
"""
a = []
b = a
class TestEquals(unittest.TestCase):
def test_for_deep_equality_of_its_operands(self):
self.assertEqual(True, R.equals(100, 100))
self.assertEqual(False, R.equals(100, '100'))
self.assertEqual(True, R.equals(a, b))
def test_considers_equal_boolean_primitives_equal(self):
self.assertEqual(True, R.equals(True, True))
self.assertEqual(True, R.equals(False, False))
self.assertEqual(False, R.equals(True, False))
self.assertEqual(False, R.equals(False, True))
def test_considers_equivalent_boolean_objects_equal(self):
self.assertEqual(True, R.equals(bool(True), bool(True)))
self.assertEqual(True, R.equals(bool(False), bool(False)))
self.assertEqual(False, R.equals(bool(True), bool(False)))
self.assertEqual(False, R.equals(bool(False), bool(True)))
# NOTICE: python does not have bool object
def test_bool_with_objects(self):
class T:
def __bool__(self):
return True
class F:
def __bool__(self):
return False
t = T()
f = F()
self.assertEqual(True, R.equals(bool(t), True))
self.assertEqual(False, R.equals(bool(t), False))
self.assertEqual(True, R.equals(bool(f), False))
self.assertEqual(False, R.equals(bool(f), True))
def test_considers_equal_number_primitives_equal(self):
self.assertEqual(True, R.equals(0, 0))
self.assertEqual(False, R.equals(0, 1))
self.assertEqual(False, R.equals(1, 0))
def test_considers_equal_string_primitives_equal(self):
self.assertEqual(True, R.equals('', ''))
self.assertEqual(False, R.equals('', 'x'))
self.assertEqual(False, R.equals('x', ''))
self.assertEqual(True, R.equals('foo', 'foo'))
self.assertEqual(False, R.equals('foo', 'bar'))
self.assertEqual(False, R.equals('bar', 'foo'))
# Test python style str
self.assertEqual(True, R.equals('foo', "foo"))
self.assertEqual(True, R.equals('foo', """foo"""))
self.assertEqual(True, R.equals('foo', '''foo'''))
self.assertEqual(True, R.equals("foo", """foo"""))
self.assertEqual(True, R.equals("foo", '''foo'''))
self.assertEqual(True, R.equals("""foo""", '''foo'''))
self.assertEqual(True, R.equals('1', str(1)))
self.assertEqual(True, R.equals("1", str(1)))
self.assertEqual(True, R.equals('''1''', str(1)))
self.assertEqual(True, R.equals("""1""", str(1)))
def test_handle_dicts(self):
self.assertEqual(True, R.equals({}, {}))
self.assertEqual(True, R.equals({'a': 1, 'b': 2}, {'a': 1, 'b': 2}))
self.assertEqual(True, R.equals({'a': 1, 'b': 2}, {'b': 2, 'a': 1}))
self.assertEqual(False, R.equals({'a': 2, 'b': 2}, {'b': 2, 'a': 1}))
self.assertEqual(False, R.equals({'a': 1, 'b': 2, 'c': 3}, {'b': 2, 'a': 1}))
def test_considers_equivalent_arguments_objects_equal(self):
a = (lambda *args: args)()
b = (lambda *args: args)()
c = (lambda *args: args)(1, 2, 3)
d = (lambda *args: args)(1, 2, 3)
self.assertEqual(True, R.equals(a, b))
self.assertEqual(True, R.equals(b, a))
self.assertEqual(True, R.equals(c, d))
self.assertEqual(True, R.equals(d, c))
self.assertEqual(False, R.equals(a, c))
self.assertEqual(False, R.equals(c, a))
def test_considers_equivalent_error_objects_equal(self):
self.assertEqual(True, R.equals(ValueError('XXX'), ValueError('XXX')))
self.assertEqual(False, R.equals(ValueError('XXX'), ValueError('YYY')))
self.assertEqual(False, R.equals(IndexError('XXX'), ValueError('XXX')))
self.assertEqual(False, R.equals(IndexError('XXX'), ValueError('YYY')))
# regex is not built-in type in python, so we don't support it yet
# TODO: support regex
def test_handles_list(self):
listA = [1, 2, 3]
listB = [1, 3, 2]
self.assertEqual(False, R.equals([], {}))
self.assertEqual(False, R.equals(listA, listB))
def test_handles_reacursieve_data_structures(self):
c = {}
c['v'] = c
d = {}
d['v'] = d
e = []
e.append(e)
f = []
f.append(f)
nestA = {'a': [1, 2, {'c': 1}], 'b': 1}
nestB = {'a': [1, 2, {'c': 1}], 'b': 1}
nestC = {'a': [1, 2, {'c': 2}], 'b': 1}
# Python can not compare such recursive data structure
# self.assertEqual(True, R.equals(c, d))
# self.assertEqual(True, R.equals(e, f))
self.assertEqual(True, R.equals(nestA, nestB))
self.assertEqual(False, R.equals(nestA, nestC))
# date is not built-in type in python, so we don't support it yet
# TODO: support date
def test_compares_set_objects_by_value(self):
self.assertEqual(True, R.equals(set(), set()))
self.assertEqual(False, R.equals(set([]), set([1])))
self.assertEqual(False, R.equals(set([]), set([1])))
self.assertEqual(True, R.equals(set([1, 2]), set([2, 1])))
# self.assertEqual(True, R.equals(set([1, set([2, set([3])])]), set(1, [set([2, set([3])])])))
# self.assertEqual(True, R.equals(set([[1, 2, 3], [4, 5, 6]]), set([[4, 5, 6], [1, 2, 3]])))
# self.assertEqual(True, R.equals(set([[1, 2, 3], [4, 5, 6]]), set([[4, 5, 6], [7, 8, 9]])))
def test_compares_WeakMap_objects_by_identity(self):
"""
ref: https://docs.python.org/3/library/weakref.html
"""
class Dict(dict):
pass
d = Dict()
self.assertEqual(True, R.equals(d, d))
# TODO: catch up with weakref
# TODO: WeakSet if need
# self.assertEqual(False, R.equals(d, Dict()))
def test_dispatches_to_equals_method_recursively(self):
class Left:
def __init__(self, x):
self.value = x
def equals(self, x):
return isinstance(x, Left) and R.equals(self.value, x.value)
class Right:
def __init__(self, x):
self.value = x
def equals(self, x):
return isinstance(x, Right) and R.equals(self.value, x.value)
self.assertEqual(True, R.equals(Left([42]), Left([42])))
self.assertEqual(False, R.equals(Left([42]), Left([43])))
self.assertEqual(False, R.equals(Left(42), {'value': 42}))
self.assertEqual(False, R.equals({'value': 42}, Left(42)))
self.assertEqual(False, R.equals(Left(42), Right(42)))
self.assertEqual(False, R.equals(Right(42), Left(42)))
self.assertEqual(True, R.equals([Left(42)], [Left(42)]))
self.assertEqual(False, R.equals([Left(42)], [Right(42)]))
self.assertEqual(False, R.equals([Right(42)], [Left(42)]))
self.assertEqual(True, R.equals([Right(42)], [Right(42)]))
def test_is_commutative(self):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def equals(self, point):
return isinstance(point, Point) and self.x == point.x and self.y == point.y
class ColorPoint:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
def equals(self, point):
return isinstance(point, ColorPoint) and self.x == point.x and self.y == point.y and self.color == point.color
self.assertEqual(True, R.equals(Point(1, 2), Point(1, 2)))
self.assertEqual(True, R.equals(ColorPoint(1, 2, 'red'), ColorPoint(1, 2, 'red')))
self.assertEqual(False, R.equals(Point(1, 2), ColorPoint(1, 2, 'red')))
self.assertEqual(False, R.equals(ColorPoint(1, 2, 'red'), Point(1, 2)))
def test_clone(self):
pass
#TODO: clone
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_equals.py
|
test_equals.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/reduced.js
"""
class TestReduced(unittest.TestCase):
def test_wraps_a_value(self):
v = {}
self.assertEqual(v, R.reduced(v)['@@transducer/value'])
def test_flags_value_as_reduced(self):
self.assertEqual(True, R.reduced({})['@@transducer/reduced'])
def test_short_circuits_reduced(self):
def fn(acc, v):
result = acc + v
if result >= 10:
result = R.reduced(result)
return result
self.assertEqual(10, R.reduce(fn, 0, [1, 2, 3, 4, 5]))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_reduced.py
|
test_reduced.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/adjust.js
"""
class TestAdjust(unittest.TestCase):
def test_applies_the_given_function_to_the_value_at_the_given_index_of_the_supplied_array(self):
self.assertEqual([0, 1, 3, 3], R.adjust(2, R.add(1), [0, 1, 2, 3]))
def test_offsets_negative_indexes_from_the_end_of_the_array(self):
self.assertEqual([0, 2, 2, 3], R.adjust(-3, R.add(1), [0, 1, 2, 3]))
def test_returns_the_original_array_if_the_supplied_index_is_out_of_bounds(self):
arr = [0, 1, 2, 3]
self.assertEqual(arr, R.adjust(4, R.add(1), arr))
self.assertEqual(arr, R.adjust(-5, R.add(1), arr))
def test_does_not_mutate_the_original_array(self):
arr = [0, 1, 2, 3]
self.assertEqual([0, 1, 3, 3], R.adjust(2, R.add(1), arr))
self.assertEqual([0, 1, 2, 3], arr)
def test_accepts_an_array_like_object(self):
pass
# TODO: find a way to implement this in python style
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_adjust.py
|
test_adjust.py
|
import unittest
from inspect import getfullargspec
from random import randint
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/curry.js
"""
class TestCurry(unittest.TestCase):
def test_curries_a_single_value(self):
def e(a, b, c, d):
return (a + b * c) / d
f = R.curry(e)
g = f(12)
self.assertEqual(15, g(3, 6, 2))
def test_curries_multiple_values(self):
def e(a, b, c, d):
return (a + b * c) / d
f = R.curry(e)
g = f(12, 3)
self.assertEqual(15, g(6, 2))
h = f(12, 3, 6)
self.assertEqual(15, h(2))
def test_allows_further_currying_of_a_curried_function(self):
def e(a, b, c, d):
return (a + b * c) / d
f = R.curry(e)
g = f(12)
self.assertEqual(15, g(3, 6, 2))
h = g(3)
self.assertEqual(15, h(6, 2))
self.assertEqual(15, g(3, 6)(2))
def test_properly_reports_the_length_of_the_curried_function(self):
def e(a, b, c, d):
return (a + b * c) / d
f = R.curry(e)
fullargspec = getfullargspec(f)
self.assertEqual(4, len(fullargspec.args))
def test_supports_R_placeholder(self):
def f(a, b, c):
return [a, b, c]
g = R.curry(f)
_ = R.__
self.assertEqual([1, 2, 3], g(1)(2)(3))
self.assertEqual([1, 2, 3], g(1)(2, 3))
self.assertEqual([1, 2, 3], g(1, 2)(3))
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, 2, 3)(1))
self.assertEqual([1, 2, 3], g(1, _, 3)(2))
self.assertEqual([1, 2, 3], g(1, 2, _)(3))
self.assertEqual([1, 2, 3], g(1, _, _)(2)(3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1)(3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1)(2))
self.assertEqual([1, 2, 3], g(1, _, _)(2, 3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1, 3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1, 2))
self.assertEqual([1, 2, 3], g(1, _, _)(_, 3)(2))
self.assertEqual([1, 2, 3], g(_, 2, _)(_, 3)(1))
self.assertEqual([1, 2, 3], g(_, _, 3)(_, 2)(1))
self.assertEqual([1, 2, 3], g(_, _, _)(_, _)(_)(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, _, _)(1, _, _)(_, _)(2, _)(_)(3))
def test_supports_functional_placeholder(self):
def f(a, b, c):
return [a, b, c]
g = R.curry(f)
_ = {'@@functional/placeholder': True, 'x': randint(0, 100)}
self.assertEqual([1, 2, 3], g(1)(2)(3))
self.assertEqual([1, 2, 3], g(1)(2, 3))
self.assertEqual([1, 2, 3], g(1, 2)(3))
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, 2, 3)(1))
self.assertEqual([1, 2, 3], g(1, _, 3)(2))
self.assertEqual([1, 2, 3], g(1, 2, _)(3))
self.assertEqual([1, 2, 3], g(1, _, _)(2)(3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1)(3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1)(2))
self.assertEqual([1, 2, 3], g(1, _, _)(2, 3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1, 3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1, 2))
self.assertEqual([1, 2, 3], g(1, _, _)(_, 3)(2))
self.assertEqual([1, 2, 3], g(_, 2, _)(_, 3)(1))
self.assertEqual([1, 2, 3], g(_, _, 3)(_, 2)(1))
self.assertEqual([1, 2, 3], g(_, _, _)(_, _)(_)(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, _, _)(1, _, _)(_, _)(2, _)(_)(3))
def test_forwads_extra_arguments(self):
def f(a, b, c, *args):
return [a] + [b] + [c] + list(args)
g = R.curry(f)
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3, 4], g(1, 2, 3, 4))
self.assertEqual([1, 2, 3, 4], g(1, 2)(3, 4))
self.assertEqual([1, 2, 3, 4], g(1)(2, 3, 4))
self.assertEqual([1, 2, 3, 4], g(1)(2)(3, 4))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_curry.py
|
test_curry.py
|
import unittest
import pamda as R
from pamda.private._helper import funcArgsLength
"""
https://github.com/ramda/ramda/blob/master/test/reduceBy.js
"""
byType = R.prop('type')
def sumValues(acc, obj): return acc + obj['val']
sumInput = [
{'type': 'A', 'val': 10},
{'type': 'B', 'val': 20},
{'type': 'A', 'val': 30},
{'type': 'A', 'val': 40},
{'type': 'C', 'val': 50},
{'type': 'B', 'val': 60}
]
def grade(score):
if score < 65:
return 'F'
elif score < 70:
return 'D'
elif score < 80:
return 'C'
elif score < 90:
return 'B'
else:
return 'A'
students = [
{'name': 'Abby', 'score': 84},
{'name': 'Brad', 'score': 73},
{'name': 'Chris', 'score': 89},
{'name': 'Dianne', 'score': 99},
{'name': 'Eddy', 'score': 58},
{'name': 'Fred', 'score': 67},
{'name': 'Gillian', 'score': 91},
{'name': 'Hannah', 'score': 78},
{'name': 'Irene', 'score': 85},
{'name': 'Jack', 'score': 69}
]
def byGrade(student):
return grade(student['score'] or 0)
class TestReduceBy(unittest.TestCase):
def test_splits_the_list_into_groups_according_to_the_grouping_function(self):
def collectNames(acc, student): return acc + [student['name']]
self.assertEqual({
'A': ['Dianne', 'Gillian'],
'B': ['Abby', 'Chris', 'Irene'],
'C': ['Brad', 'Hannah'],
'D': ['Fred', 'Jack'],
'F': ['Eddy']
}, R.reduceBy(collectNames, [], byGrade, students))
def test_splits_the_list_into_mutation_free_groups(self):
def collectNames(acc, student):
acc.append(student['name'])
return acc
self.assertEqual({
'A': ['Dianne', 'Gillian'],
'B': ['Abby', 'Chris', 'Irene'],
'C': ['Brad', 'Hannah'],
'D': ['Fred', 'Jack'],
'F': ['Eddy']
}, R.reduceBy(collectNames, [], byGrade, students))
def test_returns_an_empty_object_if_given_an_empty_array(self):
self.assertEqual({}, R.reduceBy(sumValues, 0, byType, []))
def test_can_act_as_a_transducer(self):
reduceToSumByType = R.reduceBy(sumValues, 0)
sumByType = reduceToSumByType(byType)
self.assertEqual(
{'A': 800, 'B': 800, 'C': 500},
R.into(
{},
R.compose(sumByType, R.Map(R.adjust(1, R.multiply(10)))),
sumInput)
)
def test_short_circuits_with_reduced(self):
def collectNames(acc, student): return R.reduced(acc) if student['name'] == 'Fred' else acc + [student['name']]
self.assertEqual({
'A': ['Dianne'],
'B': ['Abby', 'Chris'],
'C': ['Brad'],
'F': ['Eddy']
}, R.reduceBy(collectNames, [], byGrade, students))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_reduceBy.py
|
test_reduceBy.py
|
import types
import unittest
import pamda as R
from pamda.private._helper import funcArgsLength
"""
https://github.com/ramda/ramda/blob/master/test/pipe.js
"""
class TestPipe(unittest.TestCase):
def test_is_a_variadic_function(self):
self.assertTrue(type(R.pipe) == types.FunctionType)
self.assertEqual(0, funcArgsLength(R.pipe))
def test_performs_left_to_right_function_composition(self):
def add(a, b, c): return a + b + c
def inc(a): return a + 1
def pow(a): return a ** 2
f = R.pipe(add, inc, pow)
self.assertEqual(3, funcArgsLength(f))
self.assertEqual(49, f(1, 2, 3))
def test_throw_if_given_no_arguments(self):
with self.assertRaises(Exception):
R.pipe()
def test_can_be_applied_to_one_argument(self):
def f(a, b, c): return [a, b, c]
g = R.pipe(f)
self.assertEqual(3, funcArgsLength(g))
self.assertEqual([1, 2, 3], g(1, 2, 3))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_pipe.py
|
test_pipe.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/append.js
"""
class TestAppend(unittest.TestCase):
def test_adds_the_element_to_the_end_of_the_list(self):
self.assertEqual(['x', 'y', 'z'], R.append('z', ['x', 'y']))
self.assertEqual(['x', 'y', ['a', 'z']], R.append(['a', 'z'], ['x', 'y']))
def test_works_on_empty_list(self):
self.assertEqual([1], R.append(1, []))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_append.py
|
test_append.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/sort.js
"""
class TestSort(unittest.TestCase):
def test_sorts_the_elements_of_a_list(self):
self.assertEqual([1, 1, 2, 3, 5, 8], R.sort(lambda a, b: a - b, [3, 1, 8, 1, 2, 5]))
def test_does_not_affect_the_list_passed_supplied(self):
arr = [3, 1, 8, 1, 2, 5]
self.assertEqual([1, 1, 2, 3, 5, 8], R.sort(lambda a, b: a - b, arr))
self.assertEqual([3, 1, 8, 1, 2, 5], arr)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_sort.py
|
test_sort.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/multiply.js
"""
class TestMultiply(unittest.TestCase):
def test_multiplies_together_two_numbers(self):
self.assertEqual(42, R.multiply(6, 7))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_multiply.py
|
test_multiply.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/reverse.js
"""
class TestReverse(unittest.TestCase):
def test_reverses_arrays(self):
self.assertEqual([], R.reverse([]))
self.assertEqual([1], R.reverse([1]))
self.assertEqual([1, 2], R.reverse([2, 1]))
self.assertEqual([1, 2, 3], R.reverse([3, 2, 1]))
def test_reverses_twice_an_array_should_be_the_array_itself(self):
self.assertEqual([1, 2, 3], R.reverse(R.reverse([1, 2, 3])))
def test_reverses_strings(self):
self.assertEqual('', R.reverse(''))
self.assertEqual('1', R.reverse('1'))
self.assertEqual('12', R.reverse('21'))
self.assertEqual('123', R.reverse('321'))
def test_reverses_twice_a_string_should_be_the_string_itself(self):
self.assertEqual('123', R.reverse(R.reverse('123')))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_reverse.py
|
test_reverse.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/nth.js
"""
arr = ['foo', 'bar', 'baz', 'quux']
class TestNth(unittest.TestCase):
def test_accepts_positive_offsets(self):
self.assertEqual('foo', R.nth(0, arr))
self.assertEqual('bar', R.nth(1, arr))
self.assertEqual('baz', R.nth(2, arr))
self.assertEqual('quux', R.nth(3, arr))
self.assertEqual(None, R.nth(4, arr))
self.assertEqual('a', R.nth(0, 'abc'))
self.assertEqual('b', R.nth(1, 'abc'))
self.assertEqual('c', R.nth(2, 'abc'))
self.assertEqual('', R.nth(3, 'abc'))
def test_accepts_negative_offsets(self):
self.assertEqual('foo', R.nth(-4, arr))
self.assertEqual('bar', R.nth(-3, arr))
self.assertEqual('baz', R.nth(-2, arr))
self.assertEqual('quux', R.nth(-1, arr))
self.assertEqual(None, R.nth(-5, arr))
self.assertEqual('a', R.nth(-3, 'abc'))
self.assertEqual('b', R.nth(-2, 'abc'))
self.assertEqual('c', R.nth(-1, 'abc'))
self.assertEqual('', R.nth(-4, 'abc'))
def test_throws_if_applied_to_None(self):
with self.assertRaises(TypeError):
R.nth(0, None)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_nth.py
|
test_nth.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/keys.js
"""
obj = {'a': 100, 'b': [1, 2, 3], 'c': {'x': 200, 'y': 300}, 'd': 'D', 'e': None}
class A:
def __init__(self):
self.a = 'a'
class B(A):
def __init__(self):
self.b = 'b'
class C(A):
def __init__(self):
super().__init__()
self.c = 'c'
class TestKeys(unittest.TestCase):
def test_returns_an_array_of_the_given_object_own_keys(self):
self.assertEqual(['a', 'b', 'c', 'd', 'e'], R.keys(obj))
def test_works_with_attribute_override(self):
a, b, c = A(), B(), C()
self.assertEqual(['a'], R.keys(a))
self.assertEqual(['b'], R.keys(b))
self.assertEqual(['a', 'c'], R.keys(c))
def test_works_with_primitives(self):
self.assertEqual([], R.keys(None))
self.assertEqual([], R.keys(55))
self.assertEqual([], R.keys('foo'))
self.assertEqual([], R.keys(True))
self.assertEqual([], R.keys(False))
self.assertEqual([], R.keys([]))
self.assertEqual([], R.keys({}))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_keys.py
|
test_keys.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/differenceWith.js
"""
Ro = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
Ro2 = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
So = [{'a': 3}, {'a': 4}, {'a': 5}, {'a': 6}]
So2 = [{'a': 3}, {'a': 4}, {'a': 5}, {'a': 6}, {'a': 3}, {'a': 4}, {'a': 5}, {'a': 6}]
def eqA(r, s): return r['a'] == s['a']
def identical(a, b): return a == b
class TestDifferenceWith(unittest.TestCase):
def test_combines_two_lists_into_the_set_of_all_their_elements_based_on_the_pased_in_equality_predicate(self):
self.assertEqual([{'a': 1}, {'a': 2}], R.differenceWith(eqA, Ro, So))
def test_does_not_allow_duplicates_in_the_output_even_if_the_input_lists_had_duplicates(self):
self.assertEqual([{'a': 1}, {'a': 2}], R.differenceWith(eqA, Ro2, So2))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_differenceWith.py
|
test_differenceWith.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/tail.js
"""
class TestTail(unittest.TestCase):
def test_returns_the_tail_of_an_ordered_collection(self):
self.assertEqual([2, 3], R.tail([1, 2, 3]))
self.assertEqual([3], R.tail([2, 3]))
self.assertEqual([], R.tail([3]))
self.assertEqual([], R.tail([]))
self.assertEqual('bc', R.tail('abc'))
self.assertEqual('c', R.tail('bc'))
self.assertEqual('', R.tail('c'))
self.assertEqual('', R.tail(''))
def test_exception_if_work_with_none(self):
with self.assertRaises(TypeError):
R.tail(None)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_tail.py
|
test_tail.py
|
import unittest
import pamda as R
from .helpers import listXf
"""
https://github.com/ramda/ramda/blob/master/test/map.js
"""
def times2(x): return x * 2
def add1(x): return x + 1
def dec(x): return x - 1
intoArray = R.into([])
class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
super().__init__()
self.b = 2
class C:
def __init__(self, x):
self.x = x
def map(self, f):
return f(self.x)
class TestMap(unittest.TestCase):
def test_maps_simple_functions_over_array(self):
self.assertEqual([2, 4, 6, 8], R.Map(times2, [1, 2, 3, 4]))
def test_maps_simple_functions_into_array(self):
self.assertEqual([2, 4, 6, 8], intoArray(R.Map(times2), [1, 2, 3, 4]))
def test_maps_over_objects(self):
a, b = A(), B()
mappedA = R.Map(dec, a)
mappedB = R.Map(dec, b)
self.assertEqual(0, mappedA.a)
self.assertEqual(0, mappedB.a)
self.assertEqual(1, mappedB.b)
# make sure not change original objects
self.assertEqual(1, a.a)
self.assertEqual(1, b.a)
self.assertEqual(2, b.b)
def test_maps_over_dicts(self):
self.assertEqual({}, R.Map(dec, {}))
self.assertEqual({'x': 3, 'y': 4, 'z': 5}, R.Map(dec, {'x': 4, 'y': 5, 'z': 6}))
def test_interprets_as_a_functor(self):
def f(a): return a - 1
def g(b): return b * 2
h = R.Map(f, g)
self.assertEqual((10 * 2) - 1, h(10))
def test_dispatches_to_objects_that_implement_map(self):
c = C(42)
self.assertEqual(41, R.Map(dec, c))
def test_dispatches_to_transformer_objects(self):
o = R.Map(add1, listXf)
self.assertEqual(add1, o.f)
self.assertEqual(listXf, o.xf)
def test_throws_an_Exception_on_None(self):
with self.assertRaises(Exception):
R.Map(times2, None)
def test_composes(self):
mdouble = R.Map(times2)
mdec = R.Map(dec)
self.assertEqual([19, 39, 59], mdec(mdouble([10, 20, 30])))
def test_can_compose_transducer_style(self):
mdouble = R.Map(times2)
mdec = R.Map(dec)
xcomp = mdec(mdouble(listXf))
self.assertEqual(dec, xcomp.f)
self.assertEqual(listXf, xcomp.xf.xf)
self.assertEqual(times2, xcomp.xf.f)
def test_correctly_users_fantasy_land_implementations(self):
# TODO: fantasy-land
pass
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_map.py
|
test_map.py
|
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/into.js
"""
add = R.add
def isOdd(b): return b % 2 != 0
addXf = {
'@@transducer/step': add,
'@@transducer/init': R.always(0),
'@@transducer/result': R.identity
}
class TestInto(unittest.TestCase):
def test_transduces_into_arrays(self):
self.assertEqual([2, 3, 4, 5], R.into([], R.Map(add(1)), [1, 2, 3, 4]))
self.assertEqual([1, 3], R.into([], R.filter(isOdd), [1, 2, 3, 4]))
# TODO: take
def test_transduces_into_strings(self):
self.assertEqual('2345', R.into('', R.Map(add(1)), [1, 2, 3, 4]))
self.assertEqual('13', R.into('', R.filter(isOdd), [1, 2, 3, 4]))
# TODO: take
def test_transduces_into_dicts(self):
self.assertEqual({'a': 1, 'b': 2}, R.into({}, R.identity, [['a', 1], ['b', 2]]))
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, R.into({}, R.identity, [{'a': 1}, {'b': 2, 'c': 3}]))
def test_dispatches_to_objects_that_implement_reduce(self):
pass
# TODO: we do not support object currently
def test_allows_custom_transformer(self):
intoSum = R.into(addXf)
add2 = R.Map(add(2))
result = intoSum(add2)
self.assertEqual(18, result([1, 2, 3, 4]))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_into.py
|
test_into.py
|
import types
import unittest
import pamda as R
from pamda.private._helper import funcArgsLength
"""
https://github.com/ramda/ramda/blob/master/test/compose.js
"""
class TestCompose(unittest.TestCase):
def test_is_a_variadic_function(self):
self.assertTrue(type(R.compose) == types.FunctionType)
self.assertEqual(0, funcArgsLength(R.compose))
def test_performs_right_to_left_function_composition(self):
def add(a, b, c): return a + b + c
def inc(a): return a + 1
def pow(a): return a ** 2
f = R.compose(pow, inc, add)
self.assertEqual(3, funcArgsLength(f))
self.assertEqual(49, f(1, 2, 3))
def test_throw_if_given_no_arguments(self):
with self.assertRaises(Exception):
R.compose()
def test_can_be_applied_to_one_argument(self):
def f(a, b, c): return [a, b, c]
g = R.compose(f)
self.assertEqual(3, funcArgsLength(g))
self.assertEqual([1, 2, 3], g(1, 2, 3))
def test_composes_two_functions(self):
def inc(a): return a + 1
def pow(a): return a ** 2
self.assertEqual(inc(pow(2)), R.compose(inc, pow)(2))
def test_associative(self):
def f(a): return a + 1
def g(a): return a ** 2
def h(a): return a * 2
x = 2
result = f(g(h(x)))
self.assertEqual(result, R.compose(f, g, h)(x))
self.assertEqual(result, R.compose(f, R.compose(g, h))(x))
self.assertEqual(result, R.compose(R.compose(f, g), h)(x))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_compose.py
|
test_compose.py
|
import math
import unittest
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/add.js
"""
class TestAdd(unittest.TestCase):
def test_adds_together_two_numbers(self):
self.assertEqual(10, R.add(3, 7))
def test_coerces_its_arguments_to_numbers(self):
self.assertEqual(3, R.add('1', '2'))
self.assertEqual(3, R.add(1, '2'))
self.assertEqual(1, R.add(True, False))
self.assertTrue(math.isnan(R.add(None, None)))
def test_float(self):
self.assertEqual(4.2, R.add(1.1, 3.1))
self.assertEqual(4.2, R.add('1.1', 3.1))
self.assertEqual(4.2, R.add('1.1', '3.1'))
class TestAddProperties(unittest.TestCase):
def test_commutative(self):
self.assertEqual(R.add(1, 2), R.add(2, 1))
def test_associative(self):
self.assertEqual(R.add(1, R.add(2, 3)), R.add(R.add(1, 2), 3))
def test_identity(self):
self.assertEqual(R.add(1, 0), 1)
self.assertEqual(1, R.add(0, 1))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_add.py
|
test_add.py
|
import unittest
from datetime import date
import pamda as R
"""
https://github.com/ramda/ramda/blob/master/test/always.js
"""
class TestAlways(unittest.TestCase):
def test_returns_a_function_that_returns_the_object_initially_supplied(self):
theMeaning = R.always(42)
self.assertEqual(42, theMeaning())
self.assertEqual(42, theMeaning(10))
self.assertEqual(42, theMeaning(False))
def test_works_with_various_types(self):
self.assertEqual(False, R.always(False)())
self.assertEqual('abc', R.always('abc')())
self.assertEqual({'a': 1, 'b': 2}, R.always({'a': 1, 'b': 2})())
self.assertEqual({'a': 1, 'b': 2}, R.always({'a': 1, 'b': 2})())
obj = {'a': 1, 'b': 2}
self.assertEqual(obj, R.always(obj)())
self.assertEqual(obj, R.always(obj)())
now = date(1776, 6, 4)
self.assertEqual(date(1776, 6, 4), R.always(now)())
self.assertEqual(None, R.always(None)())
class TestAlwaysProperties(unittest.TestCase):
def test_returns_initial_argument(self):
a = 42
b = 27
f = R.always(a)
self.assertTrue(f() == a)
self.assertTrue(f(b) == a)
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/test_always.py
|
test_always.py
|
listXf = {
'@@transducer/init': lambda: [],
'@@transducer/step': lambda acc, x: acc + x,
'@@transducer/result': lambda x: x
}
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/helpers/listXf.py
|
listXf.py
|
from .listXf import listXf
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/helpers/__init__.py
|
__init__.py
|
import unittest
import pamda as R
from pamda.private._curry2 import _curry2
"""
https://github.com/ramda/ramda/blob/master/test/internal/_curry2.js
"""
class Test_Curry2(unittest.TestCase):
def test_supports_placeholder(self):
def f(a, b): return [a, b]
g = _curry2(f)
_ = R.__
self.assertEqual([1, 2], g(1)(2))
self.assertEqual([1, 2], g(1, 2))
self.assertEqual([1, 2], g(_, 2)(1))
self.assertEqual([1, 2], g(1, _)(2))
self.assertEqual([1, 2], g(_, _)(1)(2))
self.assertEqual([1, 2], g(_, _)(1, 2))
self.assertEqual([1, 2], g(_, _)(_)(1, 2))
self.assertEqual([1, 2], g(_, _)(_, 2)(1))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/private/test__curry2.py
|
test__curry2.py
|
import unittest
import pamda as R
from pamda.private._curry3 import _curry3
"""
https://github.com/ramda/ramda/blob/master/test/internal/_curry3.js
"""
class Test_Curry3(unittest.TestCase):
def test_supports_placeholder(self):
def f(a, b, c): return [a, b, c]
g = _curry3(f)
_ = R.__
self.assertEqual([1, 2, 3], g(1)(2)(3))
self.assertEqual([1, 2, 3], g(1)(2, 3))
self.assertEqual([1, 2, 3], g(1, 2)(3))
self.assertEqual([1, 2, 3], g(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, 2, 3)(1))
self.assertEqual([1, 2, 3], g(1, _, 3)(2))
self.assertEqual([1, 2, 3], g(1, 2, _)(3))
self.assertEqual([1, 2, 3], g(1, _, _)(2)(3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1)(3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1)(2))
self.assertEqual([1, 2, 3], g(1, _, _)(2, 3))
self.assertEqual([1, 2, 3], g(_, 2, _)(1, 3))
self.assertEqual([1, 2, 3], g(_, _, 3)(1, 2))
self.assertEqual([1, 2, 3], g(1, _, _)(_, 3)(2))
self.assertEqual([1, 2, 3], g(_, 2, _)(_, 3)(1))
self.assertEqual([1, 2, 3], g(_, _, 3)(_, 2)(1))
self.assertEqual([1, 2, 3], g(_, _, _)(_, _)(1, 2, 3))
self.assertEqual([1, 2, 3], g(_, _, _)(1, _, _)(_, _)(2, _)(_)(3))
if __name__ == '__main__':
unittest.main()
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/test/private/test__curry3.py
|
test__curry3.py
|
from .private._arity import _arity
from .private._curry1 import _curry1
from .private._curry2 import _curry2
from .private._curryN import _curryN
curryN = _curry2(lambda n, fn: _curry1(fn) if n == 1 else _arity(n, _curryN(n, [], fn)))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/curryN.py
|
curryN.py
|
import copy
from .curryN import curryN
from .keys import keys
from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._has import _has
from .private._helper import funcArgsLength
from .private._isFunction import _isFunction
from .private._map import _map
from .private._reduce import _reduce
from .private._xmap import _xmap
def inner_map(fn, functor):
def inner_reduce(acc, key):
"""
There are 2 cases of functor
case 1: functor is a dict or an instance with get method
case 2: functor is an instance of some classes
"""
if isinstance(functor, dict) or _has(functor, 'get'):
acc[key] = fn(functor.get(key))
else:
setattr(acc, key, fn(getattr(acc, key, None)))
return acc
if functor is None:
raise Exception('Can not work with None')
if _isFunction(functor):
return curryN(funcArgsLength(functor), lambda *arguments: fn(functor(*arguments)))
if isinstance(functor, (list, tuple)):
return _map(fn, functor)
return _reduce(inner_reduce, {} if isinstance(functor, dict) or _has(functor, 'get') else copy.deepcopy(functor), keys(functor))
Map = _curry2(_dispatchable(['fantasy-land/map', 'map'], _xmap, inner_map))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/map.py
|
map.py
|
from .private._curry1 import _curry1
reverse = _curry1(lambda arr: arr[::-1])
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/reverse.py
|
reverse.py
|
__ = {'@@functional/placeholder': True}
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/__.py
|
__.py
|
from .private._concat import _concat
from .private._curry3 import _curry3
def inner_adjust(idx, fn, arr):
length = len(arr)
if idx >= length or idx < -length:
return arr
_idx = (length + idx) % length
_arr = _concat(arr)
_arr[_idx] = fn(arr[_idx])
return _arr
adjust = _curry3(inner_adjust)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/adjust.py
|
adjust.py
|
from .private._curry3 import _curry3
from .private._helper import getAttribute
from .private._isTransformer import _isTransformer
from .private._stepCat import _stepCat
from .private._xReduce import _xReduce
def inner_into(acc, transducer, arr):
xf = transducer(acc if _isTransformer(acc) else _stepCat(acc))
return _xReduce(xf, getAttribute(xf, '@@transducer/init')(), arr)
into = _curry3(inner_into)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/into.py
|
into.py
|
from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._xall import _xall
def inner_all(fn, arr):
idx = 0
while idx < len(arr):
if not fn(arr[idx]):
return False
idx += 1
return True
all = _curry2(_dispatchable(['all'], _xall, inner_all))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/all.py
|
all.py
|
from .private._curry2 import _curry2
from .private._equals import _equals
equals = _curry2(_equals)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/equals.py
|
equals.py
|
from math import isnan
from numbers import Number
from .equals import equals
from .find import find
from .private._curry2 import _curry2
def inner_difference(first, second):
out = []
idx = 0
toFilterOut = set()
for item in second:
toFilterOut.add(item)
firstLen = len(first)
while idx < firstLen:
if isinstance(first[idx], Number) and isnan(first[idx]):
if not find(isnan, list(toFilterOut)):
toFilterOut.add(first[idx])
out.append(first[idx])
elif not find(equals(first[idx]), list(toFilterOut)):
toFilterOut.add(first[idx])
out.append(first[idx])
idx += 1
return out
difference = _curry2(inner_difference)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/difference.py
|
difference.py
|
from .private._curry1 import _curry1
from .private._has import _has
from .private._isFunction import _isFunction
def inner_keys(obj):
"""
If the given obj has method keys(), just call it and return key list.
Otherwise,
return all attributes defined directly inside of the class, in other words, return obj.__dict__,
if obj does not has __dict__ attribute, return empty list.
class A:
a = 1
def __init__(self):
self.b = 2
class B(A):
c = 3
def __init__(self):
self.d = 4
b = B()
keys(b) # ['d'], only attribute d will be included.
"""
if _has(obj, 'keys') and _isFunction(obj.keys):
return list(obj.keys())
elif _has(obj, '__dict__'):
return list(obj.__dict__)
else:
return []
keys = _curry1(inner_keys)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/keys.py
|
keys.py
|
from .private._curry2 import _curry2
"""
Since in JavaScript we can represent key-value as object,
but in Python, we can't.
So we treat objOf only works for dict in Python.
But for the naming convention, we keep the name of objOf.
"""
objOf = _curry2(lambda key, val: {key: val})
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/objOf.py
|
objOf.py
|
from .private._curry3 import _curry3
from .private._isFunction import _isFunction
from .private._xReduce import _xReduce
from .private._xwrap import _xwrap
def inner_reduce(xf, acc, arr):
return _xReduce(_xwrap(xf) if _isFunction(xf) else xf, acc, arr)
reduce = _curry3(inner_reduce)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/reduce.py
|
reduce.py
|
from .private._curry2 import _curry2
multiply = _curry2(lambda a, b: a * b)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/multiply.py
|
multiply.py
|
from .private._curry1 import _curry1
tail = _curry1(lambda arr: arr[1:])
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/tail.py
|
tail.py
|
import copy
from .keys import keys
from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._filter import _filter
from .private._has import _has
from .private._isArrayLike import _isArrayLike
from .private._reduce import _reduce
from .private._xfilter import _xfilter
def inner_filter(pred, filterable):
if _isArrayLike(filterable):
return _filter(pred, filterable)
else:
def inner_reduce(acc, key):
"""
There are 2 cases of filterable
case 1: filterable is a dict or an instance with get method
case 2: filterable is an instance of some classes
"""
if isinstance(filterable, dict) or _has(filterable, 'get'):
if pred(filterable.get(key)):
acc[key] = filterable.get(key)
else:
# This is special, because we deepcopy the original object,
# so we delete attr from original object if not match
if not pred(getattr(filterable, key, None)):
delattr(acc, key)
return acc
return _reduce(inner_reduce, {} if isinstance(filterable, dict) or _has(filterable, 'get') else copy.deepcopy(filterable), keys(filterable))
filter = _curry2(_dispatchable(['fantasy-land/filter', 'filter'], _xfilter, inner_filter))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/filter.py
|
filter.py
|
from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._xany import _xany
def inner_any(fn, arr):
idx = 0
while idx < len(arr):
if fn(arr[idx]):
return True
idx += 1
return False
any = _curry2(_dispatchable(['any'], _xany, inner_any))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/any.py
|
any.py
|
from .private._curry3 import _curry3
slice = _curry3(lambda fromIndex, toIndex, arr: arr[fromIndex:toIndex])
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/slice.py
|
slice.py
|
from .private._curry3 import _curry3
from .private._includesWith import _includesWith
def inner_differenceWith(pred, first, second):
out = []
idx = 0
firstLength = len(first)
while idx < firstLength:
if (not _includesWith(pred, first[idx], second)) and (not _includesWith(pred, first[idx], out)):
out.append(first[idx])
idx += 1
return out
differenceWith = _curry3(inner_differenceWith)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/differenceWith.py
|
differenceWith.py
|
from .private._curry1 import _curry1
def inner_always(val):
def f(*ignored):
return val
return f
always = _curry1(inner_always)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/always.py
|
always.py
|
from .private._curry1 import _curry1
def inner_comparator(pred):
def comparator(a, b):
if pred(a, b):
return -1
elif pred(b, a):
return 1
else:
return 0
return comparator
comparator = _curry1(inner_comparator)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/comparator.py
|
comparator.py
|
from .private._curry2 import _curry2
def inner_and(a, b):
return a and b
And = _curry2(inner_and)
"""
Because `and` is a keyword in Python, so we instead use And.
"""
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/And.py
|
And.py
|
from .private._curry2 import _curry2
from .private._helper import getAttribute
from .private._isArray import _isArray
from .private._isFunction import _isFunction
from .private._isString import _isString
def inner_concat(a, b):
if _isArray(a):
if _isArray(b):
return a + b
# TODO: Change to R.toString method
raise Exception(f"{b} is not an array")
if _isString(a):
if _isString(b):
return a + b
# TODO: Change to R.toString method
raise Exception(f"{b} is not a string")
if a is not None and _isFunction(getAttribute(a, 'fantasy-land/concat')):
return a.get('fantasy-land/concat')(b)
if a is not None and _isFunction(a.concat):
return a.concat(b)
raise Exception(f'{a} does not have a method named "concat" or "fantasy-land/concat"')
concat = _curry2(inner_concat)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/concat.py
|
concat.py
|
from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._xfind import _xfind
def inner_find(fn, arr):
idx = 0
while idx < len(arr):
if fn(arr[idx]):
return arr[idx]
idx += 1
find = _curry2(_dispatchable(['find'], _xfind, inner_find))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/find.py
|
find.py
|
from .curryN import curryN
from .private._curry1 import _curry1
from .private._helper import funcArgsLength
curry = _curry1(lambda fn: curryN(funcArgsLength(fn), fn))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/curry.py
|
curry.py
|
from .private._curry2 import _curry2
def inner_divide(a, b):
return a / b
divide = _curry2(inner_divide)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/divide.py
|
divide.py
|
from .private._clone import _clone
from .private._curryN import _curryN
from .private._dispatchable import _dispatchable
from .private._has import _has
from .private._helper import getAttribute
from .private._reduced import _reduced
from .private._xReduce import _xReduce
from .private._xReduceBy import _xReduceBy
from .private._xwrap import _xwrap
def inner_reduceBy(valueFn, valueAcc, keyFn, arr):
def inner_xwrap(acc, elt):
key = keyFn(elt)
value = valueFn(acc[key] if _has(acc, key) else _clone(valueAcc, deep=False), elt)
if value and getAttribute(value, '@@transducer/reduced'):
return _reduced(acc)
acc[key] = value
return acc
xf = _xwrap(inner_xwrap)
return _xReduce(xf, {}, arr)
reduceBy = _curryN(4, [], _dispatchable([], _xReduceBy, inner_reduceBy))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/reduceBy.py
|
reduceBy.py
|
from .filter import filter
from .private._complement import _complement
from .private._curry2 import _curry2
reject = _curry2(lambda pred, filterable: filter(_complement(pred), filterable))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/reject.py
|
reject.py
|
from .pipe import pipe
from .reverse import reverse
def compose(*arguments):
if len(arguments) == 0:
raise Exception('compose requires at least one argument')
return pipe(*reverse(arguments))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/compose.py
|
compose.py
|
from .private._arity import _arity
from .private._helper import funcArgsLength
from .private._pipe import _pipe
from .reduce import reduce
from .tail import tail
def pipe(*arguments):
if len(arguments) == 0:
raise Exception('pipe requires at least one argument')
return _arity(
funcArgsLength(arguments[0]),
reduce(_pipe, arguments[0], tail(list(arguments)))
)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/pipe.py
|
pipe.py
|
from .private._curry1 import _curry1
from .private._identity import _identity
identity = _curry1(_identity)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/identity.py
|
identity.py
|
from .private._concat import _concat
from .private._curry2 import _curry2
def inner_append(el, arr):
return _concat(arr, [el])
append = _curry2(inner_append)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/append.py
|
append.py
|
from .private._curry2 import _curry2
from .private._helper import toNumber
add = _curry2(lambda a, b: toNumber(a) + toNumber(b))
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/add.py
|
add.py
|
from functools import cmp_to_key
from .private._curry2 import _curry2
def inner_sort(comparator, arr):
return sorted(arr, key=cmp_to_key(comparator))
sort = _curry2(inner_sort)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/sort.py
|
sort.py
|
from .reduceBy import reduceBy
countBy = reduceBy(lambda acc, _: acc + 1, 0)
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/countBy.py
|
countBy.py
|
from .__ import __
from .add import add
from .adjust import adjust
from .all import all
from .always import always
from .And import And
from .any import any
from .append import append
from .comparator import comparator
from .compose import compose
from .concat import concat
from .countBy import countBy
from .curry import curry
from .curryN import curryN
from .difference import difference
from .differenceWith import differenceWith
from .divide import divide
from .equals import equals
from .filter import filter
from .find import find
from .identity import identity
from .into import into
from .keys import keys
from .map import Map
from .multiply import multiply
from .nth import nth
from .objOf import objOf
from .pipe import pipe
from .prop import prop
from .reduce import reduce
from .reduceBy import reduceBy
from .reduced import reduced
from .reject import reject
from .reverse import reverse
from .slice import slice
from .sort import sort
from .tail import tail
|
zydmayday-pamda
|
/zydmayday-pamda-0.0.9.tar.gz/zydmayday-pamda-0.0.9/pamda/__init__.py
|
__init__.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.