1

2# -*- coding: utf-8 -*-

3

4 u'''Floating point and other formatting utilities.

5'''

6

7 from pygeodesy.basics import isint, islistuple, isscalar, isstr, itemsorted, \

8 _zip, _0_0

9# from pygeodesy.constants import _0_0

10 from pygeodesy.errors import _or, _IsnotError, _TypeError, _ValueError, \

11 _xkwds_get, _xkwds_item2

12# from pygeodesy.internals import _dunder_nameof # from .lazily

13 from pygeodesy.interns import NN, _0_, _0to9_, MISSING, _BAR_, _COMMASPACE_, \

14 _DOT_, _E_, _ELLIPSIS_, _EQUAL_, _H_, _LR_PAIRS, \

15 _N_, _name_, _not_scalar_, _PERCENT_, _SPACE_, \

16 _STAR_, _UNDER_

17 from pygeodesy.interns import _convergence_, _distant_, _e_, _eps_, _exceeds_, \

18 _EQUALSPACED_, _f_, _F_, _g_, _limit_, _no_, \

19 _tolerance_ # PYCHOK used!

20 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _dunder_nameof

21

22 from math import fabs, log10 as _log10

23

24__all__ = _ALL_LAZY.streprs

25__version__ = '24.06.15'

26

27_at_ = 'at' # PYCHOK used!

28_EN_PREC = 6 # max MGRS/OSGR precision, 1 micrometer

29_EN_WIDE = 5 # number of MGRS/OSGR units, log10(_100km)

30_OKd_ = '._-' # acceptable name characters

31_PAREN_g = '(%g)' # PYCHOK used!

32_RESIDUAL_ = 'RESIDUAL' # PYCHOK used!

33_threshold_ = 'threshold' # PYCHOK used!

34

35

36 class _Fmt(str):

37 '''(INTERNAL) Callable formatting.

38 '''

39 name = NN

40

41 def __call__(self, *name_value_, **name_value):

42 '''Format a C{name=value} pair or C{name, value} pair or

43 just a single C{value}.

44 '''

45 for n, v in name_value.items():

46 break

47 else:

48 n, v = name_value_[:2] if len(name_value_) > 1 else \

49 (NN, (name_value_ or MISSING))

50 t = str.__mod__(self, v)

51 return NN(n, t) if n else t

52

53# def __mod__(self, arg, **unused):

54# '''Regular C{%} operator.

55# '''

56# return str.__mod__(self, arg)

57

58

59 class Fstr(str):

60 '''(INTERNAL) C{float} format.

61 '''

62 name = NN

63

64 def __call__(self, flt, prec=None, ints=False):

65 '''Format the B{C{flt}} like function L{fstr}.

66 '''

67 # see also function C{fstr} if isscalar case below

68 t = str.__mod__(_pct(self), flt) if prec is None else next(

69 _streprs(prec, (flt,), self, ints, True, None))

70 return t

71

72 def __mod__(self, arg, **unused):

73 '''Regular C{%} operator.

74

75 @arg arg: A C{scalar} value to be formatted (either

76 the C{scalar}, or a 1-tuple C{(scalar,)},

77 or 2-tuple C{(prec, scalar)}.

78

79 @raise TypeError: Non-scalar B{C{arg}} value.

80

81 @raise ValueError: Invalid B{C{arg}}.

82 '''

83 def _error(arg):

84 n = _DOT_(Fstr.__name__, self.name or self)

85 return _SPACE_(n, _PERCENT_, repr(arg))

86

87 prec = 6 # default std %f and %F

88 if islistuple(arg):

89 n = len(arg)

90 if n == 1:

91 arg = arg[0]

92 elif n == 2:

93 prec, arg = arg

94 else:

95 raise _ValueError(_error(arg))

96

97 if not isscalar(arg):

98 raise _TypeError(_error(arg))

99 return self(arg, prec=prec) # Fstr.__call__(self, arg, prec=prec)

100

101

102 class _Sub(str):

103 '''(INTERNAL) Class list formatter.

104 '''

105 # see .ellipsoidalNvector.LatLon.deltaTo

106 def __call__(self, *Classes):

107 t = _or(*(C.__name__ for C in Classes))

108 return str.__mod__(self, t or MISSING)

109

110

111 class Fmt(object):

112 '''Formatting options.

113 '''

114 ANGLE = _Fmt('<%s>')

115 COLON = _Fmt(':%s')

116# COLONSPACE = _Fmt(': %s') # == _COLONSPACE_(n, v)

