Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

#!/usr/bin/env python 

# -*- coding: UTF-8 -*- 

# 

# Copyright 2014 European Commission (JRC); 

# Licensed under the EUPL (the 'Licence'); 

# You may not use this work except in compliance with the Licence. 

# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl 

""" 

The user-facing implementation of *xlref*. 

 

Prefer accessing the public members from the parent module. 

""" 

 

from __future__ import unicode_literals 

 

from abc import abstractmethod, ABCMeta 

from collections import namedtuple, OrderedDict 

from copy import deepcopy 

import inspect 

import json 

import logging 

import re 

from string import ascii_uppercase 

import textwrap 

 

from future.backports import ChainMap 

from future.builtins import str 

from future.moves.urllib.parse import urldefrag 

from future.utils import iteritems, with_metaclass 

from past.builtins import basestring 

from toolz import dicttoolz as dtz 

 

import itertools as itt 

import numpy as np 

from pandalone.utils import as_list 

 

 

log = logging.getLogger(__name__) 

 

try: 

    from xlrd import colname as xl_colname 

    # TODO: Try different backends providing `colname` function. 

except ImportError: 

    log.warning( 

        'One of `xlrd`, `...` libraries is needed, will crash later!') 

 

 

CHECK_CELLTYPE = False 

"""When `True`, most coord-functions accept any 2-tuples.""" 

 

"""The key for specifying options within :term:`filters`.""" 

 

Cell = namedtuple('Cell', ['row', 'col']) 

""" 

A pair of 1-based strings, denoting the "A1" coordinates of a cell. 

 

The "num" coords (numeric, 0-based) are specified using numpy-arrays 

(:class:`Coords`). 

""" 

 

 

def _Cell_to_str(cell): 

    r = cell.row 

    c = cell.col 

    try: 

        c = int(c) 

        s = 'R%sC%s' % (r, c, ) 

    except: 

        s = '%s%s' % (c, r) 

    return s.upper() 

 

 

Coords = namedtuple('Coords', ['row', 'col']) 

""" 

A pair of 0-based integers denoting the "num" coordinates of a cell. 

 

The "A1" coords (1-based coordinates) are specified using :class:`Cell`. 

""" 

#     return np.array([row, cell], dtype=np.int16) 

 

 

def coords2Cell(row, col): 

    """Make *A1* :class:`Cell` from *resolved* coords, with rudimentary error-checking. 

 

    Examples:: 

 

        >>> coords2Cell(row=0, col=0) 

        Cell(row='1', col='A') 

        >>> coords2Cell(row=0, col=26) 

        Cell(row='1', col='AA') 

 

        >>> coords2Cell(row=10, col='.') 

        Cell(row='11', col='.') 

 

        >>> coords2Cell(row=-3, col=-2) 

        Traceback (most recent call last): 

        AssertionError: negative row! 

 

 

    """ 

    if row not in _special_coord_symbols: 

        assert row >= 0, 'negative row!' 

        row = str(row + 1) 

    if col not in _special_coord_symbols: 

        assert col >= 0, 'negative col!' 

        col = xl_colname(col) 

    return Cell(row=row, col=col) 

 

Edge = namedtuple('Edge', ('land', 'mov', 'mod')) 

""" 

All the infos required to :term:`target` a cell. 

 

:param Cell land: 

        the :term:`landing-cell` 

:param str mov:  

        use None for missing moves. 

:param str mod:  

        one of (`+`, `-` or `None`) 

 

An :term:`Edge` might be "cooked" or "uncooked" depending on its `land`: 

 

- An *uncooked* edge contains *A1* :class:`Cell`. 

- An *cooked* edge contains a *resolved* :class:`Coords`. 

 

""" 

 

Edge.__new__.__defaults__ = (None, None) 

"""Make optional the last 2 fields of :class:`Edge` ``(mov, mod)`` .""" 

 

 

def _Edge_to_str(edge): 

    c = _Cell_to_str(edge.land) 

    return '%s(%s%s)' % (c, edge.mov, edge.mod or '') if edge.mov else c 

 

 

_topleft_Edge = Edge(Cell('^', '^')) 

_bottomright_Edge = Edge(Cell('_', '_')) 

 

 

def Edge_uncooked(row, col, mov=None, mod=None, default=None): 

    """ 

    Make a new `Edge` from any non-values supplied, as is capitalized, or nothing. 

 

    :param str, None col:    ie ``A`` 

    :param str, None row:    ie ``1`` 

    :param str, None mov:    ie ``RU`` 

    :param str, None mod:    ie ``+`` 

 

    :return:    a `Edge` if any non-None 

    :rtype:     Edge, None 

 

 

    Examples:: 

 

        >>> tr = Edge_uncooked('1', 'a', 'Rul', '-') 

        >>> tr 

        Edge(land=Cell(row='1', col='A'), mov='RUL', mod='-') 

 

 

    No error checking performed:: 

 

        >>> Edge_uncooked('Any', 'foo', 'BaR', '+_&%') 

        Edge(land=Cell(row='Any', col='FOO'), mov='BAR', mod='+_&%') 

 

        >>> print(Edge_uncooked(None, None, None, None)) 

        None 

 

 

    except were coincidental:: 

 

        >>> Edge_uncooked(row=0, col=123, mov='BAR', mod=None) 

        Traceback (most recent call last): 

        AttributeError: 'int' object has no attribute 'upper' 

 

        >>> Edge_uncooked(row=0, col='A', mov=123, mod=None) 

        Traceback (most recent call last): 

        AttributeError: 'int' object has no attribute 'upper' 

    """ 

 

    if col == row == mov == mod is None: 

        return default 

 

    return Edge(land=Cell(col=col and col.upper(), row=row), 

                mov=mov and mov.upper(), mod=mod) 

 

_special_coord_symbols = {'^', '_', '.'} 

 

_primitive_dir_vectors = { 

    'L': Coords(0, -1), 

    'U': Coords(-1, 0), 

    'R': Coords(0, 1), 

    'D': Coords(1, 0) 

} 

 

_regular_xlref_regex = re.compile( 

    r""" 

    ^\s*(?:(?P<sh_name>[^!]+)?!)?                            # xl sheet name 

    (?:                                                      # 1st-edge 

        (?:  

            (?:  

                (?P<st_col>[A-Z]+|[_^])                      # A1-col 

                (?P<st_row>[123456789]\d*|[_^])              # A1-row 

            ) | (?:  

                R(?P<st_row2>-?[123456789]\d*|[_^.])         # RC-row 

                C(?P<st_col2>-?[123456789]\d*|[_^.])         # RC-col 

            )  

        )  

        (?:\(  

            (?P<st_mov>L|U|R|D|LD|LU|UL|UR|RU|RD|DL|DR)      # moves 

            (?P<st_mod>[+-])?                                # move modifiers 

            \)  

        )?  

    )?  

    (?:(?P<colon>:)                                          # ':' needed if 2nd 

        (?:                                                  # 2nd-edge 

            (?:                                              # target 

                (?: 

                    (?P<nd_col>[A-Z]+|[_^.])                 # A1-col 

                    (?P<nd_row>[123456789]\d*|[_^.])         # A1-row 

                ) | (?: 

                    R(?P<nd_row2>-?[123456789]\d*|[_^.])     # RC-row 

                    C(?P<nd_col2>-?[123456789]\d*|[_^.])     # RC-col 

                ) 

            ) 

            (?:\( 

                (?P<nd_mov>L|U|R|D|LD|LU|UL|UR|RU|RD|DL|DR)  # moves 

                (?P<nd_mod>[+-])?                            # move-modifiers 

                \)  

            )?  

        )? 

        (?:  

            :(?P<exp_moves>[LURD?123456789]+)                # expansion moves 

        )? 

    )? 

    (?: 

        :\s*(?P<js_filt>[[{"].*)                             # filters 

    )?$ 

    """, 

    re.IGNORECASE | re.X | re.DOTALL) 

"""The regex for parsing regular :term:`xl-ref`. """ 

 

_re_exp_moves_splitter = re.compile('([LURD]\d+)', re.IGNORECASE) 

 

# TODO: Make exp_moves `?` work different from numbers. 

_re_exp_moves_parser = re.compile( 

    r""" 

    ^(?P<moves>[LURD]+)                                  # primitive moves 

    (?P<times>\?|\d+)?                                   # repetition times 

    $""", 

    re.IGNORECASE | re.X) 

 

 

_excel_str_translator = str.maketrans('“”', '""')  # @UndefinedVariable 

"""Excel use these !@#% chars for double-quotes, which are not valid JSON-strings!!""" 

 

CallSpec = namedtuple('CallSpec', ['func', 'args', 'kwds']) 

"""The :term:`call-specifier` for holding the parsed json-filters.""" 

 

CallSpec.__new__.__defaults__ = ([], {}) 

"""Make optional the last 2 fields of :class:`CallSpec` ``(args', kwds)`` .""" 

 

 

def _parse_call_spec(call_spec_values): 

    """ 

    Parse :term:`call-specifier` from json-filters. 

 

    :param call_spec_values: 

        This is a *non-null* structure specifying some function call  

        in the `filter` part, which it can be either: 

 

        - string: ``"func_name"``  

        - list:   ``["func_name", ["arg1", "arg2"], {"k1": "v1"}]`` 

          where the last 2 parts are optional and can be given in any order; 

        - object: ``{"func": "func_name", "args": ["arg1"], "kwds": {"k":"v"}}``  

          where the `args` and `kwds` are optional. 

 

    :return:  

        the 3-tuple ``func, args=(), kwds={}`` with the defaults as shown  

        when missing.  

    """ 

    def boolarr(l): 

        return np.fromiter(l, dtype=bool) 

 

    def parse_list(func, item1=None, item2=None): 

        items = (item1, item2) 

        isargs = boolarr(isinstance(a, list) for a in items) 

        iskwds = boolarr(isinstance(a, dict) for a in items) 

        isnull = boolarr(a is None for a in items) 

 

        if isargs.all() or iskwds.all() or not ( 

                isargs ^ iskwds ^ isnull).all(): 

            msg = "Cannot decide `args`/`kwds` for call_spec(%s)!" 

            raise ValueError(msg.format(call_spec_values)) 

        args, kwds = None, None 

        if isargs.any(): 

            args = items[isargs.nonzero()[0][0]] 

        if iskwds.any(): 

            kwds = items[iskwds.nonzero()[0][0]] 

        return func, args, kwds 

 

    def parse_object(func, args=None, kwds=None): 

        return func, args, kwds 

 

    try: 

        if isinstance(call_spec_values, basestring): 

            func, args, kwds = call_spec_values, None, None 

        elif isinstance(call_spec_values, list): 

            func, args, kwds = parse_list(*call_spec_values) 

        elif isinstance(call_spec_values, dict): 

            func, args, kwds = parse_object(**call_spec_values) 

        else: 

            msg = "One of str, list or dict expected for call-spec(%s)!" 

            raise ValueError(msg.format(call_spec_values)) 

    except ValueError: 

        raise 

    except Exception as ex: 

        msg = "Cannot parse call-spec({}) due to: {}" 

        raise ValueError(msg.format(call_spec_values, ex)) 

 

    if not isinstance(func, basestring): 

        msg = "Expected a `string` for func({}) for call-spec({})!" 

        raise ValueError(msg.format(func, call_spec_values)) 

    if args is None: 

        args = [] 

    elif not isinstance(args, list): 

        msg = "Expected a `list` for args({}) for call-spec({})!" 

        raise ValueError(msg.format(args, call_spec_values)) 

    if kwds is None: 

        kwds = {} 

    elif not isinstance(kwds, dict): 

        msg = "Expected a `dict` for kwds({}) for call-spec({})!" 

        raise ValueError(msg.format(kwds, call_spec_values)) 

 

    return CallSpec(func, args, kwds) 

 

 

