How to use truncate method in chai

Best JavaScript code snippet using chai

divmodself.js

Source:divmodself.js Github

copy

Full Screen

...55 })()56 } catch (e) {}57}58// Assorted tests.59function sdiv_truncate(y) {60 return (y / y)|0;61}62assertEq(sdiv_truncate(5), 1);63assertEq(sdiv_truncate(1), 1);64assertEq(sdiv_truncate(-1), 1);65assertEq(sdiv_truncate(0), 0);66assertEq(sdiv_truncate(-0), 0);67assertEq(sdiv_truncate(1.1), 1);68assertEq(sdiv_truncate(-1.1), 1);69assertEq(sdiv_truncate(Infinity), 0);70assertEq(sdiv_truncate(NaN), 0);71assertEq(sdiv_truncate(undefined), 0);72assertEq(sdiv_truncate(null), 0);73function sdiv(y) {74 return y / y;75}76assertEq(sdiv(5), 1);77assertEq(sdiv(1), 1);78assertEq(sdiv(-1), 1);79assertEq(sdiv(0), NaN);80assertEq(sdiv(-0), NaN);81assertEq(sdiv(1.1), 1);82assertEq(sdiv(-1.1), 1);83assertEq(sdiv(Infinity), NaN);84assertEq(sdiv(NaN), NaN);85assertEq(sdiv(undefined), NaN);86assertEq(sdiv(null), NaN);87function udiv_truncate(y) {88 var yu = y>>>0;89 return (yu / yu)|0;90}91assertEq(udiv_truncate(5), 1);92assertEq(udiv_truncate(1), 1);93assertEq(udiv_truncate(-1), 1);94assertEq(udiv_truncate(0), 0);95assertEq(udiv_truncate(-0), 0);96assertEq(udiv_truncate(1.1), 1);97assertEq(udiv_truncate(-1.1), 1);98assertEq(udiv_truncate(Infinity), 0);99assertEq(udiv_truncate(NaN), 0);100assertEq(udiv_truncate(undefined), 0);101assertEq(udiv_truncate(null), 0);102function shifted_udiv_truncate(y) {103 var yu = y>>>1;104 return (yu / yu)|0;105}106assertEq(shifted_udiv_truncate(5), 1);107assertEq(shifted_udiv_truncate(2), 1);108assertEq(shifted_udiv_truncate(1), 0);109assertEq(shifted_udiv_truncate(-1), 1);110assertEq(shifted_udiv_truncate(0), 0);111assertEq(shifted_udiv_truncate(-0), 0);112assertEq(shifted_udiv_truncate(1.1), 0);113assertEq(shifted_udiv_truncate(-1.1), 1);114assertEq(shifted_udiv_truncate(Infinity), 0);115assertEq(shifted_udiv_truncate(NaN), 0);116assertEq(shifted_udiv_truncate(undefined), 0);117assertEq(shifted_udiv_truncate(null), 0);118function udiv(y) {119 var yu = y>>>0;120 return yu / yu;121}122assertEq(udiv(5), 1);123assertEq(udiv(1), 1);124assertEq(udiv(-1), 1);125assertEq(udiv(0), NaN);126assertEq(udiv(-0), NaN);127assertEq(udiv(1.1), 1);128assertEq(udiv(-1.1), 1);129assertEq(udiv(Infinity), NaN);130assertEq(udiv(NaN), NaN);131assertEq(udiv(undefined), NaN);132assertEq(udiv(null), NaN);133function shifted_udiv(y) {134 var yu = y>>>1;135 return yu / yu;136}137assertEq(shifted_udiv(5), 1);138assertEq(shifted_udiv(2), 1);139assertEq(shifted_udiv(1), NaN);140assertEq(shifted_udiv(-1), 1);141assertEq(shifted_udiv(0), NaN);142assertEq(shifted_udiv(-0), NaN);143assertEq(shifted_udiv(1.1), NaN);144assertEq(shifted_udiv(-1.1), 1);145assertEq(shifted_udiv(Infinity), NaN);146assertEq(shifted_udiv(NaN), NaN);147assertEq(shifted_udiv(undefined), NaN);148assertEq(shifted_udiv(null), NaN);149function smod_truncate(y) {150 return (y % y)|0;151}152assertEq(smod_truncate(5), 0);153assertEq(smod_truncate(1), 0);154assertEq(smod_truncate(-1), 0);155assertEq(smod_truncate(0), 0);156assertEq(smod_truncate(-0), 0);157assertEq(smod_truncate(1.1), 0);158assertEq(smod_truncate(-1.1), 0);159assertEq(smod_truncate(Infinity), 0);160assertEq(smod_truncate(NaN), 0);161assertEq(smod_truncate(undefined), 0);162assertEq(smod_truncate(null), 0);163function smod(y) {164 return y % y;165}166assertEq(smod(5), 0);167assertEq(smod(1), 0);168assertEq(smod(-1), -0);169assertEq(smod(0), NaN);170assertEq(smod(-0), NaN);171assertEq(smod(1.1), 0);172assertEq(smod(-1.1), -0);173assertEq(smod(Infinity), NaN);174assertEq(smod(NaN), NaN);175assertEq(smod(undefined), NaN);176assertEq(smod(null), NaN);177function umod_truncate(y) {178 var yu = y>>>0;179 return (yu % yu)|0;180}181assertEq(umod_truncate(5), 0);182assertEq(umod_truncate(1), 0);183assertEq(umod_truncate(-1), 0);184assertEq(umod_truncate(0), 0);185assertEq(umod_truncate(-0), 0);186assertEq(umod_truncate(1.1), 0);187assertEq(umod_truncate(-1.1), 0);188assertEq(umod_truncate(Infinity), 0);189assertEq(umod_truncate(NaN), 0);190assertEq(umod_truncate(undefined), 0);191assertEq(umod_truncate(null), 0);192function shifted_umod_truncate(y) {193 var yu = y>>>1;194 return (yu % yu)|0;195}196assertEq(shifted_umod_truncate(5), 0);197assertEq(shifted_umod_truncate(2), 0);198assertEq(shifted_umod_truncate(1), 0);199assertEq(shifted_umod_truncate(-1), 0);200assertEq(shifted_umod_truncate(0), 0);201assertEq(shifted_umod_truncate(-0), 0);202assertEq(shifted_umod_truncate(1.1), 0);203assertEq(shifted_umod_truncate(-1.1), 0);204assertEq(shifted_umod_truncate(Infinity), 0);205assertEq(shifted_umod_truncate(NaN), 0);206assertEq(shifted_umod_truncate(undefined), 0);207assertEq(shifted_umod_truncate(null), 0);208function umod(y) {209 var yu = y>>>0;210 return yu % yu;211}212assertEq(umod(5), 0);213assertEq(umod(1), 0);214assertEq(umod(-1), 0);215assertEq(umod(0), NaN);216assertEq(umod(-0), NaN);217assertEq(umod(1.1), 0);218assertEq(umod(-1.1), 0);219assertEq(umod(Infinity), NaN);220assertEq(umod(NaN), NaN);221assertEq(umod(undefined), NaN);...