117# COMMASPACE = _Fmt(', %s') # == _COMMASPACE_(n, v)

118 convergence = _Fmt(_convergence_(_PAREN_g))

119 CURLY = _Fmt('{%s}') # BRACES

120 distant = _Fmt(_distant_('(%.3g)'))

121 DOT = _Fmt('.%s') # == NN(_DOT_, n)

122 e = Fstr(_e_)

123 E = Fstr(_E_)

124 EQUAL = _Fmt(_EQUAL_(NN, '%s'))

125 EQUALg = _Fmt(_EQUAL_(NN, '%g'))

126 EQUALSPACED = _Fmt(_EQUALSPACED_(NN, '%s'))

127 exceeds_eps = _Fmt(_exceeds_(_eps_, _PAREN_g))

128 exceeds_limit = _Fmt(_exceeds_(_limit_, _PAREN_g))

129 exceeds_R = _Fmt(_exceeds_(_RESIDUAL_, _PAREN_g))

130 f = Fstr(_f_)

131 F = Fstr(_F_)

132 g = Fstr(_g_)

133 G = Fstr('G')

134 h = Fstr('%+.*f') # height, .streprs.hstr

135 limit = _Fmt(' %s limit') # .units

136 LOPEN = _Fmt('(%s]') # left-open range (L, R]

137 PAREN = _Fmt('(%s)')

138 PAREN_g = _Fmt(_PAREN_g)

139 PARENSPACED = _Fmt(' (%s)')

140 QUOTE2 = _Fmt('"%s"')

141 ROPEN = _Fmt('[%s)') # right-open range [L, R)

142# SPACE = _Fmt(' %s') # == _SPACE_(n, v)

143 SQUARE = _Fmt('[%s]') # BRACKETS

144 TAG = ANGLE

145 TAGEND = _Fmt('</%s>')

146 tolerance = _Fmt(_tolerance_(_PAREN_g))

147 zone = _Fmt('%02d') # .epsg, .mgrs, .utmupsBase

148

149 def __init__(self):

150 for n, a in self.__class__.__dict__.items():

151 if isinstance(a, (Fstr, _Fmt)):

152 setattr(a, _name_, n)

153

154 def __call__(self, obj, prec=9):

155 '''Return C{str(B{obj})} or C{repr(B{obj})}.

156 '''

157 return str(obj) if isint(obj) else next(

158 _streprs(prec, (obj,), Fmt.g, False, False, repr))

159

160 def INDEX(self, name=NN, i=None, **name_i):

161 '''Return C{"B{name}" if B{i} is None else "B{name}[B{i}]"}.

162 '''

163 if name_i:

164 name, i = _xkwds_item2(name_i)

165 return name if i is None else self.SQUARE(name, i)

166

167 def no_convergence(self, _d, *tol, **thresh):

168 '''Return C{"no convergence (B{_d})"}, C{"no convergence

169 (B{_d}), tolerance (B{tol})"} or C{"no convergence

170 (B{_d}), threshold (B{tol})"}.

171 '''

172 t = Fmt.convergence(fabs(_d))

173 if tol:

174 t = _COMMASPACE_(t, Fmt.tolerance(tol[0]))

175 if thresh and _xkwds_get(thresh, thresh=False):

176 t = t.replace(_tolerance_, _threshold_)

177 return _no_(t)

178

179 def repr_at(self, inst, text=NN):

180 '''Return a C{repr} string C{"<B{text} at B{hex_id}>"}.

181 '''

182 return self.ANGLE(_SPACE_((text or inst), _at_, hex(id(inst))))

183

184 Fmt = Fmt() # PYCHOK singleton

185 Fmt.__name__ = Fmt.__class__.__name__

186

187_DOTSTAR_ = Fmt.DOT(_STAR_)

188# formats %G and %g drop all trailing zeros and the

189# decimal point, making the float appear as an int

190_Gg = (Fmt.G, Fmt.g)

191_FfEeGg = (Fmt.F, Fmt.f, Fmt.E, Fmt.e) + _Gg # float formats

192_Fspec_ = NN('[%[<flags>][<width>]', _DOTSTAR_, ']', _BAR_.join(_FfEeGg)) # in testStreprs

193

194

195 def anstr(name, OKd=_OKd_, sub=_UNDER_):