def _repeat_moves(moves, times=None): 

    """ 

    Returns an iterator that repeats `moves` x `times`, or infinite if unspecified. 

 

    Used when parsing primitive :term:`directions`. 

 

   :param str moves: the moves to repeat ie ``RU1D?`` 

   :param str times: N of repetitions. If `None` it means infinite repetitions. 

   :return:    An iterator of the moves 

   :rtype:     iterator 

 

    Examples:: 

 

         >>> list(_repeat_moves('LUR', '3')) 

         ['LUR', 'LUR', 'LUR'] 

         >>> list(_repeat_moves('ABC', '0')) 

         [] 

         >>> _repeat_moves('ABC')  ## infinite repetitions 

         repeat('ABC') 

     """ 

    args = (moves,) 

    if times is not None: 

        args += (int(times), ) 

    return itt.repeat(*args) 

 

 

def _parse_expansion_moves(exp_moves): 

    """ 

    Parse rect-expansion into a list of dir-letters iterables. 

 

    :param exp_moves: 

        A string with a sequence of primitive moves: 

        es. L1U1R1D1 

    :type xl_ref: str 

 

    :return: 

        A list of primitive-dir chains. 

    :rtype: list 

 

 

    Examples:: 

 

        >>> res = _parse_expansion_moves('lu1urd?') 

        >>> res 

        [repeat('L'), repeat('U', 1), repeat('UR'), repeat('D', 1)] 

 

        # infinite generator 

        >>> [next(res[0]) for i in range(10)] 

        ['L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'] 

 

        >>> list(res[1]) 

        ['U'] 

 

        >>> _parse_expansion_moves('1LURD') 

        Traceback (most recent call last): 

        ValueError: Invalid rect-expansion(1LURD) due to: 

                'NoneType' object has no attribute 'groupdict' 

 

    """ 

    try: 

        res = _re_exp_moves_splitter.split(exp_moves.upper().replace('?', '1')) 

 

        return [_repeat_moves(**_re_exp_moves_parser.match(v).groupdict()) 

                for v in res 

                if v != ''] 

 

    except Exception as ex: 

        msg = 'Invalid rect-expansion({}) due to: {}' 

        raise ValueError(msg.format(exp_moves, ex)) 

 

 

def _parse_edge(gs, prefix, default_edge): 

    row_a1, row_rc = gs.pop('%s_row' % prefix), gs.pop('%s_row2' % prefix) 

    col_a1, col_rc = gs.pop('%s_col' % prefix), gs.pop('%s_col2' % prefix) 

    return Edge_uncooked(row_a1 or row_rc, col_a1 or col_rc, 

                         gs.pop('%s_mov' % prefix), 

                         gs.pop('%s_mod' % prefix), default_edge) 

 

 

def _parse_xlref_fragment(xlref_fragment): 

    """ 

    Parses a :term:`xl-ref` fragment(without '#'). 

 

    :param str xlref_fragment: 

            a string with the following format:: 

 

                <sheet>!<st_col><st_row>(<st_mov>):<nd_col><nd_row>(<nd_mov>):<exp_moves>{<js_filt>} 

 

            i.e.:: 

 

                sheet_name!UPT8(LU-):_.(D+):LDL1{"dims":1} 

 

    :return: 

        dictionary containing the following parameters: 

 

        - sheet: (str, int, None) i.e. ``sheet_name`` 

        - st_edge: (Edge, None) the 1st-ref, uncooked, with raw cell 

          i.e. ``Edge(land=Cell(row='8', col='UPT'), mov='LU', mod='-')`` 

        - nd_edge: (Edge, None) the 2nd-ref, uncooked, with raw cell 

          i.e. ``Edge(land=Cell(row='_', col='.'), mov='D', mod='+')`` 

        - exp_moves: (sequence, None), as i.e. ``LDL1`` parsed by  

          :func:`_parse_expansion_moves()` 

        - js_filt: dict i.e. ``{"dims: 1}`` 

 

    :rtype: dict 

 

 

    Examples:: 

 

        >>> res = _parse_xlref_fragment('Sheet1!A1(DR+):Z20(UL):L1U2R1D1:'  

        ...                             '{"opts":{}, "func": "foo"}') 

        >>> sorted(res.items()) 

        [('call_spec', CallSpec(func='foo', args=[], kwds={})), 

         ('exp_moves', 'L1U2R1D1'), 

         ('nd_edge', Edge(land=Cell(row='20', col='Z'), mov='UL', mod=None)), 

         ('opts', {}), 

         ('sh_name', 'Sheet1'), 

         ('st_edge', Edge(land=Cell(row='1', col='A'), mov='DR', mod='+'))] 

 

    Shortcut for all sheet from top-left to bottom-right full-cells:: 

 

        >>> res=_parse_xlref_fragment(':') 

        >>> sorted(res.items()) 

        [('call_spec', None), 

         ('exp_moves', None), 

         ('nd_edge', Edge(land=Cell(row='_', col='_'), mov=None, mod=None)), 

         ('opts', None), 

         ('sh_name', None), 

         ('st_edge', Edge(land=Cell(row='^', col='^'), mov=None, mod=None))] 

 

 

    Errors:: 

 

        >>> _parse_xlref_fragment('A1(DR)Z20(UL)') 

        Traceback (most recent call last): 

        SyntaxError: Not an `xl-ref` syntax: A1(DR)Z20(UL) 

 

    """ 

 

    m = _regular_xlref_regex.match(xlref_fragment) 

    if not m: 

        raise SyntaxError('Not an `xl-ref` syntax: %s' % xlref_fragment) 

 

    gs = m.groupdict() 

 

    is_colon = gs.pop('colon') 

    gs['st_edge'] = _parse_edge(gs, 'st', is_colon and _topleft_Edge) 

    gs['nd_edge'] = _parse_edge(gs, 'nd', is_colon and _bottomright_Edge) 

    assert is_colon or not gs['nd_edge'], (xlref_fragment, gs['nd_edge']) 

 

    exp_moves = gs['exp_moves'] 

    gs['exp_moves'] = exp_moves 

 

    js = gs.pop('js_filt', None) 

    if js: 

        try: 

            js = json.loads(js) 

        except ValueError as ex: 

            msg = 'Filters are not valid JSON: %s\n  JSON: \n%s' 

            raise ValueError(msg % (ex, js)) 

 

    opts = js.pop('opts', None) if isinstance(js, dict) else None 

    if opts is not None and not isinstance(opts, dict): 

        msg = 'Filter-opts({}) must be a json-object(dictionary)!' 

        raise ValueError(msg.format(opts)) 

    gs['opts'] = opts 

    gs['call_spec'] = _parse_call_spec(js) if js else None 

 

    return gs 

 

 

def parse_xlref(xlref): 

    """ 

    Parse a :term:`xl-ref` into a dict. 

 

    :param str xlref: 

        a string with the following format:: 

 

            <url_file>#<sheet>!<1st_edge>:<2nd_edge>:<expand><js_filt> 

 

        i.e.:: 

 

            file:///path/to/file.xls#sheet_name!UPT8(LU-):_.(D+):LDL1{"dims":1} 

 

    :return: A dict with all fields, with None with those missing. 

    :rtype: dict 

 

 

    Examples:: 

 

        >>> res = parse_xlref('workbook.xlsx#Sheet1!A1(DR+):Z20(UL):L1U2R1D1:'  

        ...                             '{"opts":{}, "func": "foo"}') 

        >>> sorted(res.items()) 

         [('call_spec', CallSpec(func='foo', args=[], kwds={})), 

         ('exp_moves', 'L1U2R1D1'), 

         ('nd_edge', Edge(land=Cell(row='20', col='Z'), mov='UL', mod=None)), 

         ('opts', {}), 

         ('sh_name', 'Sheet1'), 

         ('st_edge', Edge(land=Cell(row='1', col='A'), mov='DR', mod='+')), ('url_file', 'workbook.xlsx'), ('xl_ref', 'workbook.xlsx#Sheet1!A1(DR+):Z20(UL):L1U2R1D1:{"opts":{}, "func": "foo"}')] 

 

    Shortcut for all sheet from top-left to bottom-right full-cells:: 

 

        >>> res=parse_xlref('#:') 

        >>> sorted(res.items()) 

        [('call_spec', None), 

         ('exp_moves', None), 

         ('nd_edge', Edge(land=Cell(row='_', col='_'), mov=None, mod=None)), 

         ('opts', None), 

         ('sh_name', None), 

         ('st_edge', Edge(land=Cell(row='^', col='^'), mov=None, mod=None)), 

         ('url_file', None),  

         ('xl_ref', '#:')] 

 

 

    Errors:: 

 

        >>> parse_xlref('A1(DR)Z20(UL)') 

        Traceback (most recent call last): 

        SyntaxError: No fragment-part (starting with '#'): A1(DR)Z20(UL) 

 

        >>> parse_xlref('#A1(DR)Z20(UL)')          ## Missing ':'. 

        Traceback (most recent call last): 

        SyntaxError: Not an `xl-ref` syntax: A1(DR)Z20(UL) 

 

    But as soon as syntax is matched, subsequent errors raised are 

    :class:`ValueErrors`:: 

 

        >>> parse_xlref("#A1:B1:{'Bad_JSON_str'}") 

        Traceback (most recent call last): 

        ValueError: Filters are not valid JSON:  

        Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 

          JSON:  

        {'Bad_JSON_str'} 

    """ 

    xlref = xlref.translate(_excel_str_translator) 

    url_file, frag = urldefrag(xlref) 

    if not frag: 

        raise SyntaxError("No fragment-part (starting with '#'): %s" % xlref) 

    res = _parse_xlref_fragment(frag) 

    frag = frag.strip() 

    res['url_file'] = url_file.strip() or None 

    res['xl_ref'] = xlref 

 

    return res 

 

 