Full Screen

Full Screen

test_formal.py

Source:test_formal.py Github

copy

Full Screen

...125 assert f.as_leading_term(x) == x126 assert f.polynomial(6) == x - x**2/2 + x**3/3 - x**4/4 + x**5/5127 k = f.ak.variables[0]128 assert f.infinite == Sum((-(-1)**(-k)*x**k)/k, (k, 1, oo))129 ft, s = f.truncate(n=None), f[:5]130 for i, t in enumerate(ft):131 if i == 5:132 break133 assert s[i] == t134 f = sin(x).fps(x)135 assert isinstance(f, FormalPowerSeries)136 assert f.truncate() == x - x**3/6 + x**5/120 + O(x**6)137 raises(NotImplementedError, lambda: fps(y*x))138 raises(ValueError, lambda: fps(x, dir=0))139def test_fps__rational():140 assert fps(1/x) == (1/x)141 assert fps((x**2 + x + 1) / x**3, dir=-1) == (x**2 + x + 1) / x**3142 f = 1 / ((x - 1)**2 * (x - 2))143 assert fps(f, x).truncate() == \144 (-Rational(1, 2) - 5*x/4 - 17*x**2/8 - 49*x**3/16 - 129*x**4/32 -145 321*x**5/64 + O(x**6))146 f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))147 assert fps(f, x).truncate() == \148 (Rational(1, 2) + 5*x/4 + 17*x**2/8 + 49*x**3/16 + 113*x**4/32 +149 241*x**5/64 + O(x**6))150 f = x / (1 - x - x**2)151 assert fps(f, x, full=True).truncate() == \152 x + x**2 + 2*x**3 + 3*x**4 + 5*x**5 + O(x**6)153 f = 1 / (x**2 + 2*x + 2)154 assert fps(f, x, full=True).truncate() == \155 Rational(1, 2) - x/2 + x**2/4 - x**4/8 + x**5/8 + O(x**6)156 f = log(1 + x)157 assert fps(f, x).truncate() == \158 x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)159 assert fps(f, x, dir=1).truncate() == fps(f, x, dir=-1).truncate()160 assert fps(f, x, 2).truncate() == \161 (log(3) - Rational(2, 3) - (x - 2)**2/18 + (x - 2)**3/81 -162 (x - 2)**4/324 + (x - 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))163 assert fps(f, x, 2, dir=-1).truncate() == \164 (log(3) - Rational(2, 3) - (-x + 2)**2/18 - (-x + 2)**3/81 -165 (-x + 2)**4/324 - (-x + 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))166 f = atan(x)167 assert fps(f, x, full=True).truncate() == x - x**3/3 + x**5/5 + O(x**6)168 assert fps(f, x, full=True, dir=1).truncate() == \169 fps(f, x, full=True, dir=-1).truncate()170 assert fps(f, x, 2, full=True).truncate() == \171 (atan(2) - Rational(2, 5) - 2*(x - 2)**2/25 + 11*(x - 2)**3/375 -172 6*(x - 2)**4/625 + 41*(x - 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))173 assert fps(f, x, 2, full=True, dir=-1).truncate() == \174 (atan(2) - Rational(2, 5) - 2*(-x + 2)**2/25 - 11*(-x + 2)**3/375 -175 6*(-x + 2)**4/625 - 41*(-x + 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))176 f = x*atan(x) - log(1 + x**2) / 2177 assert fps(f, x, full=True).truncate() == x**2/2 - x**4/12 + O(x**6)178 f = log((1 + x) / (1 - x)) / 2 - atan(x)179 assert fps(f, x, full=True).truncate(n=10) == 2*x**3/3 + 2*x**7/7 + O(x**10)180def test_fps__hyper():181 f = sin(x)182 assert fps(f, x).truncate() == x - x**3/6 + x**5/120 + O(x**6)183 f = cos(x)184 assert fps(f, x).truncate() == 1 - x**2/2 + x**4/24 + O(x**6)185 f = exp(x)186 assert fps(f, x).truncate() == \187 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)188 f = atan(x)189 assert fps(f, x).truncate() == x - x**3/3 + x**5/5 + O(x**6)190 f = exp(acos(x))191 assert fps(f, x).truncate() == \192 (exp(pi/2) - x*exp(pi/2) + x**2*exp(pi/2)/2 - x**3*exp(pi/2)/3 +193 5*x**4*exp(pi/2)/24 - x**5*exp(pi/2)/6 + O(x**6))194 f = exp(acosh(x))195 assert fps(f, x).truncate() == I + x - I*x**2/2 - I*x**4/8 + O(x**6)196 f = atan(1/x)197 assert fps(f, x).truncate() == pi/2 - x + x**3/3 - x**5/5 + O(x**6)198 f = x*atan(x) - log(1 + x**2) / 2199 assert fps(f, x, rational=False).truncate() == x**2/2 - x**4/12 + O(x**6)200 f = log(1 + x)201 assert fps(f, x, rational=False).truncate() == \202 x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)203 f = airyai(x**2)204 assert fps(f, x).truncate() == \205 (3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) -206 3**Rational(2, 3)*x**2/(3*gamma(Rational(1, 3))) + O(x**6))207 f = exp(x)*sin(x)208 assert fps(f, x).truncate() == x + x**2 + x**3/3 - x**5/30 + O(x**6)209 f = exp(x)*sin(x)/x210 assert fps(f, x).truncate() == 1 + x + x**2/3 - x**4/30 - x**5/90 + O(x**6)211 f = sin(x) * cos(x)212 assert fps(f, x).truncate() == x - 2*x**3/3 + 2*x**5/15 + O(x**6)213def test_fps_shift():214 f = x**-5*sin(x)215 assert fps(f, x).truncate() == \216 1/x**4 - 1/(6*x**2) + S.One/120 - x**2/5040 + x**4/362880 + O(x**6)217 f = x**2*atan(x)218 assert fps(f, x, rational=False).truncate() == \219 x**3 - x**5/3 + O(x**6)220 f = cos(sqrt(x))*x221 assert fps(f, x).truncate() == \222 x - x**2/2 + x**3/24 - x**4/720 + x**5/40320 + O(x**6)223 f = x**2*cos(sqrt(x))224 assert fps(f, x).truncate() == \225 x**2 - x**3/2 + x**4/24 - x**5/720 + O(x**6)226def test_fps__Add_expr():227 f = x*atan(x) - log(1 + x**2) / 2228 assert fps(f, x).truncate() == x**2/2 - x**4/12 + O(x**6)229 f = sin(x) + cos(x) - exp(x) + log(1 + x)230 assert fps(f, x).truncate() == x - 3*x**2/2 - x**4/4 + x**5/5 + O(x**6)231 f = 1/x + sin(x)232 assert fps(f, x).truncate() == 1/x + x - x**3/6 + x**5/120 + O(x**6)233 f = sin(x) - cos(x) + 1/(x - 1)234 assert fps(f, x).truncate() == \235 -2 - x**2/2 - 7*x**3/6 - 25*x**4/24 - 119*x**5/120 + O(x**6)236def test_fps__asymptotic():237 f = exp(x)238 assert fps(f, x, oo) == f239 assert fps(f, x, -oo).truncate() == O(1/x**6, (x, oo))240 f = erf(x)241 assert fps(f, x, oo).truncate() == 1 + O(1/x**6, (x, oo))242 assert fps(f, x, -oo).truncate() == -1 + O(1/x**6, (x, oo))243 f = atan(x)244 assert fps(f, x, oo, full=True).truncate() == \245 -1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(1/x**6, (x, oo))246 assert fps(f, x, -oo, full=True).truncate() == \247 -1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(1/x**6, (x, oo))248 f = log(1 + x)249 assert fps(f, x, oo) != \250 (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x - log(1/x) +251 O(1/x**6, (x, oo)))252 assert fps(f, x, -oo) != \253 (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x + I*pi -254 log(-1/x) + O(1/x**6, (x, oo)))255def test_fps__fractional():256 f = sin(sqrt(x)) / x257 assert fps(f, x).truncate() == \258 (1/sqrt(x) - sqrt(x)/6 + x**Rational(3, 2)/120 -259 x**Rational(5, 2)/5040 + x**Rational(7, 2)/362880 -260 x**Rational(9, 2)/39916800 + x**Rational(11, 2)/6227020800 + O(x**6))261 f = sin(sqrt(x)) * x262 assert fps(f, x).truncate() == \263 (x**Rational(3, 2) - x**Rational(5, 2)/6 + x**Rational(7, 2)/120 -264 x**Rational(9, 2)/5040 + x**Rational(11, 2)/362880 + O(x**6))265 f = atan(sqrt(x)) / x**2266 assert fps(f, x).truncate() == \267 (x**Rational(-3, 2) - x**Rational(-1, 2)/3 + x**Rational(1, 2)/5 -268 x**Rational(3, 2)/7 + x**Rational(5, 2)/9 - x**Rational(7, 2)/11 +269 x**Rational(9, 2)/13 - x**Rational(11, 2)/15 + O(x**6))270 f = exp(sqrt(x))271 assert fps(f, x).truncate().expand() == \272 (1 + x/2 + x**2/24 + x**3/720 + x**4/40320 + x**5/3628800 + sqrt(x) +273 x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + x**Rational(7, 2)/5040 +274 x**Rational(9, 2)/362880 + x**Rational(11, 2)/39916800 + O(x**6))275 f = exp(sqrt(x))*x276 assert fps(f, x).truncate().expand() == \277 (x + x**2/2 + x**3/24 + x**4/720 + x**5/40320 + x**Rational(3, 2) +278 x**Rational(5, 2)/6 + x**Rational(7, 2)/120 + x**Rational(9, 2)/5040 +279 x**Rational(11, 2)/362880 + O(x**6))280def test_fps__logarithmic_singularity():281 f = log(1 + 1/x)282 assert fps(f, x) != \283 -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)284 assert fps(f, x, rational=False) != \285 -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)286@XFAIL287def test_fps__logarithmic_singularity_fail():288 f = asech(x) # Algorithms for computing limits probably needs improvemnts289 assert fps(f, x) == log(2) - log(x) - x**2/4 - 3*x**4/64 + O(x**6)290@XFAIL291def test_fps__symbolic():292 f = x**n*sin(x**2)293 assert fps(f, x).truncate(8) == x**2*x**n - x**6*x**n/6 + O(x**(n + 8), x)294 f = x**(n - 2)*cos(x)295 assert fps(f, x).truncate() == \296 (x**n*(-S(1)/2 + x**(-2)) + x**2*x**n/24 - x**4*x**n/720 +297 O(x**(n + 6), x))298 f = x**n*log(1 + x)299 fp = fps(f, x)300 k = fp.ak.variables[0]301 assert fp.infinite == \302 Sum((-(-1)**(-k)*x**k*x**n)/k, (k, 1, oo))303 f = x**(n - 2)*sin(x) + x**n*exp(x)304 assert fps(f, x).truncate() == \305 (x**n*(1 + 1/x) + 5*x*x**n/6 + x**2*x**n/2 + 7*x**3*x**n/40 +306 x**4*x**n/24 + 41*x**5*x**n/5040 + O(x**(n + 6), x))307 f = (x - 2)**n*log(1 + x)308 assert fps(f, x, 2).truncate() == \309 ((x - 2)**n*log(3) - (x - 2)**2*(x - 2)**n/18 +310 (x - 2)**3*(x - 2)**n/81 - (x - 2)**4*(x - 2)**n/324 +311 (x - 2)**5*(x - 2)**n/1215 + (x/3 - S(2)/3)*(x - 2)**n +312 O((x - 2)**(n + 6), (x, 2)))313 f = x**n*atan(x)314 assert fps(f, x, oo).truncate() == \315 (-x**n/(5*x**5) + x**n/(3*x**3) + x**n*(pi/2 - 1/x) +316 O(x**(n - 6), (x, oo)))317@slow318def test_fps__slow():319 f = x*exp(x)*sin(2*x) # TODO: rsolve needs improvement320 assert fps(f, x).truncate() == 2*x**2 + 2*x**3 - x**4/3 - x**5 + O(x**6)321def test_fps__operations():322 f1, f2 = fps(sin(x)), fps(cos(x))323 fsum = f1 + f2324 assert fsum.function == sin(x) + cos(x)325 assert fsum.truncate() == \326 1 + x - x**2/2 - x**3/6 + x**4/24 + x**5/120 + O(x**6)327 fsum = f1 + 1328 assert fsum.function == sin(x) + 1329 assert fsum.truncate() == 1 + x - x**3/6 + x**5/120 + O(x**6)330 fsum = 1 + f2331 assert fsum.function == cos(x) + 1332 assert fsum.truncate() == 2 - x**2/2 + x**4/24 + O(x**6)333 assert (f1 + x) == Add(f1, x)334 assert -f2.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)335 assert (f1 - f1) == S.Zero336 fsub = f1 - f2337 assert fsub.function == sin(x) - cos(x)338 assert fsub.truncate() == \339 -1 + x + x**2/2 - x**3/6 - x**4/24 + x**5/120 + O(x**6)340 fsub = f1 - 1341 assert fsub.function == sin(x) - 1342 assert fsub.truncate() == -1 + x - x**3/6 + x**5/120 + O(x**6)343 fsub = 1 - f2344 assert fsub.function == -cos(x) + 1345 assert fsub.truncate() == x**2/2 - x**4/24 + O(x**6)346 raises(ValueError, lambda: f1 + fps(exp(x), dir=-1))347 raises(ValueError, lambda: f1 + fps(exp(x), x0=1))348 fm = f1 * 3349 assert fm.function == 3*sin(x)350 assert fm.truncate() == 3*x - x**3/2 + x**5/40 + O(x**6)351 fm = 3 * f2352 assert fm.function == 3*cos(x)353 assert fm.truncate() == 3 - 3*x**2/2 + x**4/8 + O(x**6)354 assert (f1 * f2) == Mul(f1, f2)355 assert (f1 * x) == Mul(f1, x)356 fd = f1.diff()357 assert fd.function == cos(x)358 assert fd.truncate() == 1 - x**2/2 + x**4/24 + O(x**6)359 fd = f2.diff()360 assert fd.function == -sin(x)361 assert fd.truncate() == -x + x**3/6 - x**5/120 + O(x**6)362 fd = f2.diff().diff()363 assert fd.function == -cos(x)364 assert fd.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)365 f3 = fps(exp(sqrt(x)))366 fd = f3.diff()367 assert fd.truncate().expand() == \368 (1/(2*sqrt(x)) + S(1)/2 + x/12 + x**2/240 + x**3/10080 + x**4/725760 +369 x**5/79833600 + sqrt(x)/4 + x**(S(3)/2)/48 + x**(S(5)/2)/1440 +370 x**(S(7)/2)/80640 + x**(S(9)/2)/7257600 + x**(S(11)/2)/958003200 +371 O(x**6))372 assert f1.integrate((x, 0, 1)) == -cos(1) + 1373 fi = f1.integrate(x)374 assert fi.function == -cos(x)375 assert fi.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)376 fi = f2.integrate()377 assert fi.function == sin(x)...