196 '''Make a valid name of alphanumeric and OKd characters.

197

198 @arg name: The original name (C{str}).

199 @kwarg OKd: Other acceptable characters (C{str}).

200 @kwarg sub: Substitute for invalid charactes (C{str}).

201

202 @return: The modified name (C{str}).

203

204 @note: Leading and trailing whitespace characters are removed,

205 intermediate whitespace characters are coalesced and

206 substituted.

207 '''

208 s = n = str(name).strip()

209 for c in n:

210 if not (c.isalnum() or c in OKd or c in sub):

211 s = s.replace(c, _SPACE_)

212 return sub.join(s.strip().split())

213

214

215 def attrs(inst, *names, **Nones_True__pairs_kwds): # prec=6, fmt=Fmt.F, ints=False, Nones=True, sep=_EQUAL_

216 '''Get instance attributes as I{name=value} strings, with C{float}s

217 formatted by function L{fstr}.

218

219 @arg inst: The instance (any C{type}).

220 @arg names: The attribute names, all other positional (C{str}).

221 @kwarg Nones_True__pairs_kwds: Keyword argument for function L{pairs}, except

222 C{B{Nones}=True} to in-/exclude missing or C{None}-valued attributes.

223

224 @return: A C{tuple(B{sep}.join(t) for t in zip(B{names}, reprs(values, ...)))}

225 of C{str}s.

226 '''

227 def _items(inst, names, Nones):

228 for n in names:

229 v = getattr(inst, n, None)

230 if Nones or v is not None:

231 yield n, v

232

233 def _Nones_kwds(Nones=True, **kwds):

234 return Nones, kwds

235

236 Nones, kwds = _Nones_kwds(**Nones_True__pairs_kwds)

237 return pairs(_items(inst, names, Nones), **kwds)

238

239

240 def enstr2(easting, northing, prec, *extras, **wide_dot):

241 '''Return an MGRS/OSGR easting, northing string representations.

242

243 @arg easting: Easting from false easting (C{meter}).

244 @arg northing: Northing from from false northing (C{meter}).

245 @arg prec: Precision, the number of I{decimal} digits (C{int}) or if

246 negative, the number of I{units to drop}, like MGRS U{PRECISION

247 <https://GeographicLib.SourceForge.io/C++/doc/GeoConvert.1.html#PRECISION>}.

248 @arg extras: Optional leading items (C{str}s).

249 @kwarg wide_dot: Optional keword argument C{B{wide}=%d} for the number of I{unit digits}

250 (C{int}) and C{B{dot}=False} (C{bool}) to insert a decimal point.

251

252 @return: B{C{extras}} + 2-tuple C{(str(B{easting}), str(B{northing}))} or

253 + 2-tuple C{("", "")} for C{B{prec} <= -B{wide}}.

254

255 @raise ValueError: Invalid B{C{easting}}, B{C{northing}} or B{C{prec}}.

256

257 @note: The B{C{easting}} and B{C{northing}} values are I{truncated, not rounded}.

258 '''

259 t = extras

260 try: # like .dms.compassPoint

261 p = min(int(prec), _EN_PREC)

262 w = p + _xkwds_get(wide_dot, wide=_EN_WIDE)

263 if w > 0:

264 f = 10**p # truncate

265 d = (-p) if p > 0 and _xkwds_get(wide_dot, dot=False) else 0

266 t += (_0wdot(w, int(easting * f), d),

267 _0wdot(w, int(northing * f), d))

268 else: # prec <= -_EN_WIDE

269 t += (NN, NN)

270 except (TypeError, ValueError) as x:

271 raise _ValueError(easting=easting, northing=northing, prec=prec, cause=x)

272 return t

273

274 if enstr2.__doc__: # PYCHOK expected

275 enstr2.__doc__ %= (_EN_WIDE,)

276

277

278 def _enstr2m3(estr, nstr, wide=_EN_WIDE): # in .mgrs, .osgr

279 '''(INTERNAL) Convert east- and northing C{str}s to meter and resolution.

280 '''

281 def _s2m2(s, m): # e or n str to float meter

282 if _DOT_ in s:

283 m = 1 # meter

284 else:

285 s += _0_ * wide

286 s = _DOT_(s[:wide], s[wide:wide+_EN_PREC])

287 return float(s), m

288

289 e, m = _s2m2(estr, 0)

290 n, m = _s2m2(nstr, m)

291 if not m:

292 p = max(len(estr), len(nstr)) # 2 = Km, 5 = m, 7 = cm

293 m = 10**max(-_EN_PREC, wide - p) # resolution, meter

294 return e, n, m

295

296