def _margin_coords_from_states_matrix(states_matrix): 

    """ 

    Returns top-left/bottom-down margins of full cells from a :term:`state` matrix. 

 

    May be used by :meth:`ABCSheet.get_margin_coords()` if a backend 

    does not report the sheet-margins internally. 

 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :return:    the 2 coords of the top-left & bottom-right full cells 

    :rtype:     (Coords, Coords) 

 

    Examples:: 

 

        >>> states_matrix = np.asarray([ 

        ...    [0, 0, 0], 

        ...    [0, 1, 0], 

        ...    [0, 1, 1], 

        ...    [0, 0, 1], 

        ... ]) 

        >>> margins = _margin_coords_from_states_matrix(states_matrix) 

        >>> margins 

        (Coords(row=1, col=1), Coords(row=3, col=2)) 

 

 

    Note that the botom-left cell is not the same as `states_matrix` matrix size:: 

 

        >>> states_matrix = np.asarray([ 

        ...    [0, 0, 0, 0], 

        ...    [0, 1, 0, 0], 

        ...    [0, 1, 1, 0], 

        ...    [0, 0, 1, 0], 

        ...    [0, 0, 0, 0], 

        ... ]) 

        >>> _margin_coords_from_states_matrix(states_matrix) == margins 

        True 

 

    """ 

    if not states_matrix.any(): 

        c = Coords(0, 0) 

        return c, c 

    indices = np.array(np.where(states_matrix), dtype=np.int16).T 

 

    # return indices.min(0), indices.max(0) 

    return Coords(*indices.min(0)), Coords(*indices.max(0)) 

 

 

def _row2num(coord): 

    """ 

    Resolves special coords or converts Excel 1-based rows to zero-based, reporting invalids. 

 

    :param str, int coord:     excel-row coordinate or one of ``^_.`` 

    :return:    excel row number, >= 0 

    :rtype:     int 

 

    Examples:: 

 

        >>> row = _row2num('1') 

        >>> row 

        0 

        >>> row == _row2num(1) 

        True 

 

    Negatives (from bottom) are preserved:: 

 

        >>> _row2num('-1') 

        -1 

 

    Fails ugly:: 

 

        >>> _row2num('.') 

        Traceback (most recent call last): 

        ValueError: invalid literal for int() with base 10: '.' 

    """ 

    rcoord = int(coord) 

    if rcoord == 0: 

        msg = 'Uncooked-coord cannot be zero!' 

        raise ValueError(msg.format(coord)) 

    if rcoord > 0: 

        rcoord -= 1 

 

    return rcoord 

 

 

def _col2num(coord): 

    """ 

    Resolves special coords or converts Excel A1 columns to a zero-based, reporting invalids. 

 

    :param str coord:          excel-column coordinate or one of ``^_.`` 

    :return:    excel column number, >= 0 

    :rtype:     int 

 

    Examples:: 

 

        >>> col = _col2num('D') 

        >>> col 

        3 

        >>> _col2num('d') == col 

        True 

        >>> _col2num('AaZ') 

        727 

        >>> _col2num('10') 

        9 

        >>> _col2num(9) 

        8 

 

    Negatives (from left-end) are preserved:: 

 

        >>> _col2num('AaZ') 

        727 

 

    Fails ugly:: 

 

        >>> _col2num('%$') 

        Traceback (most recent call last): 

        ValueError: substring not found 

 

        >>> _col2num([]) 

        Traceback (most recent call last): 

        TypeError: int() argument must be a string, a bytes-like object or  

                    a number, not 'list' 

 

    """ 

    try: 

        rcoord = int(coord) 

    except ValueError: 

        rcoord = 0 

        for c in coord: 

            rcoord = rcoord * 26 + ascii_uppercase.rindex(c.upper()) + 1 

 

        rcoord -= 1 

    else: 

        if rcoord == 0: 

            msg = 'Uncooked-coord cannot be zero!' 

            raise ValueError(msg.format(coord)) 

        elif rcoord > 0: 

            rcoord -= 1 

 

    return rcoord 

 

 

def _resolve_coord(cname, cfunc, coord, up_coord, dn_coord, base_coord=None): 

    """ 

    Translates special coords or converts Excel string 1-based rows/cols to zero-based, reporting invalids. 

 

    :param str cname:  

            the coord-name, one of 'row', 'column' 

    :param function cfunc:  

            the function to convert coord ``str --> int`` 

    :param int, str coord:  

            the "A1" coord to translate 

    :param int up_coord: 

            the resolved *top* or *left* margin zero-based coordinate 

    :param int dn_coord: 

            the resolved *bottom* or *right* margin zero-based coordinate  

    :param int, None base_coord:  

            the resolved basis for dependent coord, if any 

 

    :return: the resolved coord or `None` if it were not a special coord. 

 

 

    Row examples:: 

 

        >>> cname = 'row' 

 

        >>> r0 = _resolve_coord(cname, _row2num, '1', 1, 10) 

        >>> r0 

        0 

        >>> r0 == _resolve_coord(cname, _row2num, 1, 1, 10) 

        True 

        >>> _resolve_coord(cname, _row2num, '^', 1, 10) 

        1 

        >>> _resolve_coord(cname, _row2num, '_', 1, 10) 

        10 

        >>> _resolve_coord(cname, _row2num, '.', 1, 10, 13) 

        13 

        >>> _resolve_coord(cname, _row2num, '-3', 0, 10) 

        8 

 

    But notice when base-cell missing:: 

 

        >>> _resolve_coord(cname, _row2num, '.', 0, 10, base_coord=None) 

        Traceback (most recent call last): 

        ValueError: Cannot resolve `relative-row` without `base-coord`! 

 

    Other ROW error-checks:: 

 

        >>> _resolve_coord(cname, _row2num, '0', 0, 10) 

        Traceback (most recent call last): 

        ValueError: invalid row('0') due to: Uncooked-coord cannot be zero! 

 

        >>> _resolve_coord(cname, _row2num, 'a', 0, 10) 

        Traceback (most recent call last): 

        ValueError: invalid row('a') due to: invalid literal for int() with base 10: 'a' 

 

        >>> _resolve_coord(cname, _row2num, None, 0, 10) 

        Traceback (most recent call last): 

        ValueError: invalid row(None) due to: 

                int() argument must be a string, 

                a bytes-like object or a number, not 'NoneType' 

 

 

    Column examples:: 

 

        >>> cname = 'column' 

 

        >>> _resolve_coord(cname, _col2num, 'A', 1, 10) 

        0 

        >>> _resolve_coord(cname, _col2num, 'DADA', 1, 10) 

        71084 

        >>> _resolve_coord(cname, _col2num, '.', 1, 10, 13) 

        13 

        >>> _resolve_coord(cname, _col2num, '-4', 0, 10) 

        7 

 

    And COLUMN error-checks:: 

 

        >>> _resolve_coord(cname, _col2num, None, 0, 10) 

        Traceback (most recent call last): 

        ValueError: invalid column(None) due to: int() argument must be a string,  

                    a bytes-like object or a number, not 'NoneType' 

 

        >>> _resolve_coord(cname, _col2num, 0, 0, 10) 

        Traceback (most recent call last): 

        ValueError: invalid column(0) due to: Uncooked-coord cannot be zero! 

 

    """ 

    try: 

        if coord in _special_coord_symbols: 

            special_dict = { 

                '^': up_coord, 

                '_': dn_coord 

            } 

            if base_coord is not None: 

                special_dict['.'] = base_coord 

            rcoord = special_dict[coord] 

        else: 

            rcoord = cfunc(coord) 

 

        # Resolve negatives as from the end. 

        if rcoord < 0: 

            rcoord = dn_coord + rcoord + 1 

 

        return rcoord 

    except Exception as ex: 

        if isinstance(ex, KeyError) and ex.args == ('.',): 

            msg = "Cannot resolve `relative-{}` without `base-coord`!" 

            raise ValueError(msg.format(cname)) 

        msg = 'invalid {}({!r}) due to: {}' 

        # fututils.raise_from(ValueError(msg.format(cname, coord, ex)), ex) see 

        # GH 141 

        raise ValueError(msg.format(cname, coord, ex)) 

 

 

def _resolve_cell(cell, up_coords, dn_coords, base_cords=None): 

    """ 

    Translates any special coords to absolute ones. 

 

    To get the margin_coords, use one of: 

 

    * :meth:`ABCSheet.get_margin_coords()` 

    * :func:`_margin_coords_from_states_matrix()` 

 

    :param Cell cell: 

            The "A1" cell to translate its coords. 

    :param Coords up_coords: 

            the top-left resolved coords with full-cells 

    :param Coords dn_coords: 

            the bottom-right resolved coords with full-cells 

    :param Coords base_cords: 

                A resolved cell to base dependent coords (``.``). 

    :return: the resolved cell-coords 

    :rtype:  Coords 

 

 

    Examples:: 

 

        >>> up = Coords(1, 2) 

        >>> dn = Coords(10, 6) 

        >>> base = Coords(40, 50) 

 

        >>> _resolve_cell(Cell(col='B', row=5), up, dn) 

        Coords(row=4, col=1) 

 

        >>> _resolve_cell(Cell('^', '^'), up, dn) 

        Coords(row=1, col=2) 

 

        >>> _resolve_cell(Cell('_', '_'), up, dn) 

        Coords(row=10, col=6) 

 

        >>> base == _resolve_cell(Cell('.', '.'), up, dn, base) 

        True 

 

        >>> _resolve_cell(Cell('-1', '-2'), up, dn) 

        Coords(row=10, col=5) 

 

        >>> _resolve_cell(Cell('A', 'B'), up, dn) 

        Traceback (most recent call last): 

        ValueError: invalid cell(Cell(row='A', col='B')) due to: 

                invalid row('A') due to: invalid literal for int() with base 10: 'A' 

 

    But notice when base-cell missing:: 

 

        >>> _resolve_cell(Cell('1', '.'), up, dn) 

        Traceback (most recent call last): 

        ValueError: invalid cell(Cell(row='1', col='.')) due to:  

        Cannot resolve `relative-col` without `base-coord`! 

 

    """ 

    assert not CHECK_CELLTYPE or isinstance(cell, Cell), cell 

    assert not CHECK_CELLTYPE or isinstance(up_coords, Coords), up_coords 

    assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

    try: 

        if base_cords is None: 

            base_row = base_col = None 

        else: 

            base_row, base_col = base_cords 

        row = _resolve_coord('row', _row2num, cell.row, 

                             up_coords[0], dn_coords[0], base_row) 

        col = _resolve_coord('col', _col2num, cell.col, 

                             up_coords[1], dn_coords[1], base_col) 

 

        return Coords(row, col) 

    except Exception as ex: 

        msg = "invalid cell(%s) due to: %s\n  margins(%s)\n  base_cords(%s)" 

        log.debug(msg, cell, ex, (up_coords, dn_coords), base_cords) 

        msg = "invalid cell(%s) due to: %s" 

        # fututils.raise_from(ValueError(msg % (cell, ex)), ex) see GH 141 

        raise ValueError(msg % (cell, ex)) 

 

 

_mov_vector_slices = { 

    # VECTO_SLICE        REVERSE  COORD_INDEX 

    'L': (1, -1, lambda r, c: (r, slice(None, c + 1))), 

    'U': (0, -1, lambda r, c: (slice(None, r + 1), c)), 

    'R': (1, 1, lambda r, c: (r, slice(c, None))), 

    'D': (0, 1, lambda r, c: (slice(r, None), c)), 

} 

 

 

def _extract_states_vector(states_matrix, dn_coords, land, mov, 

                           mov_slices=_mov_vector_slices): 

    """Extract a slice from the states-matrix by starting from `land` and following `mov`.""" 

    coord_indx, is_reverse, slice_func = mov_slices[mov] 

    vect_slice = slice_func(*land) 

    states_vect = states_matrix[vect_slice] 

    states_vect = states_vect[::is_reverse] 

 

    return states_vect, coord_indx, is_reverse 

 

 

def _target_opposite(states_matrix, dn_coords, land, moves, 

                     edge_name='', primitive_dir_vectors=_primitive_dir_vectors): 

    """ 

    Follow moves from `land` and stop on the 1st full-cell. 

 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :param Coords dn_coords: 

            the bottom-right for the top-left of full-cells 

    :param Coords land: 

            the landing-cell 

    :param str moves: MUST not be empty 

    :return: the identified target-cell's coordinates 

    :rtype: Coords 

 

 

    Examples:: 

 

        >>> states_matrix = np.array([ 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 1, 1, 1], 

        ...     [0, 0, 1, 0, 0, 1], 

        ...     [0, 0, 1, 1, 1, 1] 

        ... ]) 

        >>> args = (states_matrix, Coords(4, 5)) 

 

        >>> _target_opposite(*(args + (Coords(0, 0), 'DR'))) 

        Coords(row=3, col=2) 

 

        >>> _target_opposite(*(args + (Coords(0, 0), 'RD'))) 

        Coords(row=2, col=3) 

 

    It fails if a non-empty target-cell cannot be found, or 

    it ends-up beyond bounds:: 

 

        >>> _target_opposite(*(args + (Coords(0, 0), 'D'))) 

        Traceback (most recent call last): 

        ValueError: No opposite-target found while moving(D) from landing-Coords(row=0, col=0)! 

 

        >>> _target_opposite(*(args + (Coords(0, 0), 'UR'))) 

        Traceback (most recent call last): 

        ValueError: No opposite-target found while moving(UR) from landing-Coords(row=0, col=0)! 

 

 

    But notice that the landing-cell maybe outside of bounds:: 

 

        >>> _target_opposite(*(args + (Coords(3, 10), 'L'))) 

        Coords(row=3, col=5) 

 

    """ 

    assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

    assert not CHECK_CELLTYPE or isinstance(land, Coords), land 

 

    up_coords = np.array([0, 0]) 

    target = np.array(land) 

 

    if land[0] > dn_coords[0] and 'U' in moves: 

        target[0] = dn_coords[0] 

    if land[1] > dn_coords[1] and 'L' in moves: 

        target[1] = dn_coords[1] 

 

#     if states_matrix[target].all(): 

#         return Coords(*target) 

 

    imoves = iter(moves) 

    mov1 = next(imoves) 

    mov2 = next(imoves, None) 

    dv2 = mov2 and primitive_dir_vectors[mov2] 

 

    # Limit negative coords, since they are valid indices. 

    while (up_coords <= target).all(): 

        try: 

            states_vect, coord_indx, is_reverse = _extract_states_vector( 

                states_matrix, dn_coords, target, mov1) 

        except IndexError: 

            break 

        else: 

            if states_vect.any(): 

                indices = states_vect.nonzero()[0] 

                target[coord_indx] += is_reverse * indices.min() 

 

                return Coords(*target) 

 

            if not dv2: 

                break 

 

            target += dv2 

 

    msg = 'No opposite-target found while moving({}) from {}landing-{}!' 

    raise ValueError(msg.format(moves, edge_name, land)) 

 

 

def _target_same_vector(states_matrix, dn_coords, land, mov): 

    """ 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :param Coords dn_coords: 

            the bottom-right for the top-left of full-cells 

    :param Coords land: 

            The landing-cell, which MUST be full! 

    """ 

    states_vect, coord_indx, is_reverse = _extract_states_vector( 

        states_matrix, dn_coords, land, mov) 

    if states_vect.all(): 

        same_len = len(states_vect) - 1 

    else: 

        indices = np.diff(states_vect).nonzero()[0] 

        same_len = indices.min() 

    target_coord = land[coord_indx] + is_reverse * same_len 

 

    return target_coord, coord_indx 

 

 

def _target_same(states_matrix, dn_coords, land, moves, edge_name=''): 

    """ 

    Scan term:`exterior` row and column on specified `moves` and stop on the last full-cell. 

 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :param Coords dn_coords: 

            the bottom-right for the top-left of full-cells 

    :param Coords land: 

            the landing-cell which MUST be within bounds 

    :param moves: which MUST not be empty 

    :return: the identified target-cell's coordinates 

    :rtype: Coords 

 

 

    Examples:: 

 

        >>> states_matrix = np.array([ 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 1, 1, 1], 

        ...     [0, 0, 1, 0, 0, 1], 

        ...     [0, 0, 1, 1, 1, 1] 

        ... ]) 

        >>> args = (states_matrix, Coords(4, 5)) 

 

        >>> _target_same(*(args + (Coords(4, 5), 'U'))) 

        Coords(row=2, col=5) 

 

        >>> _target_same(*(args + (Coords(4, 5), 'L'))) 

        Coords(row=4, col=2) 

 

        >>> _target_same(*(args + (Coords(4, 5), 'UL', ))) 

        Coords(row=2, col=2) 

 

 

    It fails if landing is empty or beyond bounds:: 

 

        >>> _target_same(*(args + (Coords(2, 2), 'DR'))) 

        Traceback (most recent call last): 

        ValueError: No same-target found while moving(DR) from landing-Coords(row=2, col=2)! 

 

        >>> _target_same(*(args + (Coords(10, 3), 'U'))) 

        Traceback (most recent call last): 

        ValueError: No same-target found while moving(U) from landing-Coords(row=10, col=3)! 

 

    """ 

    assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

    assert not CHECK_CELLTYPE or isinstance(land, Coords), land 

 

    target = np.asarray(land) 

    if (target <= dn_coords).all() and states_matrix[land]: 

        for mov in moves: 

            coord, indx = _target_same_vector(states_matrix, dn_coords, 

                                              np.asarray(land), mov) 

            target[indx] = coord 

 

        return Coords(*target) 

    msg = 'No same-target found while moving({}) from {}landing-{}!' 

    raise ValueError(msg.format(moves, edge_name, land)) 

 

 

def _sort_rect(r1, r2): 

    """ 

    Sorts rect-vertices in a 2D-array (with vertices in rows). 

 

    Example:: 

 

        >>> _sort_rect((5, 3), (4, 6)) 

        array([[4, 3], 

               [5, 6]]) 

    """ 

    rect = np.array([r1, r2], dtype=int) 

    rect.sort(0) 

    return rect 

 

 

def _expand_rect(states_matrix, r1, r2, exp_moves): 

    """ 

    Applies the :term:`expansion-moves` based on the `states_matrix`. 

 

    :param state: 

    :param Coords r1: 

              any vertice of the rect to expand 

    :param Coords r2: 

              any vertice of the rect to expand 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :param exp_moves: 

            Just the parsed string, and not `None`. 

    :return: a sorted rect top-left/bottom-right 

 

 

    Examples:: 

 

        >>> states_matrix = np.array([ 

        ...     #0  1  2  3  4  5 

        ...     [0, 0, 0, 0, 0, 0], #0 

        ...     [0, 0, 1, 1, 1, 0], #1 

        ...     [0, 1, 0, 0, 1, 0], #2 

        ...     [0, 1, 1, 1, 1, 0], #3 

        ...     [0, 0, 0, 0, 0, 1], #4 

        ... ], dtype=bool) 

 

        >>> r1, r2 = (Coords(2, 1), Coords(2, 1)) 

        >>> _expand_rect(states_matrix, r1, r2, 'U') 

        (Coords(row=2, col=1), Coords(row=2, col=1)) 

 

        >>> r1, r2 = (Coords(3, 1), Coords(2, 1)) 

        >>> _expand_rect(states_matrix, r1, r2, 'R') 

        (Coords(row=2, col=1), Coords(row=3, col=4)) 

 

        >>> r1, r2 = (Coords(2, 1), Coords(6, 1)) 

        >>> _expand_rect(states_matrix, r1, r2, 'r') 

        (Coords(row=2, col=1), Coords(row=6, col=5)) 

 

        >>> r1, r2 = (Coords(2, 3), Coords(2, 3)) 

        >>> _expand_rect(states_matrix, r1, r2, 'LURD') 

        (Coords(row=1, col=1), Coords(row=3, col=4)) 

 

    """ 

    assert not CHECK_CELLTYPE or isinstance(r1, Coords), r1 

    assert not CHECK_CELLTYPE or isinstance(r2, Coords), r2 

 

    exp_moves = _parse_expansion_moves(exp_moves) 

 

    nd_offsets = np.array([0, 1, 0, 1]) 

    coord_offsets = { 

        'L': np.array([0,  0, -1, 0]), 

        'R': np.array([0,  0,  0, 1]), 

        'U': np.array([-1, 0,  0, 0]), 

        'D': np.array([0,  1,  0, 0]), 

    } 

    coord_indices = { 

        'L': [0, 1, 2, 2], 

        'R': [0, 1, 3, 3], 

        'U': [0, 0, 2, 3], 

        'D': [1, 1, 2, 3], 

    } 

 

    # Sort rect's vertices top-left/bottom-right. 

    # 

    rect = _sort_rect(r1, r2) 

    # ``[r1, r2, c1, c2]`` to use slices, below 

    rect = rect.T.flatten() 

    for dirs_repeated in exp_moves: 

        for dirs in dirs_repeated: 

            orig_rect = rect 

            for d in dirs: 

                exp_rect = rect + coord_offsets[d] 

                exp_vect_i = exp_rect[coord_indices[d]] + nd_offsets 

                exp_vect_v = states_matrix[slice(*exp_vect_i[:2]), 

                                           slice(*exp_vect_i[2:])] 

                if exp_vect_v.any(): 

                    rect = exp_rect 

            if (rect == orig_rect).all(): 

                break 

 

    return Coords(*rect[[0, 2]]), Coords(*rect[[1, 3]]) 

 

 

def resolve_capture_rect(states_matrix, up_dn_margins, 

                         st_edge, nd_edge=None, exp_moves=None, 

                         base_coords=None): 

    """ 

    Performs :term:`targeting`, :term:`capturing` and :term:`expansions` based on the :term:`states-matrix`. 

 

    To get the margin_coords, use one of: 

 

    * :meth:`ABCSheet.get_margin_coords()` 

    * :func:`_margin_coords_from_states_matrix()` 

 

    Its results can be fed into :func:`read_capture_values()`. 

 

    :param np.ndarray states_matrix: 

            A 2D-array with `False` wherever cell are blank or empty. 

            Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

    :param (Coords, Coords) up_dn_margins: 

            the top-left/bottom-right coords with full-cells 

    :param Edge st_edge: "uncooked" as matched by regex 

    :param Edge nd_edge: "uncooked" as matched by regex 

    :param list or none exp_moves: 

            Just the parsed string, and not `None`. 

    :param Coords base_coords: 

            The base for a :term:`dependent` :term;`1st` edge. 

 

    :return:    a ``(Coords, Coords)`` with the 1st and 2nd :term:`capture-cell` 

                ordered from top-left --> bottom-right. 

    :rtype: tuple 

 

    Examples:: 

 

        >>> states_matrix = np.array([ 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 0, 0, 0], 

        ...     [0, 0, 0, 1, 1, 1], 

        ...     [0, 0, 1, 0, 0, 1], 

        ...     [0, 0, 1, 1, 1, 1] 

        ... ], dtype=bool) 

        >>> up, dn = _margin_coords_from_states_matrix(states_matrix) 

 

        >>> st_edge = Edge(Cell('1', 'A'), 'DR') 

        >>> nd_edge = Edge(Cell('.', '.'), 'DR') 

        >>> resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

        (Coords(row=3, col=2), Coords(row=4, col=2)) 

 

    Using dependenent coordinates for the 2nd edge:: 

 

        >>> st_edge = Edge(Cell('_', '_'), None) 

        >>> nd_edge = Edge(Cell('.', '.'), 'UL') 

        >>> rect = resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

        >>> rect 

        (Coords(row=2, col=2), Coords(row=4, col=5)) 

 

    Using sheet's margins:: 

 

        >>> st_edge = Edge(Cell('^', '_'), None) 

        >>> nd_edge = Edge(Cell('_', '^'), None) 

        >>> rect == resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

        True 

 

    Walking backwards:: 

 

        >>> st_edge = Edge(Cell('^', '_'), 'L')          # Landing is full, so 'L' ignored. 

        >>> nd_edge = Edge(Cell('_', '_'), 'L', '+')    # '+' or would also stop. 

        >>> rect == resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

        True 

 

    """ 

    up_margin, dn_margin = up_dn_margins 

    assert not CHECK_CELLTYPE or isinstance(up_margin, Coords), up_margin 

    assert not CHECK_CELLTYPE or isinstance(dn_margin, Coords), dn_margin 

 

    st = _resolve_cell(st_edge.land, up_margin, dn_margin, base_coords) 

    try: 

        st_state = states_matrix[st] 

    except IndexError: 

        st_state = False 

 

    if st_edge.mov is not None: 

        if st_state: 

            if st_edge.mod == '+': 

                st = _target_same(states_matrix, dn_margin, st, st_edge.mov, 

                                  '1st-') 

        else: 

            st = _target_opposite(states_matrix, dn_margin, st, st_edge.mov, 

                                  '1st-') 

 

    if nd_edge is None: 

        nd = None 

    else: 

        nd = _resolve_cell(nd_edge.land, up_margin, dn_margin, st) 

 

        if nd_edge.mov is not None: 

            try: 

                nd_state = states_matrix[nd] 

            except IndexError: 

                nd_state = False 

 

            mov = nd_edge.mov 

            if nd_state: 

                if (nd_edge.mod == '+' or 

                        nd_edge.land == Cell('.', '.') and nd_edge.mod != '-'): 

                    nd = _target_same( 

                        states_matrix, dn_margin, nd, mov, '2nd-') 

            else: 

                nd = _target_opposite( 

                    states_matrix, dn_margin, nd, mov, '2nd-') 

 

    if exp_moves: 

        st, nd = _expand_rect(states_matrix, st, nd or st, exp_moves) 

    else: 

        if nd is not None: 

            rect = _sort_rect(st, nd) 

            st, nd = tuple(Coords(*c) for c in rect) 

 

    return st, nd 

 

 

def _classify_rect_shape(st, nd): 

    """ 

    Identifies rect from its edge-coordinates (row, col, 2d-table).. 

 

    :param Coords st: 

            the top-left edge of capture-rect, inclusive 

    :param Coords or None nd: 

            the bottom-right edge of capture-rect, inclusive 

    :return:  

            in int based on the input like that: 

 

            - 0: only `st` given  

            - 1: `st` and `nd` point the same cell  

            - 2: row  

            - 3: col  

            - 4: 2d-table  

 

    Examples:: 

 

        >>> _classify_rect_shape((1,1), None) 

        0 

        >>> _classify_rect_shape((2,2), (2,2)) 

        1 

        >>> _classify_rect_shape((2,2), (2,20)) 

        2 

        >>> _classify_rect_shape((2,2), (20,2)) 

        3 

        >>> _classify_rect_shape((2,2), (20,20)) 

        4 

    """ 

    if nd is None: 

        return 0 

    rows = nd[0] - st[0] 

    cols = nd[1] - st[1] 

    return 1 + bool(cols) + 2 * bool(rows) 

 

 

def _decide_ndim_by_rect_shape(shape_idx, ndims_list): 

    return ndims_list[shape_idx] 

 

 

def _updim(values, new_ndim): 

    """ 

    Append trivial dimensions to the left. 

 

    :param values:      The scalar ot 2D-results of :meth:`Sheet.read_rect()` 

    :param int new_dim: The new dimension the result should have 

    """ 

    new_shape = (1,) * (new_ndim - values.ndim) + values.shape 

    return values.reshape(new_shape) 

 

 

def _downdim(values, new_ndim): 

    """ 

    Squeeze it, and then flatten it, before inflating it. 

 

    :param values:       The scalar ot 2D-results of :meth:`Sheet.read_rect()` 

    :param int new_dim: The new dimension the result should have 

    """ 

    trivial_indxs = [i for i, d in enumerate(values.shape) if d == 1] 

    offset = values.ndim - new_ndim 

    trivial_ndims = len(trivial_indxs) 

    if offset > trivial_ndims: 

        values = values.flatten() 

    elif offset == trivial_ndims: 

        values = values.squeeze() 

    else: 

        for _, indx in zip(range(offset), trivial_indxs): 

            values = values.squeeze(indx) 

 

    return values 

 

 

def _redim(values, new_ndim): 

    """ 

    Reshapes the :term:`capture-rect` values of :func:`read_capture_rect()`. 

 

    :param values:      The scalar ot 2D-results of :meth:`Sheet.read_rect()` 

    :type values: (nested) list, * 

    :param new_ndim:  

    :type int, (int, bool) or None new_ndim:  

 

    :return: reshaped values 

    :rtype: list of lists, list, * 

 

 

    Examples:: 

 

        >>> _redim([1, 2], 2) 

        [[1, 2]] 

 

        >>> _redim([[1, 2]], 1) 

        [1, 2] 

 

        >>> _redim([], 2) 

        [[]] 

 

        >>> _redim([[3.14]], 0) 

        3.14 

 

        >>> _redim([[11, 22]], 0) 

        [11, 22] 

 

        >>> arr = [[[11], [22]]] 

        >>> arr == _redim(arr, None) 

        True 

 

        >>> _redim([[11, 22]], 0) 

        [11, 22] 

    """ 

    if new_ndim is None: 

        return values 

 

    values = np.asarray(values) 

    try: 

        new_ndim, transpose = new_ndim 

        if transpose: 

            values = values.T 

    except: 

        pass 

    if new_ndim is not None: 

        if values.ndim < new_ndim: 

            values = _updim(values, new_ndim) 

        elif values.ndim > new_ndim: 

            values = _downdim(values, new_ndim) 

 

    return values.tolist() 

 

 

class SheetsFactory(object): 

    """ 

    A caching-store of :class:`ABCSheet` instances, serving them based on (workbook, sheet) IDs, optionally creating them from backends. 

 

    :ivar dict _cached_sheets:  

            A cache of all _Spreadsheets accessed so far,  

            keyed by multiple keys generated by :meth:`_derive_sheet_keys`. 

    :ivar ABCSheet _current_sheet: 

            The last used sheet, used when unspecified by the xlref. 

 

    - To avoid opening non-trivial workbooks, use the :meth:`add_sheet()`  

      to pre-populate this cache with them. 

 

    - The last sheet added becomes the *current-sheet*, and will be  

      served when :term:`xl-ref` does not specify any workbook and sheet. 

 

      .. Tip:: 

          For the simplest API usage, try this:: 

 

              >>> sf = SheetsFactory() 

              >>> sf.add_sheet(some_sheet)              # doctest: +SKIP 

              >>> lasso('A1:C3(U)', sf)                 # doctest: +SKIP 

 

    - The *current-sheet* is served only when wokbook-id is `None`, that is, 

      the id-pair ``('foo.xlsx', None)`` does not hit it, so those ids  

      are send to the cache as they are. 

 

    - To add another backend, modify the opening-sheets logic (ie clipboard),  

      override :meth:`_open_sheet()`. 

 

    - It is a resource-manager for contained sheets, wo it can be used wth  

      a `with` statement. 

 

    """ 

 

    def __init__(self, current_sheet=None): 

        self._current_sheet = current_sheet 

        self._cached_sheets = {} 

 

    def _cache_get(self, key): 

        wb, sh = key 

        if wb in self._cached_sheets: 

            shs = self._cached_sheets[wb] 

            return shs.get(sh, None) 

 

    def _cache_put(self, key, sheet): 

        wb, sh = key 

        if wb in self._cached_sheets: 

            sh_dict = self._cached_sheets[wb] 

        else: 

            sh_dict = self._cached_sheets[wb] = {} 

        sh_dict[sh] = sheet 

 

    def _build_sheet_key(self, wb, sh): 

        assert wb is not None, (wb, sh) 

        return (wb, sh) 

 

    def _derive_sheet_keys(self, sheet,  wb_ids=None, sh_ids=None): 

        """ 

        Retuns the product of user-specified and sheet-internal keys. 

 

        :param wb_ids: 

                a single or a sequence of extra workbook-ids (ie: file, url) 

        :param sh_ids: 

                a single or sequence of extra sheet-ids (ie: name, index, None) 

        """ 

        wb_id, sh_ids2 = sheet.get_sheet_ids() 

        assert wb_id is not None, (wb_id, sh_ids2) 

        wb_ids = [wb_id] + as_list(wb_ids) 

        sh_ids = sh_ids2 + as_list(sh_ids) 

 

        key_pairs = itt.product(wb_ids, sh_ids) 

        keys = list(set(self._build_sheet_key(*p) 

                        for p in key_pairs 

                        if p[0] is not None)) 

        assert keys, (keys, sheet,  wb_ids, sh_ids) 

 

        return keys 

 

    def _close_sheet(self, key): 

        sheet = self._cache_get(key) 

        if sheet: 

            sheet._close() 

            for sh_dict in self._cached_sheets.values(): 

                for sh_id, sh in list(iteritems(sh_dict)): 

                    if sh is sheet: 

                        del sh_dict[sh_id] 

            if self._current_sheet is sheet: 

                self._current_sheet = None 

 

    def close(self): 

        """Closes all contained sheets and empties cache.""" 

        for sh_dict in self._cached_sheets.values(): 

            for sh in sh_dict.values(): 

                sh._close_all() 

        self._cached_sheets = {} 

        self._current_sheet = None 

 

    def add_sheet(self, sheet, wb_ids=None, sh_ids=None, 

                  no_current=False): 

        """ 

        Updates cache and (optionally) `_current_sheet`. 

 

        :param wb_ids: 

                a single or sequence of extra workbook-ids (ie: file, url) 

        :param sh_ids: 

                a single or sequence of extra sheet-ids (ie: name, index, None) 

        """ 

        assert sheet, (sheet, wb_ids, sh_ids) 

        keys = self._derive_sheet_keys(sheet, wb_ids, sh_ids) 

        for k in keys: 

            old_sheet = self._cache_get(k) 

            if old_sheet and old_sheet is not sheet: 

                self._close_sheet(k) 

            self._cache_put(k, sheet) 

        if not no_current: 

            self._current_sheet = sheet 

 

    def fetch_sheet(self, wb_id, sheet_id, opts={}): 

        csheet = self._current_sheet 

        if wb_id is None: 

            if not csheet: 

                msg = "No current-sheet exists yet!. Specify a Workbook." 

                raise ValueError(msg) 

 

            if sheet_id is None: 

                return csheet 

 

            wb_id, c_sh_ids = csheet.get_sheet_ids() 

            assert wb_id is not None, (csheet, c_sh_ids) 

 

            key = self._build_sheet_key(wb_id, sheet_id) 

            sheet = self._cache_get(key) 

 

            if not sheet: 

                sheet = csheet.open_sibling_sheet(sheet_id, opts) 

                assert sheet, (wb_id, sheet_id, opts) 

                self.add_sheet(sheet, wb_id, sheet_id) 

        else: 

            key = self._build_sheet_key(wb_id, sheet_id) 

            sheet = self._cache_get(key) 

            if not sheet: 

                sheet = self._open_sheet(wb_id, sheet_id, opts) 

                assert sheet, (wb_id, sheet_id, opts) 

                self.add_sheet(sheet, wb_id, sheet_id) 

 

        return sheet 

 

    def _open_sheet(self, wb_id, sheet_id, opts): 

        """OVERRIDE THIS to change backend.""" 

        from .import _xlrd 

        return _xlrd.open_sheet(wb_id, sheet_id, opts) 

 

    def __enter__(self): 

        return self 

 

    def __exit__(self, typ, value, traceback): 

        self.close() 

 

 

def _build_call_help(name, func, desc): 

    sig = func and inspect.formatargspec(*inspect.getfullargspec(func)) 

    desc = textwrap.indent(textwrap.dedent(desc), '    ') 

    return '\n\nFilter: %s%s:\n%s' % (name, sig, desc) 

 

Lasso = namedtuple('Lasso', 

                   ('xl_ref', 'url_file', 'sh_name', 

                    'st_edge', 'nd_edge', 'exp_moves', 

                    'call_spec', 

                    'sheet', 'st', 'nd', 'values', 'base_cell', 

                    'opts')) 

""" 

All the fields used by the algorithm, populated stage-by-stage by :class:`Ranger`. 

 

:param str xl_ref: 

        The full url, populated on parsing. 

:param str sh_name: 

        Parsed sheet name (or index, but still as string), populated on parsing. 

:param Edge st_edge: 

        The 1st edge, populated on parsing. 

:param Edge nd_edge: 

        The 2nd edge, populated on parsing. 

:param Coords st: 

        The top-left targeted coords of the :term:`capture-rect`,  

        populated on :term:`capturing`.` 

:param Coords nd: 

        The bottom-right targeted coords of the :term:`capture-rect`,  

        populated on :term:`capturing` 

:param ABCSheet sheet: 

        The fetched from factory or ranger's current sheet, populated  

        after :term:`capturing` before reading. 

:param values: 

        The excel's table-values captured by the :term:`lasso`,  

        populated after reading updated while applying :term:`filters`.  

:param dict or ChainMap opts: 

        - Before `parsing`, they are just any 'opts' dict found in the  

          :term:`filters`.  

        - After *parsing, a 2-map ChainMap with :attr:`Ranger.base_opts` and 

          options extracted from *filters* on top. 

""" 

 

 

Lasso.__new__.__defaults__ = (None,) * len(Lasso._fields) 

"""Make :class:`Lasso` construct with all missing fields as `None`.""" 

 

 

def _Lasso_to_edges_str(lasso): 

    st = _Edge_to_str(lasso.st_edge) if lasso.st_edge else '' 

    nd = _Edge_to_str(lasso.nd_edge) if lasso.nd_edge else '' 

    s = st if st and not nd else '%s:%s' % (st, nd) 

    exp = ':%s' % lasso.exp_moves.upper() if lasso.exp_moves else '' 

    return s + exp 

 

 

class Ranger(object): 

    """ 

    The director-class that performs all stages required for "throwing the lasso" around rect-values. 

 

    Use it when you need to have total control of the procedure and  

    configuration parameters, since no defaults are assumed. 

 

    The :meth:`do_lasso()` does the job. 

 

    :ivar SheetsFactory sheets_factory: 

            Factory of sheets from where to parse rect-values; does not  

            close it in the end. 

            Maybe `None`, but :meth:`do_lasso()` will scream unless invoked  

            with a `context_lasso` arg containing a concrete :class:`ABCSheet`. 

    :ivar dict base_opts:  

            The :term:`opts` that are deep-copied and used as the defaults  

            for every :meth:`do_lasso()`, whether invoked directly or  

            recursively by :meth:`recursive_filter()`. 

            If unspecified, no opts are used, but this attr is set to an  

            empty dict. 

            See :func:`get_default_opts()`. 

    :ivar dict or None available_filters:  

            No filters exist if unspecified.  

            See :func:`get_default_filters()`. 

    :ivar Lasso intermediate_lasso: 

            A ``('stage', Lasso)`` pair with the last :class:`Lasso` instance  

            produced during the last execution of the :meth:`do_lasso()`. 

            Used for inspecting/debuging. 

    :ivar _context_lasso_fields: 

            The name of the fields taken from `context_lasso` arg of  

            :meth:`do_lasso()`, when the parsed ones are `None`. 

            Needed for recursive invocations, see :meth:`recursive_filter`. 

    """ 

 

    _context_lasso_fields = ['sheet', 'st', 'nd', 'base_cell'] 

 

    def __init__(self, sheets_factory, 

                 base_opts=None, available_filters=None): 

        self.sheets_factory = sheets_factory 

        if base_opts is None: 

            base_opts = {} 

        self.base_opts = base_opts 

        self.available_filters = available_filters 

        self.intermediate_lasso = None 

 

    def _relasso(self, lasso, stage, **kwds): 

        """Replace lasso-values and updated :attr:`intermediate_lasso`.""" 

        lasso = lasso._replace(**kwds) 

        self.intermediate_lasso = (stage, lasso) 

 

        return lasso 

 

    def _make_call(self, lasso, func_name, args, kwds): 

        def parse_avail_func_rec(func, desc=None): 

            if not desc: 

                desc = func.__doc__ 

            return func, desc 

 

        # Just to update intermediate_lasso. 

        lasso = self._relasso(lasso, func_name) 

 

        lax = lasso.opts.get('lax', False) 

        verbose = lasso.opts.get('verbose', False) 

        func, func_desc = '', '' 

        try: 

            func_rec = self.available_filters[func_name] 

            func, func_desc = parse_avail_func_rec(**func_rec) 

            lasso = func(self, lasso, *args, **kwds) 

            assert isinstance(lasso, Lasso), (func_name, lasso) 

        except Exception as ex: 

            if verbose: 

                func_desc = _build_call_help(func_name, func, func_desc) 

            msg = "While invoking(%s, %s, %s): %s%s" 

            help_msg = func_desc if verbose else '' 

            if lax: 

                log.warning( 

                    msg, func_name, args, kwds, ex, help_msg, exc_info=1) 

            else: 

                raise ValueError(msg % (func_name, args, kwds, ex, help_msg)) 

 

        return lasso 

 

    def pipe_filter(self, lasso, *pipe): 

        """ 

        Apply all call-specifiers one after another on the captured values. 

 

        :param list pipe: the call-specifiers 

        """ 

 

        for call_spec_values in pipe: 

            call_spec = _parse_call_spec(call_spec_values) 

            lasso = self._make_call(lasso, *call_spec) 

 

        return lasso 

 

    def recursive_filter(self, lasso, include=None, exclude=None, depth=-1): 

        """ 

        Recursively expand any :term:`xl-ref` strings found by treating values as mappings (dicts, df, series) and/or nested lists. 

 

        - The `include`/`exclude` filter args work only for dict-like objects 

          with ``items()`` or ``iteritems()`` and indexing methods,  

          i.e. Mappings, series and dataframes. 

 

          - If no filter arg specified, expands for all keys.  

          - If only `include` specified, rejects all keys not explicitly  

            contained in this filter arg. 

          - If only `exclude` specified, expands all keys not explicitly  

            contained in this filter arg. 

          - When both `include`/`exclude` exist, only those explicitely  

            included are accepted, unless also excluded. 

 

        - Lower the :mod:`logging` level to see other than syntax-errors on 

          recursion reposrted on :data:`log`; . 

 

        :param list or str include: 

                Items to include in the recursive-search. 

                See descritpion above. 

        :param list or str exclude: 

                Items to include in the recursive-search. 

                See descritpion above. 

        :param int or None depth: 

                How deep to dive into nested structures for parsing xl-refs. 

                If `< 0`, no limit. If 0, stops completely. 

        """ 

        include = include and as_list(include) 

        exclude = exclude and as_list(exclude) 

 

        def verbose(msg): 

            if lasso.opts.get('verbose', False): 

                msg = '%s \n    @Lasso: %s' % (msg, lasso) 

            return msg 

 

        def is_included(key): 

            ok = not include or key in include 

            ok &= not exclude or key not in exclude 

            return ok 

 

        def new_base_cell(base_cell, cdepth, i): 

            if base_cell: 

                if cdepth == 0: 

                    base_cell = base_cell._replace(row=i) 

                elif cdepth == 1: 

                    base_cell = base_cell._replace(col=i) 

            return base_cell 

 

        def dive_list(vals, base_cell, cdepth): 

            if isinstance(vals, basestring): 

                context = lasso._asdict() 

                context['base_cell'] = base_cell 

                try: 

                    rlasso = self.do_lasso(vals, **context) 

                    vals = rlasso and rlasso.values 

                except SyntaxError as ex: 

                    msg = "Skipped recursive-lassoing value(%s) due to: %s" 

                    log.debug(msg, vals, ex) 

                except Exception as ex: 

                    msg = "Lassoing  %s stopped due to: \n  %s" % (vals, ex) 

                    raise ValueError(verbose(msg)) 

            elif isinstance(vals, list): 

                for i, v in enumerate(vals): 

                    nbc = new_base_cell(base_cell, cdepth, i) 

                    vals[i] = dive_indexed(v, nbc, cdepth + 1) 

 

            return vals 

 

        def dive_indexed(vals, base_cell, cdepth): 

            if cdepth != depth: 

                dived = False 

                try: 

                    items = iteritems(vals) 

                except: 

                    pass  # Just to avoid chained ex. 

                else: 

                    for k, v in items: 

                        if is_included(k): 

                            # No base_cell possible with Indexed. 

                            vals[k] = dive_indexed(v, None, cdepth + 1) 

                    dived = True 

                if not dived: 

                    vals = dive_list(vals, base_cell, cdepth) 

 

            return vals 

 

        values = dive_indexed(lasso.values, lasso.st, 0) 

 

        return lasso._replace(values=values) 

 

    def _make_init_Lasso(self, **context_kwds): 

        """Creates the lasso to be used for each new :meth:`do_lasso()` invocation.""" 

        def is_context_field(field): 

            return field in self._context_lasso_fields 

 

        context_fields = dtz.keyfilter(is_context_field, context_kwds) 

        context_fields['opts'] = ChainMap(deepcopy(self.base_opts)) 

        init_lasso = Lasso(**context_fields) 

 

        return init_lasso 

 

    def _parse_and_merge_with_context(self, xlref, init_lasso): 

        """ 

        Merges xl-ref parsed-parsed_fields with `init_lasso`, reporting any errors. 

 

        :param Lasso init_lasso:  

                Default values to be overridden by non-nulls. 

                Note that ``init_lasso.opts`` must be a `ChainMap`, 

                as returned by :math:`_make_init_Lasso()`.  

 

        :return: a Lasso with any non `None` parsed-fields updated 

        """ 

        assert isinstance(init_lasso.opts, ChainMap), init_lasso 

 

        try: 

            parsed_fields = parse_xlref(xlref) 

            parsed_opts = parsed_fields.pop('opts', None) 

            if parsed_opts: 

                init_lasso.opts.maps.insert(0, parsed_opts) 

            filled_fields = dtz.valfilter(lambda v: v is not None, 

                                          parsed_fields) 

            init_lasso = init_lasso._replace(**filled_fields) 

        except SyntaxError: 

            raise 

        except Exception as ex: 

            msg = "Parsing xl-ref(%r) failed due to: %s" 

            log.debug(msg, xlref, ex, exc_info=1) 

            # raise fututils.raise_from(ValueError(msg % (xlref, ex)), ex) see GH 

            # 141 

            raise ValueError(msg % (xlref, ex)) 

 

        return init_lasso 

 

    def _fetch_sheet_from_lasso(self, sheet, url_file, sh_name, opts): 

        if sheet and url_file is None: 

            if sh_name is not None: 

                sheet = sheet.open_sibling_sheet(sh_name, opts) 

                if sheet and self.sheets_factory: 

                    self.sheets_factory.add_sheet(sheet, sh_ids=sh_name) 

            return sheet 

 

    def _open_sheet(self, lasso): 

        try: 

            sheet = self._fetch_sheet_from_lasso(lasso.sheet, 

                                                 lasso.url_file, lasso.sh_name, 

                                                 lasso.opts) 

            if not sheet: 

                if not self.sheets_factory: 

                    msg = "The xl-ref(%r) specifies 'url-file` part but Ranger has no sheet-factory!" 

                    raise Exception(msg % lasso.xl_ref) 

                sheet = self.sheets_factory.fetch_sheet( 

                    lasso.url_file, lasso.sh_name, 

                    lasso.opts)  # Maybe context had a Sheet already. 

        except Exception as ex: 

            msg = "Loading sheet([%s]%s) failed due to: %s" 

            raise ValueError(msg % (lasso.url_file, lasso.sh_name, ex)) 

        return sheet 

 

    def _resolve_capture_rect(self, lasso, sheet): 

        try: 

            st, nd = resolve_capture_rect(sheet.get_states_matrix(), sheet.get_margin_coords(), 

                                          lasso.st_edge, lasso.nd_edge, lasso.exp_moves) 

        except Exception as ex: 

            msg = "Resolving capture-rect(%r) failed due to: %s" 

            raise ValueError(msg % (_Lasso_to_edges_str(lasso), ex)) 

        return st, nd 

 

    def do_lasso(self, xlref, **context_kwds): 

        """ 

        The director-method that does all the job of hrowing a :term:`lasso` 

        around spreadsheet's rect-regions according to :term:`xl-ref`. 

 

        :param str xlref: 

            a string with the :term:`xl-ref` format:: 

 

                <url_file>#<sheet>!<1st_edge>:<2nd_edge>:<expand><js_filt> 

 

            i.e.:: 

 

                file:///path/to/file.xls#sheet_name!UPT8(LU-):_.(D+):LDL1{"dims":1} 

 

        :param Lasso context_kwds:  

                Default :class:`Lasso` fields in case parsed ones are `None`  

                Only those in :attr:`_context_lasso_fields` are taken  

                into account. 

                Utilized  by :meth:`recursive_filter()`. 

        :return:  

                The final :class:`Lasso` with captured & filtered values. 

        :rtype: Lasso 

        """ 

        self.intermediate_lasso = None 

 

        lasso = self._make_init_Lasso(**context_kwds) 

        lasso = self._relasso(lasso, 'context') 

 

        lasso = self._parse_and_merge_with_context(xlref, lasso) 

        lasso = self._relasso(lasso, 'parse') 

 

        sheet = self._open_sheet(lasso) 

        lasso = self._relasso(lasso, 'open', sheet=sheet) 

 

        st, nd = self._resolve_capture_rect(lasso, sheet) 

        lasso = self._relasso(lasso, 'resolve_capture_rect', 

                              st=st, nd=nd, base_cell=lasso.base_cell) 

 

        values = sheet.read_rect(st, nd) 

        lasso = self._relasso(lasso, 'read_rect', values=values) 

 

        if lasso.call_spec: 

            try: 

                # relasso() internally 

                lasso = self._make_call(lasso, *lasso.call_spec) 

            except Exception as ex: 

                msg = "Filtering xl-ref(%r) failed due to: %s" 

                raise ValueError(msg % (lasso.xl_ref, ex)) 

 

        return lasso 

 

############### 

# FILTER-DEFS 

############### 

 

 

def xlwings_dims_call_spec(): 

    """A list :term:`call-spec` for :meth:`_redim_filter` :term:`filter` that imitates results of *xlwings* library.""" 

    return '["redim", [0, 1, 1, 1, 2]]' 

 

 

def redim_filter(ranger, lasso, 

                 scalar=None, cell=None, row=None, col=None, table=None): 

    """ 

    Reshape and/or transpose captured values, depending on rect's shape. 

 

    Each dimension might be a single int or None, or a pair [dim, transpose].  

    """ 

    ndims_list = (scalar, cell, row, col, table) 

    shape_idx = _classify_rect_shape(lasso.st, lasso.nd) 

    new_ndim = _decide_ndim_by_rect_shape(shape_idx, ndims_list) 

    values = lasso.values 

    if new_ndim is not None: 

        lasso = lasso._replace(values=_redim(values, new_ndim)) 

 

    return lasso 

 

 