Full Screen

Full Screen

text.py

Source:text.py Github

copy

Full Screen

1import html.entities2import re3import unicodedata4from gzip import GzipFile5from io import BytesIO6from django.utils.functional import (7 SimpleLazyObject, keep_lazy, keep_lazy_text, lazy,8)9from django.utils.safestring import SafeText, mark_safe10from django.utils.translation import gettext as _, gettext_lazy, pgettext11@keep_lazy_text12def capfirst(x):13 """Capitalize the first letter of a string."""14 return x and str(x)[0].upper() + str(x)[1:]15# Set up regular expressions16re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S)17re_chars = re.compile(r'<.*?>|(.)', re.S)18re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)19re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines20re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')21@keep_lazy_text22def wrap(text, width):23 """24 A word-wrap function that preserves existing line breaks. Expects that25 existing line breaks are posix newlines.26 Preserve all white space except added line breaks consume the space on27 which they break the line.28 Don't wrap long words, thus the output text may have lines longer than29 ``width``.30 """31 def _generator():32 for line in text.splitlines(True): # True keeps trailing linebreaks33 max_width = min((line.endswith('\n') and width + 1 or width), width)34 while len(line) > max_width:35 space = line[:max_width + 1].rfind(' ') + 136 if space == 0:37 space = line.find(' ') + 138 if space == 0:39 yield line40 line = ''41 break42 yield '%s\n' % line[:space - 1]43 line = line[space:]44 max_width = min((line.endswith('\n') and width + 1 or width), width)45 if line:46 yield line47 return ''.join(_generator())48class Truncator(SimpleLazyObject):49 """50 An object used to truncate text, either by characters or words.51 """52 def __init__(self, text):53 super().__init__(lambda: str(text))54 def add_truncation_text(self, text, truncate=None):55 if truncate is None:56 truncate = pgettext(57 'String to return when truncating text',58 '%(truncated_text)s...')59 if '%(truncated_text)s' in truncate:60 return truncate % {'truncated_text': text}61 # The truncation text didn't contain the %(truncated_text)s string62 # replacement argument so just append it to the text.63 if text.endswith(truncate):64 # But don't append the truncation text if the current text already65 # ends in this.66 return text67 return '%s%s' % (text, truncate)68 def chars(self, num, truncate=None, html=False):69 """70 Return the text truncated to be no longer than the specified number71 of characters.72 `truncate` specifies what should be used to notify that the string has73 been truncated, defaulting to a translatable string of an ellipsis74 (...).75 """76 self._setup()77 length = int(num)78 text = unicodedata.normalize('NFC', self._wrapped)79 # Calculate the length to truncate to (max length - end_text length)80 truncate_len = length81 for char in self.add_truncation_text('', truncate):82 if not unicodedata.combining(char):83 truncate_len -= 184 if truncate_len == 0:85 break86 if html:87 return self._truncate_html(length, truncate, text, truncate_len, False)88 return self._text_chars(length, truncate, text, truncate_len)89 def _text_chars(self, length, truncate, text, truncate_len):90 """Truncate a string after a certain number of chars."""91 s_len = 092 end_index = None93 for i, char in enumerate(text):94 if unicodedata.combining(char):95 # Don't consider combining characters96 # as adding to the string length97 continue98 s_len += 199 if end_index is None and s_len > truncate_len:100 end_index = i101 if s_len > length:102 # Return the truncated string103 return self.add_truncation_text(text[:end_index or 0],104 truncate)105 # Return the original string since no truncation was necessary106 return text107 def words(self, num, truncate=None, html=False):108 """109 Truncate a string after a certain number of words. `truncate` specifies110 what should be used to notify that the string has been truncated,111 defaulting to ellipsis (...).112 """113 self._setup()114 length = int(num)115 if html:116 return self._truncate_html(length, truncate, self._wrapped, length, True)117 return self._text_words(length, truncate)118 def _text_words(self, length, truncate):119 """120 Truncate a string after a certain number of words.121 Strip newlines in the string.122 """123 words = self._wrapped.split()124 if len(words) > length:125 words = words[:length]126 return self.add_truncation_text(' '.join(words), truncate)127 return ' '.join(words)128 def _truncate_html(self, length, truncate, text, truncate_len, words):129 """130 Truncate HTML to a certain number of chars (not counting tags and131 comments), or, if words is True, then to a certain number of words.132 Close opened tags if they were correctly closed in the given HTML.133 Preserve newlines in the HTML.134 """135 if words and length <= 0:136 return ''137 html4_singlets = (138 'br', 'col', 'link', 'base', 'img',139 'param', 'area', 'hr', 'input'140 )141 # Count non-HTML chars/words and keep note of open tags142 pos = 0143 end_text_pos = 0144 current_len = 0145 open_tags = []146 regex = re_words if words else re_chars147 while current_len <= length:148 m = regex.search(text, pos)149 if not m:150 # Checked through whole string151 break152 pos = m.end(0)153 if m.group(1):154 # It's an actual non-HTML word or char155 current_len += 1156 if current_len == truncate_len:157 end_text_pos = pos158 continue159 # Check for tag160 tag = re_tag.match(m.group(0))161 if not tag or current_len >= truncate_len:162 # Don't worry about non tags or tags after our truncate point163 continue164 closing_tag, tagname, self_closing = tag.groups()165 # Element names are always case-insensitive166 tagname = tagname.lower()167 if self_closing or tagname in html4_singlets:168 pass169 elif closing_tag:170 # Check for match in open tags list171 try:172 i = open_tags.index(tagname)173 except ValueError:174 pass175 else:176 # SGML: An end tag closes, back to the matching start tag,177 # all unclosed intervening start tags with omitted end tags178 open_tags = open_tags[i + 1:]179 else:180 # Add it to the start of the open tags list181 open_tags.insert(0, tagname)182 if current_len <= length:183 return text184 out = text[:end_text_pos]185 truncate_text = self.add_truncation_text('', truncate)186 if truncate_text:187 out += truncate_text188 # Close any tags still open189 for tag in open_tags:190 out += '</%s>' % tag191 # Return string192 return out193@keep_lazy_text194def get_valid_filename(s):195 """196 Return the given string converted to a string that can be used for a clean197 filename. Remove leading and trailing spaces; convert other spaces to198 underscores; and remove anything that is not an alphanumeric, dash,199 underscore, or dot.200 >>> get_valid_filename("john's portrait in 2004.jpg")201 'johns_portrait_in_2004.jpg'202 """203 s = str(s).strip().replace(' ', '_')204 return re.sub(r'(?u)[^-\w.]', '', s)205@keep_lazy_text206def get_text_list(list_, last_word=gettext_lazy('or')):207 """208 >>> get_text_list(['a', 'b', 'c', 'd'])209 'a, b, c or d'210 >>> get_text_list(['a', 'b', 'c'], 'and')211 'a, b and c'212 >>> get_text_list(['a', 'b'], 'and')213 'a and b'214 >>> get_text_list(['a'])215 'a'216 >>> get_text_list([])217 ''218 """219 if len(list_) == 0:220 return ''221 if len(list_) == 1:222 return str(list_[0])223 return '%s %s %s' % (224 # Translators: This string is used as a separator between list elements225 _(', ').join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1])226 )227@keep_lazy_text228def normalize_newlines(text):229 """Normalize CRLF and CR newlines to just LF."""230 return re_newlines.sub('\n', str(text))231@keep_lazy_text232def phone2numeric(phone):233 """Convert a phone number with letters into its numeric equivalent."""234 char2number = {235 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4',236 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6',237 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8',238 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9',239 }240 return ''.join(char2number.get(c, c) for c in phone.lower())241# From http://www.xhaus.com/alan/python/httpcomp.html#gzip242# Used with permission.243def compress_string(s):244 zbuf = BytesIO()245 with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0) as zfile:246 zfile.write(s)247 return zbuf.getvalue()248class StreamingBuffer:249 def __init__(self):250 self.vals = []251 def write(self, val):252 self.vals.append(val)253 def read(self):254 if not self.vals:255 return b''256 ret = b''.join(self.vals)257 self.vals = []258 return ret259 def flush(self):260 return261 def close(self):262 return263# Like compress_string, but for iterators of strings.264def compress_sequence(sequence):265 buf = StreamingBuffer()266 with GzipFile(mode='wb', compresslevel=6, fileobj=buf, mtime=0) as zfile:267 # Output headers...268 yield buf.read()269 for item in sequence:270 zfile.write(item)271 data = buf.read()272 if data:273 yield data274 yield buf.read()275# Expression to match some_token and some_token="with spaces" (and similarly276# for single-quoted strings).277smart_split_re = re.compile(r"""278 ((?:279 [^\s'"]*280 (?:281 (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')282 [^\s'"]*283 )+284 ) | \S+)285""", re.VERBOSE)286def smart_split(text):287 r"""288 Generator that splits a string by spaces, leaving quoted phrases together.289 Supports both single and double quotes, and supports escaping quotes with290 backslashes. In the output, strings will keep their initial and trailing291 quote marks and escaped quotes will remain escaped (the results can then292 be further processed with unescape_string_literal()).293 >>> list(smart_split(r'This is "a person\'s" test.'))294 ['This', 'is', '"a person\\\'s"', 'test.']295 >>> list(smart_split(r"Another 'person\'s' test."))296 ['Another', "'person\\'s'", 'test.']297 >>> list(smart_split(r'A "\"funky\" style" test.'))298 ['A', '"\\"funky\\" style"', 'test.']299 """300 for bit in smart_split_re.finditer(str(text)):301 yield bit.group(0)302def _replace_entity(match):303 text = match.group(1)304 if text[0] == '#':305 text = text[1:]306 try:307 if text[0] in 'xX':308 c = int(text[1:], 16)309 else:310 c = int(text)311 return chr(c)312 except ValueError:313 return match.group(0)314 else:315 try:316 return chr(html.entities.name2codepoint[text])317 except (ValueError, KeyError):318 return match.group(0)319_entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")320@keep_lazy_text321def unescape_entities(text):322 return _entity_re.sub(_replace_entity, str(text))323@keep_lazy_text324def unescape_string_literal(s):325 r"""326 Convert quoted string literals to unquoted strings with escaped quotes and327 backslashes unquoted::328 >>> unescape_string_literal('"abc"')329 'abc'330 >>> unescape_string_literal("'abc'")331 'abc'332 >>> unescape_string_literal('"a \"bc\""')333 'a "bc"'334 >>> unescape_string_literal("'\'ab\' c'")335 "'ab' c"336 """337 if s[0] not in "\"'" or s[-1] != s[0]:338 raise ValueError("Not a string literal: %r" % s)339 quote = s[0]340 return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')341@keep_lazy(str, SafeText)342def slugify(value, allow_unicode=False):343 """344 Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.345 Remove characters that aren't alphanumerics, underscores, or hyphens.346 Convert to lowercase. Also strip leading and trailing whitespace.347 """348 value = str(value)349 if allow_unicode:350 value = unicodedata.normalize('NFKC', value)351 else:352 value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')353 value = re.sub(r'[^\w\s-]', '', value).strip().lower()354 return mark_safe(re.sub(r'[-\s]+', '-', value))355def camel_case_to_spaces(value):356 """357 Split CamelCase and convert to lower case. Strip surrounding whitespace.358 """359 return re_camel_case.sub(r' \1', value).strip().lower()360def _format_lazy(format_string, *args, **kwargs):361 """362 Apply str.format() on 'format_string' where format_string, args,363 and/or kwargs might be lazy.364 """365 return format_string.format(*args, **kwargs)...