297 def fstr(floats, prec=6, fmt=Fmt.F, ints=False, sep=_COMMASPACE_, strepr=None, force=True):

298 '''Convert one or more floats to string, optionally stripped of trailing zero decimals.

299

300 @arg floats: Single or a list, sequence, tuple, etc. (C{scalar}s).

301 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

302 Trailing zero decimals are stripped if B{C{prec}} is

303 positive, but kept for negative B{C{prec}} values. In

304 addition, trailing decimal zeros are stripped for U{alternate,

305 form '#'<https://docs.Python.org/3/library/stdtypes.html

306 #printf-style-string-formatting>}.

307 @kwarg fmt: Optional C{float} format (C{letter}).

308 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}).

309 @kwarg sep: Separator joining the B{C{floats}} (C{str}).

310 @kwarg strepr: Optional callable to format non-C{floats} (typically

311 C{repr}, C{str}) or C{None} to raise a TypeError and used

312 only if C{B{force} is not True}.

313 @kwarg force: If C{True} format all B{C{floats}} using B{C{fmt}},

314 otherwise use B{C{strepr}} for non-C{floats}.

315

316 @return: The C{sep.join(strs(floats, ...)} joined (C{str}) or single

317 C{strs((floats,), ...)} (C{str}) if B{C{floats}} is C{scalar}.

318 '''

319 if isscalar(floats): # see Fstr.__call__ above

320 return next(_streprs(prec, (floats,), fmt, ints, force, strepr))

321 else:

322 return sep.join(_streprs(prec, floats, fmt, ints, force, strepr))

323

324

325 def _fstrENH2(inst, prec, m, fmt=Fmt.F): # in .css, .lcc, .utmupsBase

326 # (INTERNAL) For C{Css.} and C{Lcc.} C{toRepr} and C{toStr} and C{UtmUpsBase._toStr}.

327 t = inst.easting, inst.northing

328 t = tuple(_streprs(prec, t, fmt, False, True, None))

329 T = _E_, _N_

330 if m is not None and fabs(inst.height): # fabs(self.height) > EPS

331 t += hstr(inst.height, prec=-2, m=m),

332 T += _H_,

333 return t, T

334

335

336 def _fstrLL0(inst, prec, toRepr): # in .azimuthal, .css

337 # (INTERNAL) For C{_AlbersBase.}, C{_AzimuthalBase.} and C{CassiniSoldner.}

338 t = tuple(_streprs(prec, inst.latlon0, Fmt.F, False, True, None))

339 if toRepr:

340 n = inst.name

341 if n:

342 t += Fmt.EQUAL(_name_, repr(n)),

343 t = Fmt.PAREN(inst.classname, _COMMASPACE_.join(t))

344 return t

345

346

347 def fstrzs(efstr, ap1z=False):

348 '''Strip trailing zero decimals from a C{float} string.

349

350 @arg efstr: Float with or without exponent (C{str}).

351 @kwarg ap1z: Append the decimal point and one zero decimal

352 if the B{C{efstr}} is all digits (C{bool}).

353

354 @return: Float (C{str}).

355 '''

356 s = efstr.find(_DOT_)

357 if s >= 0:

358 e = efstr.rfind(Fmt.e)

359 if e < 0:

360 e = efstr.rfind(Fmt.E)

361 if e < 0:

362 e = len(efstr)

363 s += 2 # keep 1st _DOT_ + _0_

364 if s < e and efstr[e-1] == _0_:

365 efstr = NN(efstr[:s], efstr[s:e].rstrip(_0_), efstr[e:])

366

367 elif ap1z:

368 # %.G and %.g formats may drop the decimal

369 # point and all trailing zeros, ...

370 if efstr.isdigit():

371 efstr += _DOT_ + _0_ # ... append or ...

372 else: # ... insert one dot and zero

373 e = efstr.rfind(Fmt.e)

374 if e < 0:

375 e = efstr.rfind(Fmt.E)

376 if e > 0:

377 efstr = NN(efstr[:e], _DOT_, _0_, efstr[e:])

378

379 return efstr

380

381

382 def hstr(height, prec=2, fmt=Fmt.h, ints=False, m=NN):

383 '''Return a string for the height value.

384

385 @arg height: Height value (C{float}).

386 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

387 Trailing zero decimals are stripped if B{C{prec}} is

388 positive, but kept for negative B{C{prec}} values.

389 @kwarg fmt: Optional C{float} format (C{letter}).

390 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}).

391 @kwarg m: Optional unit of the height (C{str}).

392 '''

393 h = next(_streprs(prec, (height,), fmt, ints, True, None))

394 return NN(h, str(m)) if m else h

395

396

397 def instr(inst, *args, **kwds):

398 '''Return the string representation of an instantiation.

399

400 @arg inst: The instance (any C{type}).

401 @arg args: Optional positional arguments.

402 @kwarg kwds: Optional keyword arguments.

403

404 @return: Representation (C{str}).

405 '''

406 return unstr(_MODS.named.classname(inst), *args, **kwds)

407

408

409 def lrstrip(txt, lrpairs=_LR_PAIRS):

410 '''Left- I{and} right-strip parentheses, brackets, etc. from a string.

411

412 @arg txt: String to be stripped (C{str}).

413 @kwarg lrpairs: Parentheses, etc. to remove (C{dict} of one or several

414 C{(Left, Right)} pairs).

415

416 @return: Stripped B{C{txt}} (C{str}).

417 '''

418 _e, _s, _n = str.endswith, str.startswith, len

419 while _n(txt) > 2:

420 for L, R in lrpairs.items():

421 if _e(txt, R) and _s(txt, L):

422 txt = txt[_n(L):-_n(R)]

423 break # restart

424 else:

425 return txt

426

427

428 def pairs(items, prec=6, fmt=Fmt.F, ints=False, sep=_EQUAL_):

429 '''Convert items to I{name=value} strings, with C{float}s handled like L{fstr}.

430

431 @arg items: Name-value pairs (C{dict} or 2-{tuple}s of any C{type}s).

432 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

433 Trailing zero decimals are stripped if B{C{prec}} is

434 positive, but kept for negative B{C{prec}} values.

435 @kwarg fmt: Optional C{float} format (C{letter}).

436 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}).

437 @kwarg sep: Separator joining I{names} and I{values} (C{str}).

438

439 @return: A C{tuple(B{sep}.join(t) for t in B{items}))} of C{str}s.

440 '''

441 try:

442 if isinstance(items, dict):

443 items = itemsorted(items)

444 elif not islistuple(items):

445 items = tuple(items)

446 # can't unzip empty items tuple, list, etc.

447 n, v = _zip(*items) if items else ((), ()) # strict=True

448 except (TypeError, ValueError):

449 raise _IsnotError(dict, '2-tuples', items=items)

450 v = _streprs(prec, v, fmt, ints, False, repr)

451 return tuple(sep.join(t) for t in _zip(map(str, n), v)) # strict=True

452

453

454 def _pct(fmt):

455 '''(INTERNAL) Prefix C{%} if needed.

456 '''

457 return fmt if _PERCENT_ in fmt else NN(_PERCENT_, fmt)

458

459

460 def reprs(objs, prec=6, fmt=Fmt.F, ints=False):

461 '''Convert objects to C{repr} strings, with C{float}s handled like L{fstr}.

462

463 @arg objs: List, sequence, tuple, etc. (any C{type}s).

464 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

465 Trailing zero decimals are stripped if B{C{prec}} is

466 positive, but kept for negative B{C{prec}} values.

467 @kwarg fmt: Optional C{float} format (C{letter}).

468 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}).

469

470 @return: A C{tuple(map(fstr|repr, objs))} of C{str}s.

471 '''

472 return tuple(_streprs(prec, objs, fmt, ints, False, repr)) if objs else ()

473

474

475 def _resolution10(resolution, Error=ValueError): # in .mgrs, .osgr

476 '''(INTERNAL) Validate C{resolution} in C{meter}.

477 '''

478 try:

479 r = int(_log10(resolution))

480 if _EN_WIDE < r or r < -_EN_PREC:

481 raise ValueError

482 except (ValueError, TypeError):

483 raise Error(resolution=resolution)

484 return _MODS.units.Meter(resolution=10**r)

485

486

487 def _streprs(prec, objs, fmt, ints, force, strepr):

488 '''(INTERNAL) Helper for C{fstr}, C{pairs}, C{reprs} and C{strs}

489 '''

490 # <https://docs.Python.org/3/library/stdtypes.html#printf-style-string-formatting>

491 if fmt in _FfEeGg:

492 fGg = fmt in _Gg

493 fmt = NN(_PERCENT_, _DOT_, abs(prec), fmt)

494

495 elif fmt.startswith(_PERCENT_):

496 fGg = False

497 try: # to make sure fmt is valid

498 f = fmt.replace(_DOTSTAR_, Fmt.DOT(abs(prec)))

499 _ = f % (_0_0,)

500 except (TypeError, ValueError):

501 raise _ValueError(fmt=fmt, txt_not_=repr(_DOTSTAR_))

502 fmt = f

503

504 else:

505 raise _ValueError(fmt=fmt, txt_not_=repr(_Fspec_))

506

507 for i, o in enumerate(objs):

508 if force or isinstance(o, float):

509 t = fmt % (float(o),)

510 if ints and t.rstrip(_0to9_ if isint(o, both=True) else

511 _0_).endswith(_DOT_):

512 t = t.split(_DOT_)[0]

513 elif prec > 1:

514 t = fstrzs(t, ap1z=fGg)

515 elif strepr:

516 t = strepr(o)

517 else:

518 t = Fmt.PARENSPACED(Fmt.SQUARE(objs=i), o)

519 raise TypeError(_SPACE_(t, _not_scalar_))

520 yield t

521

522

523 def strs(objs, prec=6, fmt=Fmt.F, ints=False):

524 '''Convert objects to C{str} strings, with C{float}s handled like L{fstr}.

525

526 @arg objs: List, sequence, tuple, etc. (any C{type}s).

527 @kwarg prec: The C{float} precision, number of decimal digits (0..9).

528 Trailing zero decimals are stripped if B{C{prec}} is

529 positive, but kept for negative B{C{prec}} values.

530 @kwarg fmt: Optional C{float} format (C{letter}).

531 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}).

532

533 @return: A C{tuple(map(fstr|str, objs))} of C{str}s.

534 '''

535 return tuple(_streprs(prec, objs, fmt, ints, False, str)) if objs else ()

536

537

538 def unstr(where, *args, **kwds):

539 '''Return the string representation of an invokation.

540

541 @arg where: Class, function, method (C{type}) or name (C{str}).

542 @arg args: Optional positional arguments.

543 @kwarg kwds: Optional keyword arguments, except C{B{_fmt}=Fmt.g}

544 and C{B{_ELLIPSIS}=False}.

545

546 @return: Representation (C{str}).

547 '''

548 def _e_g_kwds3(_ELLIPSIS=False, _fmt=Fmt.g, **kwds):

549 return _ELLIPSIS, _fmt, kwds

550

551 e, g, kwds = _e_g_kwds3(**kwds)

552 t = reprs(args, fmt=g) if args else ()

553 if e:

554 t += _ELLIPSIS_,

555 if kwds:

556 t += pairs(itemsorted(kwds), fmt=g)

557 n = where if isstr(where) else _dunder_nameof(where) # _NN_

558 return Fmt.PAREN(n, _COMMASPACE_.join(t))

559

560

561 def _0wd(*w_i): # in .osgr, .wgrs

562 '''(INTERNAL) Int formatter'.

563 '''

564 return '%0*d' % w_i

565

566

567 def _0wdot(w, f, dot=0):

568 '''(INTERNAL) Int and Float formatter'.

569 '''

570 s = _0wd(w, int(f))

571 if dot:

572 s = _DOT_(s[:dot], s[dot:])

573 return s

574

575

576 def _0wpF(*w_p_f): # in .dms, .osgr

577 '''(INTERNAL) Float deg, min, sec formatter'.

578 '''

579 return '%0*.*f' % w_p_f # XXX was F

580

581

582 def _xzipairs(names, values, sep=_COMMASPACE_, fmt=NN, pair_fmt=Fmt.COLON):

583 '''(INTERNAL) Zip C{names} and C{values} into a C{str}, joined and bracketed.

584 '''

585 try:

586 t = sep.join(pair_fmt(*t) for t in _zip(names, values)) # strict=True

587 except Exception as x:

588 raise _ValueError(names=names, values=values, cause=x)

589 return (fmt % (t,)) if fmt else t # enc

590

591# **) MIT License

592#

593# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

594#

595# Permission is hereby granted, free of charge, to any person obtaining a

596# copy of this software and associated documentation files (the "Software"),

597# to deal in the Software without restriction, including without limitation

598# the rights to use, copy, modify, merge, publish, distribute, sublicense,

599# and/or sell copies of the Software, and to permit persons to whom the

600# Software is furnished to do so, subject to the following conditions:

601#

602# The above copyright notice and this permission notice shall be included

603# in all copies or substantial portions of the Software.

604#

605# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

606# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

607# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

608# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

609# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

610# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

611# OTHER DEALINGS IN THE SOFTWARE.