def get_default_filters(overrides=None): 

    """ 

   The default available :term:`filters` used by :func:`lasso()` when constructing its internal :class:`Ranger`. 

 

    :param dict or None overrides: 

            Any items to update the default ones. 

 

    :return:  

            a dict-of-dicts with 2 items:  

 

            - *func*: a function with args: ``(Ranger, Lasso, *args, **kwds)`` 

            - *desc*:  help-text replaced by ``func.__doc__`` if missing. 

 

    :rtype:  

            dict 

    """ 

    filters = { 

        'pipe': { 

            'func': Ranger.pipe_filter, 

        }, 

        'recurse': { 

            'func': Ranger.recursive_filter, 

        }, 

        'redim': { 

            'func': redim_filter, 

        }, 

        'numpy': { 

            'func': lambda ranger, lasso, * args, **kwds: lasso._replace( 

                values=np.array(lasso.values, *args, **kwds)), 

            'desc': np.array.__doc__, 

        }, 

        'dict': { 

            'func': lambda ranger, lasso, * args, **kwds: lasso._replace( 

                values=dict(lasso.values, *args, **kwds)), 

            'desc': dict.__doc__, 

        }, 

        'odict': { 

            'func': lambda ranger, lasso, * args, **kwds: lasso._replace( 

                values=OrderedDict(lasso.values, *args, **kwds)), 

            'desc': OrderedDict.__doc__, 

        }, 

        'sorted': { 

            'func': lambda ranger, lasso, * args, **kwds: lasso._replace( 

                values=sorted(lasso.values, *args, **kwds)), 

            'desc': sorted.__doc__, 

        }, 

    } 

 

    try: 

        import pandas as pd 

        from pandas.io import parsers, excel as pdexcel 

 

        def _df_filter(ranger, lasso, *args, **kwds): 

            values = lasso.values 

            header = kwds.get('header', 'infer') 

            if header == 'infer': 

                header = kwds['header'] = 0 if kwds.get( 

                    'names') is None else None 

            if header is not None: 

                values[header] = pdexcel._trim_excel_header(values[header]) 

            # , convert_float=True, 

            parser = parsers.TextParser(values, **kwds) 

            lasso = lasso._replace(values=parser.read()) 

 

            return lasso 

 

        filters.update({ 

            'df': { 

                'func': _df_filter, 

                'desc': parsers.TextParser.__doc__, 

            }, 

            'series': { 

                'func': lambda ranger, lasso, *args, **kwds: pd.Series(OrderedDict(lasso.values), 

                                                                       *args, **kwds), 

                'desc': ("Converts a 2-columns list-of-lists into pd.Series.\n" + 

                         pd.Series.__doc__), 

            } 

        }) 

    except ImportError as ex: 

        msg = "The 'df' and 'series' filters were notinstalled, due to: %s" 

        log.info(msg, ex) 

 

    if overrides: 

        filters.update(overrides) 

 

    return filters 

 

 

def get_default_opts(overrides=None): 

    """ 

    Default :term:`opts` used by :func:`lasso()` when constructing its internal :class:`Ranger`. 

 

    :param dict or None overrides: 

            Any items to update the default ones. 

    """ 

    opts = { 

        'lax': False, 

        'verbose': False, 

        'read': {'on_demand': True, }, 

    } 

 

    if overrides: 

        opts.update(overrides) 

 

    return opts 

 

 

def make_default_Ranger(sheets_factory=None, 

                        base_opts=None, 

                        available_filters=None): 

    """ 

    Makes a defaulted :class:`Ranger`. 

 

    :param sheets_factory: 

            Factory of sheets from where to parse rect-values; if unspecified,  

            a new :class:`SheetsFactory` is created. 

            Remember to invoke its :meth:`SheetsFactory.close()` to clear 

            resources from any opened sheets.  

    :param dict or None base_opts:  

            Default opts to affect the lassoing, to be merged with defaults;  

            uses :func:`get_default_opts()`. 

 

            Read the code to be sure what are the available choices :-(.  

    :param dict or None available_filters:  

            The :term:`filters` available to xlrefs, to be merged with defaults;. 

            Uses :func:`get_default_filters()` if unspecified. 

 

    """ 

    return Ranger(sheets_factory or SheetsFactory(), 

                  base_opts or get_default_opts(), 

                  available_filters or get_default_filters()) 

 

 

def lasso(xlref, 

          sheets_factory=None, 

          base_opts=None, 

          available_filters=None, 

          return_lasso=False, 

          **context_kwds): 

    """ 

    High-level function to :term:`lasso` around spreadsheet's rect-regions  

    according to :term:`xl-ref` strings by using internally a :class:`Ranger` . 

 

    :param str xlref: 

        a string with the :term:`xl-ref` format:: 

 

            <url_file>#<sheet>!<1st_edge>:<2nd_edge>:<expand><js_filt> 

 

        i.e.:: 

 

            file:///path/to/file.xls#sheet_name!UPT8(LU-):_.(D+):LDL1{"dims":1} 

 

    :param sheets_factory: 

            Factory of sheets from where to parse rect-values; if unspecified,  

            the new :class:`SheetsFactory` created is closed afterwards. 

            Delegated to :func:`make_default_Ranger()`, so items override 

            default ones; use a new :class:`Ranger` if that is not desired. 

    :ivar dict or None base_opts:  

            Opts affecting the lassoing procedure that are deep-copied and used 

            as the base-opts for every :meth:`Ranger.do_lasso()`, whether invoked  

            directly or recursively by :meth:`Ranger.recursive_filter()`.  

            Read the code to be sure what are the available choices.  

            Delegated to :func:`make_default_Ranger()`, so items override 

            default ones; use a new :class:`Ranger` if that is not desired. 

    :param dict or None available_filters:  

            Delegated to :func:`make_default_Ranger()`, so items override 

            default ones; use a new :class:`Ranger` if that is not desired. 

    :param bool return_lasso: 

            If `True`, values are contained in the returned Lasso instance, 

            along with all other artifacts of the :term:`lassoing` procedure. 

 

            For more debugging help, create a :class:`Range` yourself and  

            inspect the :attr:`Ranger.intermediate_lasso`. 

    :param Lasso context_kwds:  

            Default :class:`Lasso` fields in case parsed ones are `None` 

            (i.e. you can specify the sheet like that). 

            Only those in :attr:`Ranger._context_lasso_fields` are taken  

            into account. 

 

    :return:  

            Either the captured & filtered values or the final :class:`Lasso`, 

            depending on the `return_lassos` arg. 

    """ 

    factory_is_mine = not sheets_factory 

    if base_opts is None: 

        base_opts = get_default_opts() 

    if available_filters is None: 

        available_filters = get_default_filters() 

 

    try: 

        ranger = make_default_Ranger(sheets_factory=sheets_factory, 

                                     base_opts=base_opts, 

                                     available_filters=available_filters) 

        lasso = ranger.do_lasso(xlref, **context_kwds) 

    finally: 

        if factory_is_mine: 

            ranger.sheets_factory.close() 

 

    return lasso if return_lasso else lasso.values 

 

 

class ABCSheet(with_metaclass(ABCMeta, object)): 

    """ 

    A delegating to backend factory and sheet-wrapper with utility methods. 

 

    :param np.ndarray _states_matrix: 

            The :term:`states-matrix` cached, so recreate object 

            to refresh it. 

    :param dict _margin_coords: 

            limits used by :func:`_resolve_cell`, cached, so recreate object 

            to refresh it. 

 

    Resource management is outside of the scope of this class, 

    and must happen in the backend workbook/sheet instance. 

 

    *xlrd* examples:: 

 

        >>> import xlrd                                       #  doctest: +SKIP 

        >>> with xlrd.open_workbook(self.tmp) as wb:          #  doctest: +SKIP 

        ...     sheet = xlref.xlrdSheet(wb.sheet_by_name('Sheet1')) 

        ...     ## Do whatever 

 

    *win32* examples:: 

 

        >>> with dsgdsdsfsd as wb:          #  doctest: +SKIP 

        ...     sheet = xlref.win32Sheet(wb.sheet['Sheet1']) 

        TODO: Win32 Sheet example 

    """ 

 

    _states_matrix = None 

    _margin_coords = None 

 

    def _close(self): 

        """ Override it to release resources for this sheet.""" 

 

    def _close_all(self): 

        """ Override it to release resources this and all sibling sheets.""" 

 

    @abstractmethod 

    def get_sheet_ids(self): 

        """ 

        :return: a 2-tuple of its wb-name and a sheet-ids of this sheet i.e. name & indx 

        :rtype: ([str or None, [str or int or None]) 

        """ 

 

    @abstractmethod 

    def open_sibling_sheet(self, sheet_id, opts=None): 

        """Return a sibling sheet by the given index or name""" 

 

    @abstractmethod 

    def _read_states_matrix(self): 

        """ 

        Read the :term:`states-matrix` of the wrapped sheet. 

 

        :return:   A 2D-array with `False` wherever cell are blank or empty. 

        :rtype:     ndarray 

        """ 

 

    def get_states_matrix(self): 

        """ 

        Read and cache the :term:`states-matrix` of the wrapped sheet. 

 

        :return:   A 2D-array with `False` wherever cell are blank or empty. 

        :rtype:     ndarray 

        """ 

        if self._states_matrix is None: 

            self._states_matrix = self._read_states_matrix() 

        return self._states_matrix 

 

    @abstractmethod 

    def read_rect(self, st, nd): 

        """ 

        Fecth the actual values from the backend Excel-sheet. 

 

        :param Coords st: 

                the top-left edge, inclusive 

        :param Coords, None nd: 

                the bottom-right edge, inclusive(!); when `None`, 

                must return a scalar value. 

        :return:  

                a 1D or 2D-list with the values fenced by the rect, 

                which might be empty if beyond limits. 

        :rtype: list 

        """ 

 

    def _read_margin_coords(self): 

        """ 

        Override if possible to read (any of the) limits directly from the sheet. 

 

        :return:    the 2 coords of the top-left & bottom-right full cells; 

                    anyone coords can be None. 

                    By default returns ``(None, None)``. 

        :rtype:     (Coords, Coords) 

 

        """ 

        return None, None  # pragma: no cover 

 

    def get_margin_coords(self): 

        """ 

        Extract (and cache) margins either internally or from :func:`_margin_coords_from_states_matrix()`. 

 

        :return:    the resolved top-left and bottom-right :class:`Coords` 

        :rtype:     tuple 

 

        """ 

        if not self._margin_coords: 

            up, dn = self._read_margin_coords() 

            if up is None or dn is None: 

                sm = self.get_states_matrix() 

                up1, dn1 = _margin_coords_from_states_matrix(sm) 

                up = up or up1 

                dn = dn or dn1 

            self._margin_coords = up, dn 

 

        return self._margin_coords 

 

    def __repr__(self): 

        return '%s%s' % (type(self), self.get_sheet_ids()) 

 

 

class ArraySheet(ABCSheet): 

    """A sample :class:`ABCSheet` made out of 2D-list or numpy-arrays, for facilitating tests.""" 

 

    def __init__(self, arr, ids=('wb', ['sh', 0])): 

        self._arr = np.asarray(arr) 

        self._ids = ids 

 

    def open_sibling_sheet(self, sheet_id): 

        raise NotImplementedError() 

 

    def get_sheet_ids(self): 

        return self._ids 

 

    def _read_states_matrix(self): 

        return ~np.equal(self._arr, None) 

 

    def read_rect(self, st, nd): 

        if nd is None: 

            return self._arr[st] 

        rect = np.array([st, nd]) + [[0, 0], [1, 1]] 

        return self._arr[slice(*rect[:, 0]), slice(*rect[:, 1])].tolist() 

 

    def __repr__(self): 

        return 'ArraySheet%s \n%s' % (self.get_sheet_ids(), self._arr)