Full Screen

Full Screen

truncate.js

Source:truncate.js Github

copy

Full Screen

1// Truncate text component module2'use strict';3var $ = require('jquery');4var debounce = require('../../services/debounce/debounce');5module.exports = function Truncate() {6 var truncate = {};7 /**8 * @example9 * <div id="truncate" style="overflow: hidden; line-height: 20px; max-height: 60px;">10 * Lorem ipsum ...11 * </div>12 *13 * import Truncate from '@sulu/web/packages/components/truncate';14 * var component = new Truncate();15 * component.initialize(document.getElementById('truncate'), {});16 *17 * @param {HTMLElement} el18 * @param {object} options19 */20 truncate.initialize = function initialize(el, options) {21 truncate.$el = $(el);22 // Set default options if no custom options are defined23 truncate.separator = options.separator || ' ...';24 truncate.debounceDelay = options.debounceDelay || 250;25 truncate.text = truncate.$el.text().trim();26 truncate.$inner = $('<span></span>').text(truncate.text).css('display', 'block');27 truncate.$el.html(truncate.$inner).css('display', 'block');28 truncate.calculateRegex();29 truncate.calculateText();30 $(window).on('load resize', debounce(truncate.calculateText, truncate.debounceDelay));31 };32 /**33 * Calculate regex based on the separator.34 */35 truncate.calculateRegex = function calculateRegex() {36 var separatorRegex = truncate.separator.split('').map(c => '\\' + c).join('');37 truncate.regex = new RegExp('\\W*\\s?(?:\\S*|\\S*' + separatorRegex + ')$');38 };39 /**40 * Calculate output text based on the element's height.41 */42 truncate.calculateText = function calculateText() {43 var height;44 truncate.$inner.text(truncate.text);45 height = truncate.$el.height();46 while (truncate.$inner.outerHeight() > height) {47 truncate.$inner.text(function(index, text) {48 if (text === truncate.separator) {49 return '';50 }51 return text.replace(truncate.regex, truncate.separator);52 });53 }54 };55 return {56 initialize: truncate.initialize,57 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('chai').assert;2var truncate = require('truncate');3describe('truncate', function() {4 it('should truncate a string', function() {5 assert.equal(truncate('hello world', 5), 'hello');6 });7});8module.exports = function(str, len) {9 return str.slice(0, len);10};11var expect = require('chai').expect;12var truncate = require('truncate');13describe('truncate', function() {14 it('should truncate a string', function() {15 expect(truncate('hello world', 5)).to.equal('hello');16 });17});18module.exports = function(str, len) {19 return str.slice(0, len);20};21var should = require('chai').should();22var truncate = require('truncate');23describe('truncate', function() {24 it('should truncate a string', function() {25 truncate('hello world', 5).should.equal('hello');26 });27});28module.exports = function(str, len) {29 return str.slice(0, len);30};31var assert = require('chai').assert;32var truncate = require('truncate');33describe('truncate', function() {34 it('should truncate a string', function() {35 assert.equal(truncate('hello world', 5), 'hello');36 });37});38module.exports = function(str, len) {39 return str.slice(0, len);40};41var expect = require('chai').expect;42var truncate = require('truncate');43describe('truncate', function() {44 it('should truncate a string', function() {45 expect(truncate('hello world', 5)).to.equal('hello');46 });47});48module.exports = function(str, len) {49 return str.slice(0, len);50};51var should = require('chai').should();52var truncate = require('truncate');53describe('truncate', function() {54 it('should truncate a string', function() {55 truncate('

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('chai').assert;2var truncate = require('truncate');3assert.equal(truncate('Hello World', 5), 'Hello');4assert.equal(truncate('Hello World', 5, '...'), 'Hello...');5var assert = require('chai').assert;6var truncate = require('truncate');7assert.equal(truncate('Hello World', 5), 'Hello');8assert.equal(truncate('Hello World', 5, '...'), 'Hello...');9var assert = require('chai').assert;10var truncate = require('truncate');11assert.equal(truncate('Hello World', 5), 'Hello');12assert.equal(truncate('Hello World', 5, '...'), 'Hello...');13var assert = require('chai').assert;14var truncate = require('truncate');15assert.equal(truncate('Hello World', 5), 'Hello');16assert.equal(truncate('Hello World', 5, '...'), 'Hello...');17var assert = require('chai').assert;18var truncate = require('truncate');19assert.equal(truncate('Hello World', 5), 'Hello');20assert.equal(truncate('Hello World', 5, '...'), 'Hello...');21var assert = require('chai').assert;22var truncate = require('truncate');23assert.equal(truncate('Hello World', 5), 'Hello');24assert.equal(truncate('Hello World', 5, '...'), 'Hello...');25var assert = require('chai').assert;26var truncate = require('truncate');27assert.equal(truncate('Hello World', 5), 'Hello');28assert.equal(truncate('Hello World', 5, '...'), 'Hello...');29var assert = require('chai').assert;30var truncate = require('truncate');31assert.equal(truncate('Hello World', 5), 'Hello');32assert.equal(truncate('Hello World', 5, '...'), 'Hello...');

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('chai').assert;2const truncate = require('../truncate');3describe('truncate', function() {4 it('should truncate a string', function() {5 assert.equal(truncate('truncated string', 10), 'truncated...');6 });7});8function truncate(str, length) {9 return str.length > length ? str.slice(0, length) + '...' : str;10}11module.exports = truncate;12 1 passing (10ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1const truncate = require('truncate-chain');2const { chain } = require('lodash');3const result = chain([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])4 .truncate(3)5 .value();6### truncate(number)7- [truncate](

Full Screen

Using AI Code Generation

copy

Full Screen

1var chai = require('chai');2var expect = chai.expect;3var assert = chai.assert;4var should = chai.should();5var truncate = require('../truncate');6describe('Test truncate method', function() {7 it('Should truncate a string to a given length', function() {8 truncate('Hello World!', 5).should.equal('Hello...');9 });10 it('Should return a string if length is less than or equal to 3', function() {11 truncate('Hello World!', 3).should.equal('Hel');12 });13 it('Should return a string if length is less than or equal to 3', function() {14 truncate('Hello World!', 2).should.equal('He');15 });16 it('Should return a string if length is less than or equal to 3', function() {17 truncate('Hello World!', 1).should.equal('H');18 });19 it('Should return a string if length is less than or equal to 3', function() {20 truncate('Hello World!', 0).should.equal('');21 });22 it('Should return a string if length is less than or equal to 3', function() {23 truncate('Hello World!', -1).should.equal('');24 });25 it('Should return a string if length is less than or equal to 3', function() {26 truncate('Hello World!', -2).should.equal('');27 });28 it('Should return a string if length is less than or equal to 3', function() {29 truncate('Hello World!', -3).should.equal('');30 });31 it('Should return a string if length is less than or equal to 3', function() {32 truncate('Hello World!', -4).should.equal('');33 });34});35module.exports = function(str, length) {36 if (length <= 3) return str.slice(0, length);37 if (str.length > length)38 return str.slice(0, length - 3) + '...';39 return str;40};

Full Screen

Using AI Code Generation

copy

Full Screen

1var chain = require("./chain");2var truncate = chain.truncate;3var myChain = new chain.Chain();4myChain.addBlock("first block");5myChain.addBlock("second block");6myChain.addBlock("third block");7myChain.addBlock("fourth block");8myChain.addBlock("fifth block");9myChain.addBlock("sixth block");10myChain.addBlock("seventh block");11myChain.addBlock("eighth block");12myChain.addBlock("ninth block");13myChain.addBlock("tenth block");14myChain.addBlock("eleventh block");15myChain.addBlock("twelveth block");16myChain.addBlock("thirteenth block");17myChain.addBlock("fourteenth block");18myChain.addBlock("fifteenth block");19myChain.addBlock("sixteenth block");20myChain.addBlock("seventeenth block");21myChain.addBlock("eighteenth block");22myChain.addBlock("nineteenth block");23myChain.addBlock("twentieth block");24myChain.addBlock("twenty-first block");25myChain.addBlock("twenty-second block");26myChain.addBlock("twenty-third block");27myChain.addBlock("twenty-fourth block");28myChain.addBlock("twenty-fifth block");29myChain.addBlock("twenty-sixth block");30myChain.addBlock("twenty-seventh block");31myChain.addBlock("twenty-eighth block");32myChain.addBlock("twenty-ninth block");33myChain.addBlock("thirtieth block");34myChain.addBlock("thirty-first block");35myChain.addBlock("thirty-second block");36myChain.addBlock("thirty-third block");37myChain.addBlock("thirty-fourth block");38myChain.addBlock("thirty-fifth block");39myChain.addBlock("thirty-sixth block");40myChain.addBlock("thirty-seventh block");41myChain.addBlock("thirty-eighth block");42myChain.addBlock("thirty-ninth block");43myChain.addBlock("fortieth block");44myChain.addBlock("forty-first block");45myChain.addBlock("forty-second block");46myChain.addBlock("forty-third block");47myChain.addBlock("forty-fourth block");48myChain.addBlock("forty-fifth block");49myChain.addBlock("forty-sixth block");50myChain.addBlock("forty-seventh block");51myChain.addBlock("forty-eighth block");

Full Screen

Using AI Code Generation

copy

Full Screen

1var expect = require('chai').expect;2var truncate = require('truncate');3var testString = "This is a test string";4describe('truncate', function() {5 it('should truncate a string to a specified length', function() {6 expect(truncate(testString, 8)).to.equal('This is...');7 });8});9* **Chen Chen** - *Initial work* - [Chenchen](

Full Screen

Using AI Code Generation

copy

Full Screen

1var chai = require('chai');2var truncate = require('truncate');3var str = truncate('This is a long sentence.', 10, '...');4var str = truncate('This is a long sentence.', 10);5var str = truncate('This is a long sentence.', 10, '...');6var str = truncate('This is a long sentence.', 10, '...');7var str = truncate('This is a long sentence.', 10, '...');8var str = truncate('This is a long sentence.', 10, '...');9var str = truncate('This is a long sentence.', 10, '...');10var str = truncate('This is a long sentence.', 10, '...');11var str = truncate('This is a long sentence.', 10, '...');12var str = truncate('This is a long sentence.', 10, '...');13var str = truncate('This is a long sentence.', 10, '...');14var str = truncate('This is a long sentence.', 10, '...');

Full Screen

Using AI Code Generation

copy

Full Screen

1var truncate = require('truncate-chain');2var chain = require('chain-js');3var text = "Hello World";4var result = chain(text).truncate(5).value();5### `trim()`6var trim = require('trim-chain');7var chain = require('chain-js');8var text = " Hello World ";9var result = chain(text).trim().value();10### `trimEnd()`11var trimEnd = require('trim-end-chain');12var chain = require('chain-js');13var text = "Hello World ";14var result = chain(text).trimEnd().value();15### `trimStart()`16var trimStart = require('trim-start-chain');17var chain = require('chain-js');18var text = " Hello World";19var result = chain(text).trimStart().value();20### `unescape()`21var unescape = require('unescape-chain');22var chain = require('chain-js');23var text = "Hello &lt;b&gt;World&lt;/b&gt;";24var result = chain(text).unescape().value();25### `upperCase()`26var upperCase = require('upper-case-chain');27var chain = require('chain-js');28var text = "Hello World";29var result = chain(text).upperCase().value();30### `upperFirst()`

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run chai automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful