master 17bcc4abb60e cached
121 files
978.1 KB
245.6k tokens
1409 symbols
1 requests
Download .txt
Showing preview only (1,026K chars total). Download the full file or copy to clipboard to get everything.
Repository: JetBrains/intellij-micropython
Branch: master
Commit: 17bcc4abb60e
Files: 121
Total size: 978.1 KB

Directory structure:
gitextract_ebr8_o39/

├── .github/
│   └── workflows/
│       └── check.yml
├── .gitignore
├── CHANGES.md
├── LICENSE.txt
├── Pipfile
├── README.md
├── build.gradle.kts
├── examples/
│   └── rpsls.py
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── licenses/
│   └── microrepl_license.txt
├── scripts/
│   ├── findusb.py
│   ├── microcleanfs.py
│   ├── microrepl.py
│   └── microupload.py
├── src/
│   └── main/
│       ├── kotlin/
│       │   └── com/
│       │       └── jetbrains/
│       │           └── micropython/
│       │               ├── actions/
│       │               │   ├── MicroPythonAction.kt
│       │               │   ├── MicroPythonCommandAction.kt
│       │               │   ├── RemoveAllFilesFromDeviceAction.kt
│       │               │   └── RunMicroReplAction.kt
│       │               ├── devices/
│       │               │   ├── Esp8266DeviceProvider.kt
│       │               │   ├── MicroBitDeviceProvider.kt
│       │               │   ├── MicroBitV2DeviceProvider.kt
│       │               │   ├── MicroPythonDeviceProvider.kt
│       │               │   ├── PyboardDeviceProvider.kt
│       │               │   └── RPiPicoDeviceProvider.kt
│       │               ├── inspections/
│       │               │   └── MicroPythonRequirementsInspection.kt
│       │               ├── repl/
│       │               │   ├── MicroPythonReplManager.kt
│       │               │   ├── StopReplBeforeRunTask.kt
│       │               │   └── ToolWindowReplTab.kt
│       │               ├── run/
│       │               │   ├── MicroPythonConfigurationType.kt
│       │               │   ├── MicroPythonRunConfiguration.kt
│       │               │   ├── MicroPythonRunConfigurationEditor.kt
│       │               │   ├── MicroPythonRunConfigurationProducer.kt
│       │               │   └── MicroUpload.kt
│       │               ├── settings/
│       │               │   ├── MicroPythonDevicesConfiguration.kt
│       │               │   ├── MicroPythonFacet.kt
│       │               │   ├── MicroPythonFacetConfiguration.kt
│       │               │   ├── MicroPythonFacetDetector.kt
│       │               │   ├── MicroPythonFacetEditorTab.kt
│       │               │   ├── MicroPythonFacetType.kt
│       │               │   ├── MicroPythonModuleConfigurable.kt
│       │               │   ├── MicroPythonProjectConfigurable.kt
│       │               │   ├── MicroPythonSettingsPanel.kt
│       │               │   ├── MicroPythonTypeHints.kt
│       │               │   └── MicroPythonUsbId.kt
│       │               └── ui/
│       │                   └── MicroPythonToolWindowFactory.kt
│       └── resources/
│           ├── META-INF/
│           │   └── plugin.xml
│           └── inspectionDescriptions/
│               └── MicroPythonRequirements.html
└── typehints/
    ├── esp32/
    │   ├── esp.pyi
    │   ├── esp32.pyi
    │   └── network.pyi
    ├── esp8266/
    │   ├── esp.pyi
    │   └── network.pyi
    ├── microbit/
    │   ├── microbit/
    │   │   ├── __init__.pyi
    │   │   ├── accelerometer.pyi
    │   │   ├── compass.pyi
    │   │   ├── display.pyi
    │   │   ├── i2c.pyi
    │   │   ├── spi.pyi
    │   │   └── uart.pyi
    │   ├── music.pyi
    │   ├── neopixel.pyi
    │   ├── radio.pyi
    │   └── speech.pyi
    ├── micropython/
    │   ├── bluetooth.pyi
    │   ├── btree.pyi
    │   ├── cryptolib.pyi
    │   ├── framebuf.pyi
    │   ├── machine.pyi
    │   ├── micropython.pyi
    │   ├── neopixel.pyi
    │   ├── network.pyi
    │   ├── ubluetooth.pyi
    │   ├── ucryptolib.pyi
    │   └── uctypes.pyi
    ├── pyboard/
    │   ├── lcd160cr.pyi
    │   ├── pyb.pyi
    │   └── stm.pyi
    ├── rpi_pico/
    │   └── rp2.pyi
    └── stdlib/
        ├── _thread.pyi
        ├── array.pyi
        ├── binascii.pyi
        ├── cmath.pyi
        ├── collections.pyi
        ├── errno.pyi
        ├── gc.pyi
        ├── hashlib.pyi
        ├── heapq.pyi
        ├── io.pyi
        ├── json.pyi
        ├── math.pyi
        ├── os.pyi
        ├── re.pyi
        ├── select.pyi
        ├── socket.pyi
        ├── ssl.pyi
        ├── struct.pyi
        ├── sys.pyi
        ├── time.pyi
        ├── uarray.pyi
        ├── uasyncio.pyi
        ├── ubinascii.pyi
        ├── ucollections.pyi
        ├── uerrno.pyi
        ├── uhashlib.pyi
        ├── uheapq.pyi
        ├── uio.pyi
        ├── ujson.pyi
        ├── uos.pyi
        ├── ure.pyi
        ├── uselect.pyi
        ├── usocket.pyi
        ├── ussl.pyi
        ├── ustruct.pyi
        ├── usys.pyi
        ├── utime.pyi
        ├── uzlib.pyi
        └── zlib.pyi

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/check.yml
================================================
name: check

on:
  push:
    branches:
      - master
  pull_request:
  schedule:
    -   cron: '0 3 * * *'

# Allow cancelling all previous runs for the same branch
# See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#concurrency
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-plugin:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          distribution: corretto
          java-version: 17

      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v4

      - name: Build plugin
        run: ./gradlew :buildPlugin -Pversion=SNAPSHOT-${{ github.run_number }}

      - name: Upload plugin archive
        uses: actions/upload-artifact@v4
        with:
          name: intellij-micropython-SNAPSHOT-${{ github.run_number }}
          path: build/distributions/intellij-micropython-SNAPSHOT-${{ github.run_number }}.zip


================================================
FILE: .gitignore
================================================
*.iml
.idea/
!/.idea/runConfigurations/
.gradle/
build/
venv/
tmp/

# IntelliJ Platform Gradle Plugin
.intellijPlatform/


================================================
FILE: CHANGES.md
================================================
The Changelog
=============

1.4.6 - 2024-08-28
------------------

* Support for 2024.2 IDE versions
  ([#295](https://github.com/JetBrains/intellij-micropython/issues/295))

1.4.5 - 2024-07-27
------------------

### Fixed

* Don't interrupt program execution when REPL is started right after the upload
  ([#313](https://github.com/JetBrains/intellij-micropython/pull/313))
* Update `machine.pyi`
  ([#291](https://github.com/JetBrains/intellij-micropython/pull/291))
  (Thanks to [Lucio Rossi](https://github.com/eigen-value))
* Update `network.pyi`
  ([#296](https://github.com/JetBrains/intellij-micropython/pull/296))

1.4.4 - 2024-07-13
------------------

### Fixed

* Compatibility with 2024.1.x IDEs
* REPL should work fine with the latest IDE versions

1.4.2 - 2023-10-11
------------------

### Fixed

* Metro M4 Airlift Lite support added
  ([#254](https://github.com/JetBrains/intellij-micropython/pull/254))
  (Thanks to [@PierreDeQuebec](https://github.com/PierreDeQuebec))
* Compatibility issue in REPL support is fixed
  ([#253](https://github.com/JetBrains/intellij-micropython/pull/253))
  (Thanks to [@lancelote](https://github.com/lancelote))

1.4.1 - 2023-03-17
------------------

### Added

* Type Hints for ESP32 added
  ([#218](https://github.com/JetBrains/intellij-micropython/pull/218))
  (Thanks to [@MrNavaStar](https://github.com/MrNavaStar))

1.4.0 - 2022-11-21
------------------

### Added

* MicroPython REPL running in a dedicated tool window 
  ([#139](https://github.com/JetBrains/intellij-micropython/pull/139))
  (Thanks to [@lensvol](https://github.com/lensvol))
* Support for the Micro:bit V2 device type
  ([#186](https://github.com/JetBrains/intellij-micropython/pull/186))

### Changed

* Compatibility with 2021.3-2022.3


1.3.3 — 2022-09-23
------------------

### Fixed

* Broken compatibility with the older PyCharm versions

1.3.2 — 2022-09-23
------------------

### Fixed

* An error on opening projects in PyCharm 2022.2.2
  ([#205](https://github.com/JetBrains/intellij-micropython/issues/205))


1.3.1 — 2022-03-18
------------------

### Changed

* Compatibility with 2020.3-2022.1
  ([#184](https://github.com/vlasovskikh/intellij-micropython/issues/184))


1.3 — 2021-12-01
----------------

### Added 

* Added many stubs for the MicroPython standard library and Pyboard
  ([#176](https://github.com/vlasovskikh/intellij-micropython/pull/176))
  (Thanks to [@hlovatt](https://github.com/hlovatt))

### Changed

* Compatibility with 2020.3-2021.3

### Fixed

* Fixed special keys in REPL on Windows for pyserial>=3.5
  ([#175](https://github.com/vlasovskikh/intellij-micropython/issues/175))


1.2 — 2021-08-05
----------------

### Added

* Added support for Raspberry Pi Pico devices
  ([#132](https://github.com/vlasovskikh/intellij-micropython/issues/132))
  (Thanks to [@timsavage](https://github.com/timsavage))
* Added type hints for `lcd160cr`, `network`, `ubluetooth`, `ucryptolib`, `uctypes`
  (Thanks to [@hlovatt](https://github.com/hlovatt))

### Changed

* Compatibility with 2020.3-2021.2
  ([#170](https://github.com/vlasovskikh/intellij-micropython/issues/170))
* Updated type hints for `pyb`, `machine`, `micropython`, `uarray`, `btree`, `framebuf`
  (Thanks to [@hlovatt](https://github.com/hlovatt))

### Fixed

* Fixed handling backslash while flashing files on Windows
  ([#128](https://github.com/vlasovskikh/intellij-micropython/issues/128))
  (Thanks to [@jdjjm](https://github.com/jdjjm))

1.1.4 — 2021-03-05
------------------

* Compatibility with 2020.2-2021.1

1.1.3 — 2020-12-12
------------------

* Added an SVG icon for MicroPython actions
* Fixed a regression in 2020.3 that prevented the plugin from updating and persisting
  your device type on changing it in the settings

1.1.2 — 2020-10-24
------------------

* Added a type hinting stub for `pyb`
* Switched to newer terminal API to fix regression in PyCharm 2020.2
* Compatibility with 2020.2-2020.3

1.1.1 — 2020-06-24
------------------

* Fixed control characters in REPL on Windows
* Fixed path separators for flashing directories on Windows

1.1 — 2020-06-07
----------------

* Auto-detect a connected MicroPython device with an option to specify the device path
  manually in the IDE settings for MicroPython
* Use the nearest directory marked "Sources Root" as the root of your device while
  flashing files
* Ignore `.git/`, `.idea/` and other files starting with `.` when flashing a directory
* Launch a run configuration to flash a directory from its context menu
* Compatibility with 2020.1-2020.2

1.0.14 — 2020-01-31
-------------------

* Compatibility with 2019.3-2020.1

1.0.13 — 2019-10-02
-------------------

* Compatibility with 2019.3 only

1.0.12 — 2019-07-23
-------------------

* Compatibility with 2018.3-2019.2

1.0.11 — 2019-02-12
-------------------

* Compatibility with 2018.3-2019.1

1.0.10 — 2018-11-22
-------------------

* Compatibility with 2018.3 only

1.0.9 — 2018-09-10
------------------

* Compatibility with 2018.2-2018.3

1.0.8 — 2018-07-25
------------------

* Compatibility with 2018.2 only

1.0.7 — 2018-06-19
------------------

* Compatibility with 2017.3-2018.2

1.0.6 — 2018-02-23
------------------

* Fixed several bugs in `machine` stub

1.0.5 — 2018-02-11
------------------

* Don't delete `boot.py` when removing all files from the device #35

1.0.4 — 2018-01-18
------------------

* Fixed launching REPL on Windows #12

1.0.3 — 2018-01-16
------------------

* Fixed the outdated pyserial version in requirements #26
* Fixed the error message when getting `EACCESS` error for the device file #27

1.0.2 — 2018-01-15
------------------

* Restored compatibility with IntelliJ

1.0.1 — 2018-01-15
------------------

* Restored compatibility with 2017.2-2018.1

1.0 — 2018-01-15
----------------

* Run files and REPL for ESP8266 and Pyboard devices
* Initial code insight for ESP8266 and MicroPython standard library
* Action for detecting the device path in the MicroPython settings
* Action for removing all files from the device

0.1 — 2017-06-18
----------------

* Code insight and documentation for Micro:bit Python API
* Run Python files on Micro:bit
* Micro:bit Python REPL


================================================
FILE: LICENSE.txt
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2000-2016 JetBrains s.r.o.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: Pipfile
================================================
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
docopt = "*"
adafruit-ampy = "*"
pyserial = "*"

[dev-packages]

[requires]
python_version = "3.7"


================================================
FILE: README.md
================================================
# MicroPython Plugin for PyCharm and IntelliJ

[![JetBrains team project](http://jb.gg/badges/team.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)
[![JetBrains IntelliJ Plugins](https://img.shields.io/jetbrains/plugin/v/9777-micropython)](https://plugins.jetbrains.com/plugin/9777-micropython)
[![JetBrains IntelliJ plugins](https://img.shields.io/jetbrains/plugin/d/9777-micropython)](https://plugins.jetbrains.com/plugin/9777-micropython)
[![JetBrains IntelliJ Plugins](https://img.shields.io/jetbrains/plugin/r/rating/9777-micropython)](https://plugins.jetbrains.com/plugin/9777-micropython)
[![check](https://github.com/JetBrains/intellij-micropython/actions/workflows/check.yml/badge.svg?branch=master)](https://github.com/JetBrains/intellij-micropython/actions/workflows/check.yml)
[![Join the chat at https://gitter.im/intellij-micropython/community](https://badges.gitter.im/intellij-micropython/community.svg)](https://gitter.im/intellij-micropython/community)

The Python code development plugin for [MicroPython](http://micropython.org/) devices in
[PyCharm](https://www.jetbrains.com/pycharm/) and [IntelliJ](https://www.jetbrains.com/idea/).

## Discontinued

- The project is discontinued and is no longer maintained
- Kindly use [MicroPython Tools](https://plugins.jetbrains.com/plugin/26227-micropython-tools/) instead

## Supported devices

The plugin supports Python development for these devices:

* [ESP8266](https://github.com/JetBrains/intellij-micropython/wiki/ESP8266)
* [PyBoard](https://github.com/JetBrains/intellij-micropython/wiki/Pyboard)
* [BBC Micro:bit](https://github.com/JetBrains/intellij-micropython/wiki/BBC-Micro%3Abit)
* [Raspberry Pi Pico](https://www.raspberrypi.org/products/raspberry-pi-pico/)

It will support more MicroPython devices and more device-specific and MicroPython-specific modules eventually. We are
interested in your contributions to the project. Feel free to open issues and send pull requests!

See also [the changelog](CHANGES.md) for the plugin.

## Features


### Code insight for MicroPython modules

* Context-aware code completion and documentation
    * Use <kbd>Ctrl+Q</kbd> (<kbd>F1</kbd> on macOS) for quick documentation window, you can dock it permanently

      ![Code completion](media/code-completion.png)

* Syntax checking and type checking
    * The plugin checks your code while you're typing it

      ![Type checking](media/type-checking.png)


### Run code on MicroPython devices

* Flash Python files or project directories to devices
    * Right-click on a file or directory and select <em>"Run 'Flash <your-file-name>'"</em> to flash this item to your
      connected device. If you want to flash a sub-directory to the root directory of your device, please mark this
      sub-directory as a sources root: right-click on it and select <em>"Mark Directory as | Sources Root"</em>. Its
      icon will become blue, see the screenshot.
    
      ![Flash directory](media/flash-directory.png)

    * You can edit your run configurations for flashing files or directories in <em>"Run | Edit Configurations..."</em>
      menu.

      ![Run](media/run.png)

* MicroPython REPL
    * Use <em>"Tools | MicroPython | MicroPython REPL"</em> menu to run a MicroPython shell on your device. Or open 
  MicroPython REPL tool window directly

      ![REPL](media/repl_toolwindow.png)


## Requirements

* PyCharm or IntelliJ
* Python 3.5+
    * The MicroPython language version is 3.5. If you select a newer version, turn on <em>"File | Settings | Editor |
      Inspections | Python | Code compatibility inspection"</em> and add Python 3.5 to the compatibility list there
* Python plugin (IntelliJ only)
* Supported MicroPython development board with a recent version of MicroPython firmware flashed to the board


## Installation

1. Install the "MicroPython" plugin from your IDE settings.

2. Create a new project or open an existing folder with your MicroPython code.

3. This step differs for PyCharm and IntelliJ:
    * PyCharm: Enable MicroPython support in <em>"File | Settings | Languages & Frameworks | MicroPython"</em> and
      specify the path to your MicroPython device
    * IntelliJ: Add the MicroPython facet to a Python module in your project structure and specify the path to your
      MicroPython device

    ![Configurable](media/configurable.png)

4. Open any Python file in project. You may see a yellow bar on top of the file, notifying you that you don't
   have some packages required for communicating with your device. In this case click "Install requirements" and wait
   while the plugin downloads and installs the packages.


## Source Code

We write this plugin in Python and [Kotlin](https://kotlinlang.org/). Kotlin a new JVM language by JetBrains, the
makers of PyCharm and IntelliJ. Google recommends Kotlin as the best language for developing Android apps. If you are a
Python developer, Kotlin may be an interesting language for you to learn.

The steps for setting up the development environment:

1. Check out this project from GitHub
2. Create a new project from existing sources in IntelliJ

To just run the development version use `./gradlew clean runIde` from the command line
or just run **runIde** [run configuration](https://www.jetbrains.com/help/idea/run-debug-configuration.html).

Contributions are welcome!


## License

The plugin is licensed under the terms of the Apache 2 license.


================================================
FILE: build.gradle.kts
================================================
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

repositories {
    mavenCentral()
    intellijPlatform {
        defaultRepositories()
    }
}

plugins {
    kotlin("jvm") version "2.0.20"
    id("org.jetbrains.intellij.platform") version "2.0.1"
}

dependencies {
    intellijPlatform {
        val type = project.property("platformType").toString()
        val version = project.property("platformVersion").toString()
        val pythonPlugin = project.property("pythonPlugin").toString()

        create(type, version, useInstaller = false)

        bundledPlugin("org.jetbrains.plugins.terminal")

        when (type) {
            "PC" -> bundledPlugin("PythonCore")
            "PY" -> bundledPlugin("Pythonid")
            else -> plugin(pythonPlugin)
        }
    }
}

java {
    sourceCompatibility = JavaVersion.VERSION_21
    targetCompatibility = JavaVersion.VERSION_21
}

intellijPlatform {
    pluginConfiguration {
        name = "MicroPython"
    }

    instrumentCode = false

    publishing {
        token = project.property("publishToken").toString()
    }
}

tasks {
    withType<KotlinCompile> {
        compilerOptions {
            jvmTarget = JvmTarget.JVM_21
            languageVersion = KotlinVersion.DEFAULT
            apiVersion = KotlinVersion.KOTLIN_1_9
        }
    }
    prepareSandbox {
        from("$rootDir") {
            into("intellij-micropython")
            include("typehints/")
            include("scripts/")
        }
    }
}


================================================
FILE: examples/rpsls.py
================================================
from random import choice
import gc

import radio
from microbit import *


CLASSIC_STORY = """
Scissors cuts Paper
Paper covers Rock
Rock crushes Scissors
"""


SHELDON_COOPER_STORY = """
Scissors cuts Paper
Paper covers Rock
Rock crushes Lizard
Lizard poisons Spock
Spock smashes Scissors
Scissors decapitates Lizard
Lizard eats Paper
Paper disproves Spock
Spock vaporizes Rock
(and as it always has) Rock crushes Scissors
"""


STORY = SHELDON_COOPER_STORY


# @formatter:off
SKETCHES = {
    'Scissors': '*    :'
                '  *  :'
                '    *:'
                '  *  :'
                '*    :',

    'Paper':    '*****:'
                '*   *:'
                '*   *:'
                '*   *:'
                '*****:',

    'Rock':     ' *** :'
                '*****:'
                '*****:'
                '*****:'
                ' *** :',

    'Lizard':   '**   :'
                '  *  :'
                '  *  :'
                '  *  :'
                '   **:',

    'Spock':    ' *** :'
                '*****:'
                '** **:'
                '** **:'
                '** **:',
}
# @formatter:on


def sketch_to_image(sketch):
    return Image(sketch.replace(' ', '0').replace('*', '9'))


IMAGES = {name: sketch_to_image(sketch) for name, sketch in SKETCHES.items()}


def parse_story(story):
    gc.collect()
    sentences = [line.split()[-3:] for line in story.split('\n') if line.strip()]
    actors = {s for s, v, o in sentences}
    victims = {actor: {o for s, v, o in sentences if s == actor} for actor in actors}
    return actors, victims


ACTORS, VICTIMS = parse_story(STORY)


def random_outcome():
    return choice(list(ACTORS))


def expired(time):
    return abs(running_time() - time) > 2000


def beats(actor, victim):
    return victim in VICTIMS.get(actor, [])


def wait_for_outcome():
    start = running_time()
    while not expired(start):
        received = radio.receive()
        if received:
            return received


def main():
    last_received = 0
    other_outcome = None

    radio.on()

    while True:
        received = radio.receive()
        if received:
            other_outcome = received
            last_received = running_time()

        if not accelerometer.was_gesture('face down'):
            continue

        my_outcome = random_outcome()
        radio.send(my_outcome)

        if not other_outcome or expired(last_received):
            other_outcome = wait_for_outcome()

        if other_outcome:
            sleep(1000)
            image = IMAGES.get(my_outcome, Image.SAD)
            if beats(my_outcome, other_outcome):
                to_show = [Image('00000:'
                                 '00000:'
                                 '00000:'
                                 '00000:'
                                 '00000:'), image, image, image] * 5

            else:
                to_show = [image] * 20

            display.show(to_show, delay=200, clear=True, wait=False)
            other_outcome = None


if __name__ == '__main__':
    main()



================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists


================================================
FILE: gradle.properties
================================================
version=1.4.6-2024.2
platformType=PC
platformVersion=242-EAP-SNAPSHOT
pythonPlugin=PythonCore:242.20224.300
publishToken=token

# Since kotlin 1.4, stdlib dependency is added by default by kotlin gradle plugin.
# But we don't need it because all necessary kotlin libraries are already bundled into IDE.
# See https://kotlinlang.org/docs/gradle-configure-project.html#dependency-on-the-standard-library for more details
kotlin.stdlib.default.dependency=false


================================================
FILE: gradlew
================================================
#!/bin/sh

#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
#   Gradle start up script for POSIX generated by Gradle.
#
#   Important for running:
#
#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
#       noncompliant, but you have some other compliant shell such as ksh or
#       bash, then to run this script, type that shell name before the whole
#       command line, like:
#
#           ksh Gradle
#
#       Busybox and similar reduced shells will NOT work, because this script
#       requires all of these POSIX shell features:
#         * functions;
#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
#         * compound commands having a testable exit status, especially «case»;
#         * various built-in commands including «command», «set», and «ulimit».
#
#   Important for patching:
#
#   (2) This script targets any POSIX shell, so it avoids extensions provided
#       by Bash, Ksh, etc; in particular arrays are avoided.
#
#       The "traditional" practice of packing multiple parameters into a
#       space-separated string is a well documented source of bugs and security
#       problems, so this is (mostly) avoided, by progressively accumulating
#       options in "$@", and eventually passing that to Java.
#
#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
#       see the in-line comments for details.
#
#       There are tweaks for specific operating systems such as AIX, CygWin,
#       Darwin, MinGW, and NonStop.
#
#   (3) This script is generated from the Groovy template
#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
#       within the Gradle project.
#
#       You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
app_path=$0

# Need this for daisy-chained symlinks.
while
    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
    [ -h "$app_path" ]
do
    ls=$( ls -ld "$app_path" )
    link=${ls#*' -> '}
    case $link in             #(
      /*)   app_path=$link ;; #(
      *)    app_path=$APP_HOME$link ;;
    esac
done

# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

warn () {
    echo "$*"
} >&2

die () {
    echo
    echo "$*"
    echo
    exit 1
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in                #(
  CYGWIN* )         cygwin=true  ;; #(
  Darwin* )         darwin=true  ;; #(
  MSYS* | MINGW* )  msys=true    ;; #(
  NONSTOP* )        nonstop=true ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD=$JAVA_HOME/jre/sh/java
    else
        JAVACMD=$JAVA_HOME/bin/java
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD=java
    if ! command -v java >/dev/null 2>&1
    then
        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
    case $MAX_FD in #(
      max*)
        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        MAX_FD=$( ulimit -H -n ) ||
            warn "Could not query maximum file descriptor limit"
    esac
    case $MAX_FD in  #(
      '' | soft) :;; #(
      *)
        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        ulimit -n "$MAX_FD" ||
            warn "Could not set maximum file descriptor limit to $MAX_FD"
    esac
fi

# Collect all arguments for the java command, stacking in reverse order:
#   * args from the command line
#   * the main class name
#   * -classpath
#   * -D...appname settings
#   * --module-path (only if needed)
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )

    JAVACMD=$( cygpath --unix "$JAVACMD" )

    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    for arg do
        if
            case $arg in                                #(
              -*)   false ;;                            # don't mess with options #(
              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
                    [ -e "$t" ] ;;                      #(
              *)    false ;;
            esac
        then
            arg=$( cygpath --path --ignore --mixed "$arg" )
        fi
        # Roll the args list around exactly as many times as the number of
        # args, so each arg winds up back in the position where it started, but
        # possibly modified.
        #
        # NB: a `for` loop captures its iteration list before it begins, so
        # changing the positional parameters here affects neither the number of
        # iterations, nor the values presented in `arg`.
        shift                   # remove old arg
        set -- "$@" "$arg"      # push replacement arg
    done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
#     and any embedded shellness will be escaped.
#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
#     treated as '${Hostname}' itself on the command line.

set -- \
        "-Dorg.gradle.appname=$APP_BASE_NAME" \
        -classpath "$CLASSPATH" \
        org.gradle.wrapper.GradleWrapperMain \
        "$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
    die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
#   set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
        xargs -n1 |
        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
        tr '\n' ' '
    )" '"$@"'

exec "$JAVACMD" "$@"


================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*

:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: licenses/microrepl_license.txt
================================================
Copyright 2015 The Python Software Foundation (http://python.org/)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: scripts/findusb.py
================================================
# Copyright 2000-2017 JetBrains s.r.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Find USB devices.

Usage:
    findusb

Outputs the list of all USB devices it has managed to find.
"""

from serial.tools.list_ports import comports

def main() -> None:
    for port in comports():
        if port.vid is not None and port.pid is not None:
            print('0x%02x:0x%02x %s' % (port.vid, port.pid, port.device))


if __name__ == '__main__':
    main()


================================================
FILE: scripts/microcleanfs.py
================================================
# Copyright 2000-2017 JetBrains s.r.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Remove the contents of the file system on a MicroPython device.

Usage:
    microcleanfs PORT [options]

    Options:
    -f --force     Remove ALL files from filesystem w/o preserving excludes
"""

import traceback
from typing import List

import sys
import time

from ampy.files import Files
from ampy.pyboard import Pyboard, PyboardError
from docopt import docopt


def main(args: List[str]) -> None:
    opts = docopt(__doc__, argv=args)
    port = opts['PORT']
    force = opts['--force']

    print('Connecting to {}'.format(port), file=sys.stderr)
    board = Pyboard(port)
    files = Files(board)

    # Specifying subdirectories DOES NOT work as they will be deleted when the
    # parent directory is deleted. Specifying top level directories DOES work.
    exclude_files = ['boot.py']

    print('Removing the contents of the file system')
    wait_for_board()
    for name in files.ls(long_format=False):
        if force or name not in exclude_files:
            try:
                files.rm(name)
            except (RuntimeError, PyboardError):
                try:
                    files.rmdir(name)
                except (RuntimeError, PyboardError):
                    print('Unknown Error removing file {}'.format(name),
                          file=sys.stderr)

    print('Done')


def wait_for_board() -> None:
    """Wait for some ESP8266 devices to become ready for REPL commands."""
    time.sleep(0.5)


if __name__ == '__main__':
    try:
        main(sys.argv[1:])
        exitcode = 0
    except:
        traceback.print_exc()
        exitcode = 1
    finally:
        input('Press ENTER to continue')
    sys.exit(exitcode)


================================================
FILE: scripts/microrepl.py
================================================
# Copyright 2015 The Python Software Foundation (http://python.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
A simple shim around PySerial that detects the correct port to which the
MicroPython device is connected and attempts to make a serial connection to it
in order to bring up the Python REPL.

Based on https://github.com/ntoll/microrepl by Nicholas H.Tollervey and the
contributors.
"""

import errno
import sys
from time import sleep
import traceback

import serial
import serial.tools.miniterm
from serial.tools.miniterm import Miniterm, key_description

BAUDRATE = 115200
PARITY = 'N'


if sys.version_info >= (3, 0):
    def character(b):
        return b.decode('latin1')
else:
    def character(b):
        return b


def connect_miniterm(port):
    try:
        ser = serial.Serial(port, BAUDRATE, parity=PARITY, rtscts=False,
                            xonxoff=False)
        return Miniterm(ser, echo=False)
    except serial.SerialException as e:
        if e.errno == errno.ENOENT:
            sys.stderr.write(
                "Device %r not found. Check your "
                "MicroPython device path settings.\n" % port)
        elif e.errno == errno.EBUSY:
            # Device is busy. Explain what to do.
            sys.stderr.write(
                "Found the device, but it is busy. "
                "Wait up to 20 seconds, or "
                "press the reset button on the "
                "back of the device next to the yellow light; "
                "then try again.\n"
            )
        elif e.errno == errno.EACCES:
            sys.stderr.write("Found the device, but could not connect.\n".format(port))
            sys.stderr.write('%s\n' % (str(e),))
            sys.stderr.write('On linux, try adding yourself to the "dialout" group:\n')
            sys.stderr.write('sudo usermod -a -G dialout <your-username>\n')
        else:
            # Try to be as helpful as possible.
            sys.stderr.write("Found the device, but could not connect via" +
                             " port %r: %s\n" % (port, e))
            sys.stderr.write("I'm not sure what to suggest. :-(\n")
        input("Press ENTER to continue")
        sys.exit(1)


def main():
    """
    The function that actually runs the REPL.
    """
    if len(sys.argv) not in range(2, 3):
        print("Usage: microrepl.py /path/to/device [--nointerrupt]")

    port = sys.argv[1]
    print('Device path', port)
    serial.tools.miniterm.EXITCHARCTER = character(b'\x1d')
    miniterm = connect_miniterm(port)
    # Emit some helpful information about the program and MicroPython.
    shortcut_message = 'Quit: {} | Stop program: Ctrl+C | Reset: Ctrl+D\n'
    help_message = 'Type \'help()\' (without the quotes) then press ENTER.\n'
    exit_char = key_description(serial.tools.miniterm.EXITCHARCTER)
    sys.stderr.write(shortcut_message.format(exit_char))
    sys.stderr.write(help_message)
    # Start everything.
    miniterm.set_rx_encoding('utf-8')
    miniterm.set_tx_encoding('utf-8')
    miniterm.start()
    sleep(0.5)
    if len(sys.argv) != 3 or sys.argv[2] != '--nointerrupt':
        miniterm.serial.write(b'\x03')  # Connecting stops the running program.
    try:
        miniterm.join(True)
    except KeyboardInterrupt:
        pass
    sys.stderr.write('\nEXIT - see you soon... :-)\n')


if __name__ == '__main__':
    try:
        main()
    except Exception:
        sys.stderr.write(traceback.format_exc())
        input("Press ENTER to continue")
        sys.exit(1)


================================================
FILE: scripts/microupload.py
================================================
# Copyright 2000-2017 JetBrains s.r.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Upload files and directories onto a MicroPython device.

Usage:
    microupload PORT PATH [-X PATH]... [options]

Options:
    -X --exclude=PATH       Path to exclude, may be repeated.
    -C --chdir=PATH         Change current directory to path.
    -v --verbose            Verbose output.
"""

import time
import sys
import os
from contextlib import suppress
from typing import List, Iterable, TypeVar, Sequence, Set

from docopt import docopt
from ampy.pyboard import Pyboard
from ampy.files import Files, DirectoryExistsError


__all__ = []

verbose = False
T = TypeVar('T')


def main(args: List[str]) -> None:
    global verbose
    opts = docopt(__doc__, argv=args)
    verbose = opts['--verbose']
    root = opts['PATH']

    chdir = opts['--chdir']
    if chdir:
        os.chdir(chdir)

    port = opts['PORT']
    print('Connecting to {}'.format(port), file=sys.stderr)
    board = Pyboard(port)
    files = Files(board)
    rel_root = os.path.relpath(root, os.getcwd())

    wait_for_board()

    if os.path.isdir(root):
        to_upload = [os.path.join(rel_root, x)
                     for x in list_files(root, opts['--exclude'])]
    else:
        to_upload = [rel_root]

    created_cache = set()
    for path in progress('Uploading files', to_upload):
        local_path = os.path.abspath(path)
        remote_path = os.path.normpath(path).replace(os.path.sep, '/')
        if verbose:
            print('\n{} -> {}'.format(local_path, remote_path),
                  file=sys.stderr, flush=True)
        remote_dir = os.path.dirname(path)
        if remote_dir:
            make_dirs(files, remote_dir, created_cache)
        with open(local_path, 'rb') as fd:
            files.put(remote_path, fd.read())

    print('Soft reboot', file=sys.stderr, flush=True)
    soft_reset(board)


def make_dirs(files: Files, path: str,
              created_cache: Set[str] = None) -> None:
    """Make all the directories the specified relative path consists of."""
    if path == '.':
        return
    if created_cache is None:
        created_cache = set()
    parent = os.path.dirname(path)
    if parent and parent not in created_cache:
        make_dirs(files, parent, created_cache)
    with suppress(DirectoryExistsError):
        posix_path = path.replace(os.path.sep, '/')
        files.mkdir(posix_path)
        created_cache.add(path)


def soft_reset(board: Pyboard) -> None:
    """Perform soft-reset of the ESP8266 board."""
    board.serial.write(b'\x03\x04')


def list_files(path: str, excluded: List[str]) -> Iterable[str]:
    """List relative file paths inside the given path."""
    excluded = {os.path.abspath(x) for x in excluded}
    for root, dirs, files in os.walk(path):
        abs_root = os.path.abspath(root)
        for d in list(dirs):
            if os.path.join(abs_root, d) in excluded or d.startswith('.'):
                dirs.remove(d)
        for f in files:
            if os.path.join(abs_root, f) not in excluded and not f.startswith('.'):
                yield os.path.relpath(os.path.join(root, f), path)


def wait_for_board() -> None:
    """Wait for some ESP8266 devices to become ready for REPL commands."""
    time.sleep(0.5)


def progress(msg: str, xs: Sequence[T]) -> Iterable[T]:
    """Show progress while iterating over a sequence."""
    size = len(xs)
    sys.stderr.write('\r{}: 0% (0/{})'.format(msg, size))
    sys.stderr.flush()
    for i, x in enumerate(xs, 1):
        yield x
        s = '{0}: {1}% ({2}/{3})'.format(msg, int(i * 100 / size), i, size)
        sys.stderr.write('\r' + s)
        sys.stderr.flush()
    sys.stderr.write('\n')
    sys.stderr.flush()


if __name__ == '__main__':
    main(sys.argv[1:])


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/actions/MicroPythonAction.kt
================================================
package com.jetbrains.micropython.actions

import com.intellij.facet.ui.ValidationResult
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.micropython.settings.firstMicroPythonFacet

abstract class MicroPythonAction : AnAction() {
    override fun update(e: AnActionEvent) {
        val project = e.project ?: return
        val facet = project.firstMicroPythonFacet
        if (facet != null) {
            e.presentation.isEnabledAndVisible = facet.checkValid() == ValidationResult.OK
        } else {
            e.presentation.isEnabledAndVisible = false
        }
    }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/actions/MicroPythonCommandAction.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.actions

import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.micropython.settings.MicroPythonFacet
import com.jetbrains.micropython.settings.firstMicroPythonFacet
import org.jetbrains.plugins.terminal.LocalTerminalDirectRunner
import org.jetbrains.plugins.terminal.TerminalToolWindowManager

/**
 * @author vlan
 */
abstract class MicroPythonCommandAction : MicroPythonAction() {
  override fun actionPerformed(e: AnActionEvent) {
    val project = e.project ?: return
    val facet = project.firstMicroPythonFacet ?: return
    val command = getCommand(facet) ?: return
    TerminalToolWindowManager.getInstance(project).createNewSession(object : LocalTerminalDirectRunner(project) {
      override fun getInitialCommand(envs: Map<String, String>): List<String> = command
    })
  }

  protected abstract fun getCommand(facet: MicroPythonFacet): List<String>?
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/actions/RemoveAllFilesFromDeviceAction.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.actions

import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.jetbrains.micropython.settings.MicroPythonFacet

/**
 * @author vlan
 */
class RemoveAllFilesFromDeviceAction : MicroPythonCommandAction() {
  override fun getCommand(facet: MicroPythonFacet): List<String>? {
    val pythonPath = facet.pythonPath ?: return null
    val devicePath = facet.getOrDetectDevicePathSynchronously() ?: return null
    return listOf(pythonPath, "${MicroPythonFacet.scriptsPath}/microcleanfs.py", devicePath)
  }

  override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/actions/RunMicroReplAction.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.actions

import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.micropython.repl.MicroPythonReplManager
import com.jetbrains.micropython.settings.firstMicroPythonFacet

class RunMicroReplAction : MicroPythonAction() {

  override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT

  override fun actionPerformed(e: AnActionEvent) {
    val project = e.project ?: return
    val editor = FileEditorManagerEx.getInstanceEx(project).selectedTextEditor ?: return

    /*
    Here we make our best to find out module which is relevant to the current event.
    There are two cases to consider:
    1) There is an open file present.
    2) No files are opened.
    */

    val virtualFile: VirtualFile? = FileDocumentManager.getInstance().getFile(editor.document)
    val module: Module? = if (virtualFile != null) {
      ModuleUtil.findModuleForFile(virtualFile, project)
    } else {
      project.firstMicroPythonFacet?.module
    }

    project.service<MicroPythonReplManager>().startOrRestartRepl()
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/Esp8266DeviceProvider.kt
================================================
package com.jetbrains.micropython.devices

import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.run.getMicroUploadCommand
import com.jetbrains.micropython.settings.MicroPythonTypeHints
import com.jetbrains.micropython.settings.MicroPythonUsbId
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyRequirement

/**
 * @author vlan
 */
class Esp8266DeviceProvider : MicroPythonDeviceProvider {
  override val persistentName: String
    get() = "ESP8266"

  override val documentationURL: String
    get() = "https://github.com/JetBrains/intellij-micropython/wiki/ESP8266"

  override fun checkUsbId(usbId: MicroPythonUsbId): Boolean = usbIds.contains(usbId)

  val usbIds: List<MicroPythonUsbId>
    get() = listOf(
      MicroPythonUsbId(0x1A86, 0x7523),
      MicroPythonUsbId(0x10C4, 0xEA60),
      MicroPythonUsbId(0x0403, 0x6001),
      MicroPythonUsbId(0x239A, 0x8038),  // Metro M4 Airlift Lite
    )

  override val typeHints: MicroPythonTypeHints by lazy {
    MicroPythonTypeHints(listOf("stdlib", "micropython", "esp8266"))
  }

  override fun getPackageRequirements(sdk: Sdk): List<PyRequirement> {
    val manager = PyPackageManager.getInstance(sdk)
    return manager.parseRequirements("""|pyserial>=3.5,<4.0
                                        |docopt>=0.6.2,<0.7
                                        |adafruit-ampy>=1.0.5,<1.1""".trimMargin())
  }

  override fun getRunCommandLineState(configuration: MicroPythonRunConfiguration,
                                      environment: ExecutionEnvironment): CommandLineState? {
    val module = configuration.module ?: return null
    val command = getMicroUploadCommand(configuration.path, module) ?: return null

    return object : CommandLineState(environment) {
      override fun startProcess() =
          OSProcessHandler(GeneralCommandLine(command))
    }
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/MicroBitDeviceProvider.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.devices

import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.settings.MicroPythonTypeHints
import com.jetbrains.micropython.settings.MicroPythonUsbId
import com.jetbrains.micropython.settings.microPythonFacet
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyRequirement

/**
 * @author vlan
 */
open class MicroBitDeviceProvider : MicroPythonDeviceProvider {
  override val persistentName: String
    get() = "Micro:bit"

  override val documentationURL: String
    get() = "https://github.com/JetBrains/intellij-micropython/wiki/BBC-Micro:bit"

  override fun checkUsbId(usbId: MicroPythonUsbId): Boolean = usbId == MicroPythonUsbId(0x0D28, 0x0204)

  override fun getPackageRequirements(sdk: Sdk): List<PyRequirement> {
    val manager = PyPackageManager.getInstance(sdk)
    return manager.parseRequirements("""|uflash>=1.2.4,<1.3
                                        |docopt>=0.6.2,<0.7
                                        |pyserial>=3.5,<4.0""".trimMargin())
  }

  override val typeHints: MicroPythonTypeHints by lazy {
    MicroPythonTypeHints(listOf("microbit"))
  }

  override val detectedModuleNames: Set<String>
    get() = linkedSetOf("microbit")

  override fun getRunCommandLineState(configuration: MicroPythonRunConfiguration,
                                      environment: ExecutionEnvironment): CommandLineState? {
    val pythonPath = configuration.module?.microPythonFacet?.pythonPath ?: return null
    return object : CommandLineState(environment) {
      override fun startProcess() =
          OSProcessHandler(GeneralCommandLine(pythonPath, "-m", "uflash", configuration.path))
    }
  }

  override val isDefault: Boolean
    get() = true
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/MicroBitV2DeviceProvider.kt
================================================
package com.jetbrains.micropython.devices

import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyRequirement

class MicroBitV2DeviceProvider : MicroBitDeviceProvider() {
    override val persistentName: String
        get() = "Micro:bit V2"

    override fun getPackageRequirements(sdk: Sdk): List<PyRequirement> {
        val manager = PyPackageManager.getInstance(sdk)
        return manager.parseRequirements("""|uflash>=2.0
                                            |docopt>=0.6.2,<0.7
                                            |pyserial>=3.5,<4.0""".trimMargin())
    }

    override val isDefault: Boolean
        get() = false
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/MicroPythonDeviceProvider.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.devices

import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.settings.MicroPythonTypeHints
import com.jetbrains.micropython.settings.MicroPythonUsbId
import com.jetbrains.python.packaging.PyRequirement

/**
 * @author vlan
 */
interface MicroPythonDeviceProvider {
  companion object {
    private val EP_NAME: ExtensionPointName<MicroPythonDeviceProvider> =
        ExtensionPointName.create("com.jetbrains.micropython.deviceProvider")

    val providers: List<MicroPythonDeviceProvider>
      get() = EP_NAME.extensionList

    val default: MicroPythonDeviceProvider
      get() = providers.first { it.isDefault }
  }

  val persistentName: String

  val documentationURL: String
  fun checkUsbId(usbId: MicroPythonUsbId): Boolean

  val presentableName: String
    get() = persistentName

  fun getPackageRequirements(sdk: Sdk): List<PyRequirement> = emptyList()

  val typeHints: MicroPythonTypeHints?
    get() = null

  val detectedModuleNames: Set<String>
    get() = emptySet()

  fun getRunCommandLineState(configuration: MicroPythonRunConfiguration,
                             environment: ExecutionEnvironment): CommandLineState? = null

  val isDefault: Boolean
    get() = false
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/PyboardDeviceProvider.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.devices

import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.run.getMicroUploadCommand
import com.jetbrains.micropython.settings.MicroPythonTypeHints
import com.jetbrains.micropython.settings.MicroPythonUsbId
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyRequirement

/**
 * @author stefanhoelzl
 */
class PyboardDeviceProvider : MicroPythonDeviceProvider {
  override val persistentName: String
    get() = "Pyboard"

  override val documentationURL: String
    get() = "https://github.com/JetBrains/intellij-micropython/wiki/Pyboard"

  override fun checkUsbId(usbId: MicroPythonUsbId): Boolean = usbId == MicroPythonUsbId(0xF055, 0x9800)

  override val typeHints: MicroPythonTypeHints by lazy {
    MicroPythonTypeHints(listOf("stdlib", "micropython", "pyboard"))
  }

  override fun getPackageRequirements(sdk: Sdk): List<PyRequirement> {
    val manager = PyPackageManager.getInstance(sdk)
    return manager.parseRequirements("""|pyserial>=3.5,<4.0
                                        |docopt>=0.6.2,<0.7
                                        |adafruit-ampy>=1.0.5,<1.1""".trimMargin())
  }

  override fun getRunCommandLineState(configuration: MicroPythonRunConfiguration,
                                      environment: ExecutionEnvironment): CommandLineState? {
    val module = configuration.module ?: return null
    val command = getMicroUploadCommand(configuration.path, module) ?: return null

    return object : CommandLineState(environment) {
      override fun startProcess() =
          OSProcessHandler(GeneralCommandLine(command))
    }
  }
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/devices/RPiPicoDeviceProvider.kt
================================================
package com.jetbrains.micropython.devices

import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.run.getMicroUploadCommand
import com.jetbrains.micropython.settings.MicroPythonTypeHints
import com.jetbrains.micropython.settings.MicroPythonUsbId
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyRequirement

/**
 * @author timsavage
 */
class RPiPicoDeviceProvider : MicroPythonDeviceProvider {
  override val persistentName: String
    get() = "Raspberry Pi Pico"

  override val documentationURL: String
    get() = "https://www.raspberrypi.com/documentation/microcontrollers/raspberry-pi-pico.html"

  /**
   * From https://github.com/raspberrypi/usb-pid :
   *
   * "The USB-IF have given Raspberry Pi permission to sub-license the USB product ID values for its vendor ID (0x2E8A)
   * since they are to be used on a common silicon component which will be used within a customer's product (the RP2040
   * silicon)."
   *
   * Consequently, most usb devices with the vendor id 0x2E8A are likely to be an RP2040, and therefore capable of
   * running MicroPython.
   */
  override fun checkUsbId(usbId: MicroPythonUsbId): Boolean =
          usbId.vendorId == 0x2E8A && ProductId.likelyToRunMicroPython(usbId.productId)

  object ProductId {
    private const val PICO_WITH_STANDARD_MICROPYTHON_FIRMWARE = 0x05

    /**
     * Raspberry Pi have allocated the productId range 0x1000 - 0x1fff for Commercial RP2040 devices.
     * See https://github.com/raspberrypi/usb-pid#assignment
     */
    private val COMMERCIAL_RANGE = 0x1000..0x1fff

    fun likelyToRunMicroPython(productId: Int): Boolean =
            productId == PICO_WITH_STANDARD_MICROPYTHON_FIRMWARE || productId in COMMERCIAL_RANGE
  }

  override val typeHints: MicroPythonTypeHints by lazy {
    MicroPythonTypeHints(listOf("stdlib", "micropython", "rpi_pico"))
  }

  override fun getPackageRequirements(sdk: Sdk): List<PyRequirement> {
    val manager = PyPackageManager.getInstance(sdk)
    return manager.parseRequirements("""|pyserial>=3.5,<4.0
                                        |docopt>=0.6.2,<0.7
                                        |adafruit-ampy>=1.0.5,<1.1""".trimMargin())
  }

  override fun getRunCommandLineState(configuration: MicroPythonRunConfiguration,
                                      environment: ExecutionEnvironment): CommandLineState? {
    val module = configuration.module ?: return null
    val command = getMicroUploadCommand(configuration.path, module) ?: return null

    return object : CommandLineState(environment) {
      override fun startProcess() =
          OSProcessHandler(GeneralCommandLine(command))
    }
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/inspections/MicroPythonRequirementsInspection.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.inspections

import com.intellij.codeInspection.*
import com.intellij.facet.ui.FacetConfigurationQuickFix
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.jetbrains.micropython.settings.microPythonFacet

/**
 * @author vlan
 */
class MicroPythonRequirementsInspection : LocalInspectionTool() {
  override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
    val module = ModuleUtilCore.findModuleForPsiElement(file) ?: return null
    val facet = module.microPythonFacet ?: return null
    val result = facet.checkValid()
    if (result.isOk) return null
    val facetFix: FacetConfigurationQuickFix? = result.quickFix
    val fix = if (facetFix != null) object : LocalQuickFix {
      override fun getFamilyName() = "Missing required MicroPython packages"

      override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
        facetFix.run(null)
      }
    } else null
    val fixes = if (fix != null) arrayOf(fix) else emptyArray()
    return arrayOf(manager.createProblemDescriptor(file, result.errorMessage, true, fixes,
                                                   ProblemHighlightType.GENERIC_ERROR_OR_WARNING))
  }
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/repl/MicroPythonReplManager.kt
================================================
package com.jetbrains.micropython.repl

import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.util.messages.Topic


interface MicroPythonReplControl {
    fun stopRepl()
    fun startOrRestartRepl(interrupt: Boolean = true)
}

@Service(Service.Level.PROJECT)
class MicroPythonReplManager(private val project: Project) : MicroPythonReplControl {
    override fun stopRepl() =
        project.messageBus.syncPublisher(MICROPYTHON_REPL_CONTROL).stopRepl()


    override fun startOrRestartRepl(interrupt: Boolean) =
        project.messageBus.syncPublisher(MICROPYTHON_REPL_CONTROL).startOrRestartRepl(interrupt)

}

val MICROPYTHON_REPL_CONTROL = Topic(MicroPythonReplControl::class.java)

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/repl/StopReplBeforeRunTask.kt
================================================
package com.jetbrains.micropython.repl

import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.util.Key
import com.jetbrains.micropython.run.MicroPythonRunConfiguration
import com.jetbrains.micropython.settings.MicroPythonFacetType

class StopReplBeforeRunTask : BeforeRunTask<StopReplBeforeRunTask>(StopReplBeforeRunTaskProvider.ID) {
    init {
        isEnabled = true
    }
}

class StopReplBeforeRunTaskProvider : BeforeRunTaskProvider<StopReplBeforeRunTask>() {
    companion object {
        val ID = Key.create<StopReplBeforeRunTask>("MicroPython.StopREPL.Before.Run")
    }

    override fun getId() = ID

    override fun getIcon() = MicroPythonFacetType.LOGO

    override fun getName() = "Stop MicroPython REPL"

    override fun createTask(runConfiguration: RunConfiguration): StopReplBeforeRunTask? {
        if (runConfiguration is MicroPythonRunConfiguration) {
            return StopReplBeforeRunTask()
        }

        return null
    }

    override fun executeTask(
        context: DataContext,
        configuration: RunConfiguration,
        environment: ExecutionEnvironment,
        task: StopReplBeforeRunTask
    ): Boolean {
        if (configuration is MicroPythonRunConfiguration) {
            environment.project.service<MicroPythonReplManager>().stopRepl()
        }
        return true
    }

}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/repl/ToolWindowReplTab.kt
================================================
package com.jetbrains.micropython.repl

import com.intellij.icons.AllIcons
import com.intellij.ide.ActivityTracker
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsContexts
import com.intellij.util.application
import com.jediterm.terminal.TtyConnector
import com.jetbrains.micropython.settings.MicroPythonDevicesConfiguration
import com.jetbrains.micropython.settings.MicroPythonFacet
import com.jetbrains.micropython.settings.microPythonFacet
import org.jetbrains.plugins.terminal.JBTerminalSystemSettingsProvider
import org.jetbrains.plugins.terminal.LocalTerminalDirectRunner
import org.jetbrains.plugins.terminal.ShellStartupOptions
import org.jetbrains.plugins.terminal.ShellTerminalWidget
import java.awt.BorderLayout
import java.util.concurrent.TimeUnit
import javax.swing.JPanel

class ToolWindowReplTab(val module: Module, parent: Disposable) : MicroPythonReplControl {
    private val deviceConfiguration = MicroPythonDevicesConfiguration.getInstance(module.project)
    val terminalWidget: ShellTerminalWidget

    init {
        val mySettingsProvider = JBTerminalSystemSettingsProvider()
        terminalWidget = ShellTerminalWidget(module.project, mySettingsProvider, parent)
        terminalWidget.isEnabled = false
        module.project.messageBus.connect(parent).subscribe(MICROPYTHON_REPL_CONTROL, this)

    }

    private fun connectWidgetTty(terminalWidget: ShellTerminalWidget, connector: TtyConnector) {
        terminalWidget.start(connector)
        val modalityState = ModalityState.stateForComponent(terminalWidget.component)

        ApplicationManager.getApplication().invokeLater(
            {
                try {
                    terminalWidget.component.revalidate()
                    terminalWidget.notifyStarted()
                } catch (e: RuntimeException) {
                    TODO("You can't cut back on error reporting! You will regret this!")
                }
            },
            modalityState
        )
    }

    fun createUI(): JPanel {
        val actionManager = ActionManager.getInstance()
        val toolbarActions = DefaultActionGroup().apply {
            add(replStartAction)
            add(replStopAction)
            add(clearReplOnLaunch)
        }
        val actionToolbar = actionManager.createActionToolbar("MicroPythonREPL", toolbarActions, false)
        actionToolbar.targetComponent = terminalWidget.component

        return JPanel().apply {
            layout = BorderLayout()

            add(actionToolbar.component, BorderLayout.WEST)
            add(terminalWidget.component)
        }
    }

    private val replStopAction = object : DumbAwareAction(
        "Stop", "Stop REPL session", AllIcons.Actions.Suspend
    ) {
        override fun update(e: AnActionEvent) {
            e.presentation.isEnabled = terminalWidget.isSessionRunning
        }

        override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT

        override fun actionPerformed(e: AnActionEvent) {
            stopRepl()
        }
    }

    private val replStartAction =
        object : DumbAwareAction("Restart", "Restart REPL session", AllIcons.Actions.Restart) {
            override fun update(e: AnActionEvent) {
                e.presentation.isEnabled = true
            }

            override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT

            override fun actionPerformed(e: AnActionEvent) =
                module.project.service<MicroPythonReplManager>().startOrRestartRepl()
        }

    private val clearReplOnLaunch = object : ToggleAction(
        "Clear Window On Start",
        "Clear REPL window on every start", AllIcons.Actions.GC
    ) {
        override fun isSelected(e: AnActionEvent): Boolean {
            return deviceConfiguration.clearReplOnLaunch
        }

        override fun setSelected(e: AnActionEvent, state: Boolean) {
            deviceConfiguration.clearReplOnLaunch = state
        }

        override fun getActionUpdateThread(): ActionUpdateThread {
            return ActionUpdateThread.EDT
        }
    }

    private fun onProcessCreationFailed(@NlsContexts.SystemNotificationText reason: String) {
        terminalWidget.terminal.nextLine()
        terminalWidget.terminal.writeCharacters(reason)
    }

    private fun interruptBanner() {
        application.invokeLater(
            {
                with(terminalWidget.terminal) {
                    nextLine()
                    writeCharacters("=== SESSION HAS BEEN INTERRUPTED ===")
                    nextLine()
                }
            },
            { module.isDisposed }
        )

    }
    override fun stopRepl() {
        interruptBanner()
        application.executeOnPooledThread {
            synchronized(this) {
                terminalWidget.processTtyConnector?.process?.destroy()
            }
        }
    }

    override fun startOrRestartRepl(interrupt: Boolean) {
        interruptBanner()
        application.executeOnPooledThread {
            synchronized(this) {
                terminalWidget.processTtyConnector?.process?.apply {
                    if (isAlive) destroy()
                    waitFor(10, TimeUnit.SECONDS)
                }
            }
            application.invokeLater(
                { startRepl(interrupt) },
                { module.project.isDisposed })
        }
    }

    private fun startRepl(interrupt: Boolean) {
        val facet = module.microPythonFacet ?: return
        val devicePath = facet.getOrDetectDevicePathSynchronously()

        if (facet.pythonPath == null) {
            onProcessCreationFailed("Valid Python interpreter is needed to start REPL!")
            return
        }

        if (devicePath == null) {
            onProcessCreationFailed("Device path is not specified, please check settings.")
            return
        }

        val initialShellCommand = mutableListOf(
            facet.pythonPath!!,
            "${MicroPythonFacet.scriptsPath}/microrepl.py",
            devicePath
        ).apply {
            if(!interrupt) add("--nointerrupt")
        }

        val terminalRunner = LocalTerminalDirectRunner(module.project)

        synchronized(this) {
            val terminalOptions = terminalRunner.configureStartupOptions(
                ShellStartupOptions.Builder()
                    .shellCommand(initialShellCommand)
                    .build()
            )

            val process = terminalRunner.createProcess(terminalOptions)
            val ttyConnector = terminalRunner.createTtyConnector(process)
            process.onExit().whenComplete { _, _ -> ActivityTracker.getInstance().inc() }
            if (deviceConfiguration.clearReplOnLaunch) {
                terminalWidget.terminalTextBuffer.clearHistory()
                terminalWidget.terminal.reset(true)
            } else {
                terminalWidget.terminal.nextLine()
            }
            connectWidgetTty(terminalWidget, ttyConnector)
            terminalWidget.isEnabled = true
        }
    }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/run/MicroPythonConfigurationType.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.run

import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.project.Project
import com.jetbrains.micropython.settings.MicroPythonFacetType
import com.jetbrains.python.run.PythonConfigurationFactoryBase
import javax.swing.Icon

/**
 * @author Mikhail Golubev
 */
class MicroPythonConfigurationType : ConfigurationType {
  companion object {
    fun getInstance(): MicroPythonConfigurationType =
        ConfigurationTypeUtil.findConfigurationType(MicroPythonConfigurationType::class.java)
  }
  
  internal val factory = object : PythonConfigurationFactoryBase(this) {
    override fun createTemplateConfiguration(project: Project): RunConfiguration =
        MicroPythonRunConfiguration(project, this)

    override fun getId(): String = "MicroPython"
  }

  override fun getIcon(): Icon = MicroPythonFacetType.LOGO

  override fun getConfigurationTypeDescription(): String = "MicroPython run configuration"

  override fun getId(): String = "MicroPythonConfigurationType"

  override fun getDisplayName(): String = "MicroPython"

  override fun getConfigurationFactories(): Array<ConfigurationFactory> = arrayOf(factory)
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfiguration.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.run

import com.intellij.execution.ExecutionResult
import com.intellij.execution.Executor
import com.intellij.execution.configuration.AbstractRunConfiguration
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.RunConfigurationWithSuppressedDefaultDebugAction
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.configurations.RuntimeConfigurationError
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ProgramRunner
import com.intellij.facet.ui.ValidationResult
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.util.PathUtil
import com.intellij.util.PlatformUtils
import com.jetbrains.micropython.repl.MicroPythonReplManager
import com.jetbrains.micropython.settings.MicroPythonProjectConfigurable
import com.jetbrains.micropython.settings.microPythonFacet
import org.jdom.Element

/**
 * @author Mikhail Golubev
 */

class RunStateWrapper(private val original: RunProfileState, val block: () -> Unit) : RunProfileState by original {
  override fun execute(executor: Executor?, runner: ProgramRunner<*>): ExecutionResult? {
    val result = original.execute(executor, runner)

    result?.processHandler?.addProcessListener(object : ProcessListener {
      override fun startNotified(event: ProcessEvent) {}

      override fun processTerminated(event: ProcessEvent) {
        if (event.exitCode == 0) {
          block()
        }
      }

      override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {}
    })

    return result
  }
}

class MicroPythonRunConfiguration(project: Project, factory: ConfigurationFactory) : AbstractRunConfiguration(project, factory), RunConfigurationWithSuppressedDefaultDebugAction {

  var path: String = ""
  var runReplOnSuccess: Boolean = false
  override fun getValidModules() =
          allModules.filter { it.microPythonFacet != null }.toMutableList()

  override fun getConfigurationEditor() = MicroPythonRunConfigurationEditor(this)

  override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? {
    val currentModule = environment.dataContext?.getData(LangDataKeys.MODULE) ?: module
    val state = currentModule?.microPythonFacet?.configuration?.deviceProvider?.getRunCommandLineState(this, environment)
//    ComponentManagerImpl
    if (runReplOnSuccess && state != null) {
      return RunStateWrapper(state) {
        ApplicationManager.getApplication().invokeLater {
          project.service<MicroPythonReplManager>().startOrRestartRepl(false)
          ToolWindowManager.getInstance(project).getToolWindow("MicroPython")?.show()
        }
      }
    }

    return state
  }

  override fun checkConfiguration() {
    super.checkConfiguration()
    if (StringUtil.isEmpty(path)) {
      throw RuntimeConfigurationError("Path is not specified")
    }
    val m = module ?: throw RuntimeConfigurationError("Module for path is not found")
    val showSettings = Runnable {
      when {
        PlatformUtils.isPyCharm() ->
          ShowSettingsUtil.getInstance().showSettingsDialog(project, MicroPythonProjectConfigurable::class.java)
        PlatformUtils.isIntelliJ() ->
          ProjectSettingsService.getInstance(project).openModuleSettings(module)
        else ->
          ShowSettingsUtil.getInstance().showSettingsDialog(project)
      }
    }
    val facet = m.microPythonFacet ?: throw RuntimeConfigurationError(
            "MicroPython support is not enabled for selected module in IDE settings",
            showSettings
    )
    val validationResult = facet.checkValid()
    if (validationResult != ValidationResult.OK) {
      val runQuickFix = Runnable {
        validationResult.quickFix.run(null)
      }
      throw RuntimeConfigurationError(validationResult.errorMessage, runQuickFix)
    }
    facet.pythonPath ?: throw RuntimeConfigurationError("Python interpreter is not found")
    if (!facet.autoDetectDevicePath && facet.devicePath == null) {
      throw RuntimeConfigurationError("Device path is not specified in IDE settings", showSettings)
    }
  }

  override fun suggestedName() = "Flash ${PathUtil.getFileName(path)}"

  override fun writeExternal(element: Element) {
    super.writeExternal(element)
    element.setAttribute("path", path)
    element.setAttribute("runReplOnSuccess", if (runReplOnSuccess) "yes" else "no")
  }

  override fun readExternal(element: Element) {
    super.readExternal(element)
    configurationModule.readExternal(element)
    element.getAttributeValue("path")?.let {
      path = it
    }
    element.getAttributeValue("runReplOnSuccess")?.let {
      runReplOnSuccess = it == "yes"
    }
  }

  val module: Module?
    get() {
      val file = StandardFileSystems.local().findFileByPath(path) ?: return null
      return ModuleUtil.findModuleForFile(file, project)
    }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfigurationEditor.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.run

import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.TextComponentAccessor
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.ui.components.CheckBox
import com.intellij.util.ui.FormBuilder
import javax.swing.JComponent

class MicroPythonRunConfigurationEditor(config: MicroPythonRunConfiguration) : SettingsEditor<MicroPythonRunConfiguration>() {
  private val pathField = TextFieldWithBrowseButton()
  private val runReplOnSuccess = CheckBox("Open MicroPython REPL on success", selected = true)

  init {
    val descriptor = FileChooserDescriptor(true, true, false, false, false, false)
    val listener = ComponentWithBrowseButton.BrowseFolderActionListener(
        "Select Path", "",
        pathField,
        config.project, descriptor,
        TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT
    )
    pathField.addActionListener(listener)
  }

  override fun createEditor(): JComponent =
      FormBuilder.createFormBuilder()
          .addLabeledComponent("Path:", pathField)
          .addComponent(runReplOnSuccess)
          .panel

  override fun applyEditorTo(s: MicroPythonRunConfiguration) {
    s.path = pathField.text
    s.runReplOnSuccess = runReplOnSuccess.isSelected
  }

  override fun resetEditorFrom(s: MicroPythonRunConfiguration) {
    pathField.text = s.path
    runReplOnSuccess.isSelected = s.runReplOnSuccess
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfigurationProducer.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.run

import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.actions.LazyRunConfigurationProducer
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.facet.FacetManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightVirtualFile
import com.jetbrains.micropython.settings.MicroPythonFacetType
import com.jetbrains.python.run.AbstractPythonRunConfiguration

/**
 * @author Mikhail Golubev
 */
class MicroPythonRunConfigurationProducer : LazyRunConfigurationProducer<MicroPythonRunConfiguration>() {
  override fun getConfigurationFactory(): ConfigurationFactory {
    return MicroPythonConfigurationType.getInstance().factory
  }

  override fun isConfigurationFromContext(configuration: MicroPythonRunConfiguration, context: ConfigurationContext): Boolean {
    val file = context.location?.virtualFile ?: return false
    if (!facetEnabledForElement(file, context.project)) return false
    if (file is LightVirtualFile) return false
    return configuration.path == file.path
  }

  override fun setupConfigurationFromContext(configuration: MicroPythonRunConfiguration,
                                             context: ConfigurationContext,
                                             sourceElement: Ref<PsiElement>): Boolean {
    val file = context.location?.virtualFile ?: return false
    if (!facetEnabledForElement(file, context.project)) return false
    configuration.path = file.path
    configuration.setGeneratedName()
    configuration.setModule(ModuleUtilCore.findModuleForFile(file, context.project))
    return true
  }

  private fun facetEnabledForElement(virtualFile: VirtualFile, project: Project): Boolean {
    val module = ModuleUtilCore.findModuleForFile(virtualFile, project) ?: return false
    return FacetManager.getInstance(module)?.getFacetByType(MicroPythonFacetType.ID) != null
  }

  override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext) =
      other.configuration is AbstractPythonRunConfiguration<*>
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/run/MicroUpload.kt
================================================
package com.jetbrains.micropython.run

import com.intellij.openapi.module.Module
import com.intellij.openapi.project.guessModuleDir
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.micropython.settings.MicroPythonFacet
import com.jetbrains.micropython.settings.microPythonFacet

fun getMicroUploadCommand(path: String, module: Module): List<String>? {
  val facet = module.microPythonFacet ?: return null
  val pythonPath = facet.pythonPath ?: return null
  val devicePath = facet.getOrDetectDevicePathSynchronously() ?: return null
  val file = StandardFileSystems.local().findFileByPath(path) ?: return null
  val rootDir = getClosestRoot(file, module) ?: return null
  val excludeRoots = ModuleRootManager.getInstance(module).excludeRoots
  val excludes = excludeRoots
      .asSequence()
      .filter { VfsUtil.isAncestor(file, it, false) }
      .map { VfsUtilCore.getRelativePath(it, rootDir) }
      .filterNotNull()
      .map { listOf("-X", it) }
      .flatten()
      .toList()
  return listOf(pythonPath, "${MicroPythonFacet.scriptsPath}/microupload.py", "-C", rootDir.path) +
      excludes +
      listOf("-v", devicePath, path)
}

private fun getClosestRoot(file: VirtualFile, module: Module): VirtualFile? {
  val roots = mutableSetOf<VirtualFile>().apply {
    val rootManager = module.rootManager
    addAll(rootManager.contentRoots)
    addAll(rootManager.sourceRoots)
  }
  var parent: VirtualFile? = file
  while (parent != null) {
    if (parent in roots) {
      break
    }
    parent = parent.parent
  }
  return parent ?: module.guessModuleDir()
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonDevicesConfiguration.kt
================================================
package com.jetbrains.micropython.settings

import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.XmlSerializerUtil
import com.intellij.util.xmlb.annotations.Attribute

/**
 * @author vlan
 */
@State(name = "MicroPythonDevices", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class MicroPythonDevicesConfiguration : PersistentStateComponent<MicroPythonDevicesConfiguration> {

  companion object {
    fun getInstance(project: Project): MicroPythonDevicesConfiguration =
      project.getService(MicroPythonDevicesConfiguration::class.java)
  }

  // Currently, the device path is stored per project, not per module
  @Attribute var devicePath: String = ""

  @Attribute var autoDetectDevicePath: Boolean = true

  @Attribute var clearReplOnLaunch: Boolean = true

  override fun getState() = this

  override fun loadState(state: MicroPythonDevicesConfiguration) {
    XmlSerializerUtil.copyBean(state, this)
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacet.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.facet.Facet
import com.intellij.facet.FacetManager
import com.intellij.facet.FacetType
import com.intellij.facet.ui.FacetConfigurationQuickFix
import com.intellij.facet.ui.ValidationResult
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.util.text.nullize
import com.jetbrains.micropython.devices.MicroPythonDeviceProvider
import com.jetbrains.python.facet.FacetLibraryConfigurator
import com.jetbrains.python.facet.LibraryContributingFacet
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.PyPackageManagerUI
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.PySdkUtil
import com.jetbrains.python.sdk.PythonSdkUtil
import javax.swing.JComponent

/**
 * @author vlan
 */
class MicroPythonFacet(facetType: FacetType<out Facet<*>, *>, module: Module, name: String,
                       configuration: MicroPythonFacetConfiguration, underlyingFacet: Facet<*>?)
  : LibraryContributingFacet<MicroPythonFacetConfiguration>(facetType, module, name, configuration, underlyingFacet) {

  companion object {
    private const val PLUGIN_ID = "intellij-micropython"

    val scriptsPath: String
      get() = "${pluginDescriptor.pluginPath}/scripts"

    private val pluginDescriptor: IdeaPluginDescriptor
      get() = PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID)) ?:
          throw RuntimeException("The $PLUGIN_ID plugin cannot find itself")
  }

  override fun initFacet() {
    updateLibrary()
  }

  override fun updateLibrary() {
    val plugin = pluginDescriptor
    val boardHintsPaths = configuration.deviceProvider.typeHints?.paths?.map {
      "${plugin.pluginPath}/typehints/$it"
    } ?: emptyList()
    ApplicationManager.getApplication().invokeLater {
      FacetLibraryConfigurator.attachPythonLibrary(module, null, "MicroPython", boardHintsPaths)
      removeLegacyLibraries()
    }
  }

  override fun removeLibrary() {
    FacetLibraryConfigurator.detachPythonLibrary(module, "MicroPython")
  }

  fun checkValid(): ValidationResult {
    val provider = configuration.deviceProvider
    val sdk = PythonSdkUtil.findPythonSdk(module)
    if (sdk == null || PythonSdkUtil.isInvalid(sdk) || PySdkUtil.getLanguageLevelForSdk(sdk).isOlderThan(LanguageLevel.PYTHON35)) {
      return ValidationResult("${provider.presentableName} support requires valid Python 3.5+ SDK")
    }
    val packageManager = PyPackageManager.getInstance(sdk)
    val packages = packageManager.packages ?: return ValidationResult.OK
    val requirements = provider.getPackageRequirements(sdk).filter { it.match(packages) == null }.toList()
    if (requirements.isNotEmpty()) {
      val requirementsText = requirements.joinToString(", ") {
        it.presentableText
      }
      return ValidationResult("Packages required for ${provider.presentableName} support not found: $requirementsText",
                              object : FacetConfigurationQuickFix("Install Requirements") {
        override fun run(place: JComponent?) {
          PyPackageManagerUI(module.project, sdk, null).install(requirements, emptyList())
        }
      })
    }
    return ValidationResult.OK
  }

  private fun findSerialPorts(deviceProvider: MicroPythonDeviceProvider, indicator: ProgressIndicator): List<String> {
    val timeout = 1_000
    val pythonPath = pythonPath ?: return emptyList()
    val command = listOf(pythonPath, "$scriptsPath/findusb.py")
    val process = CapturingProcessHandler(GeneralCommandLine(command))
    val output = process.runProcessWithProgressIndicator(indicator, timeout)
    return when {
      output.isCancelled -> emptyList()
      output.isTimeout -> emptyList()
      output.exitCode != 0 -> emptyList()
      else -> {
        output.stdoutLines.associate {
          Pair(MicroPythonUsbId.parse(it.substringBefore(' ')), it.substringAfter(' '))
        }.filterKeys { deviceProvider.checkUsbId(it) }.values.toList()
      }
    }
  }

  val pythonPath: String?
    get() = PythonSdkUtil.findPythonSdk(module)?.homePath

  var devicePath: String?
    get() = MicroPythonDevicesConfiguration.getInstance(module.project).devicePath.nullize(true)
    set(value) {
      MicroPythonDevicesConfiguration.getInstance(module.project).devicePath = value ?: ""
    }

  var autoDetectDevicePath: Boolean
    get() = MicroPythonDevicesConfiguration.getInstance(module.project).autoDetectDevicePath
    set(value) {
      MicroPythonDevicesConfiguration.getInstance(module.project).autoDetectDevicePath = value
    }

  fun getOrDetectDevicePathSynchronously(): String? =
      if (autoDetectDevicePath)
        detectDevicePathSynchronously(configuration.deviceProvider)
      else
        devicePath

  fun detectDevicePathSynchronously(deviceProvider: MicroPythonDeviceProvider): String? {
    ApplicationManager.getApplication().assertIsDispatchThread()

    var detectedDevicePath: String? = null
    val deviceProviderName = deviceProvider.presentableName
    val progress = ProgressManager.getInstance()

    progress.runProcessWithProgressSynchronously({
      progress.progressIndicator.text = "Detecting connected $deviceProviderName devices..."
      val detected = findSerialPorts(deviceProvider, progress.progressIndicator).firstOrNull()
      ApplicationManager.getApplication().invokeLater {
        if (detected == null) {
          Messages.showErrorDialog(module.project,
              """Possible solutions:
                |
                |- Check if your device is connected to your computer
                |- Specify the device path manually in the IDE settings for MicroPython""".trimMargin(),
              "No $deviceProviderName Devices Detected")
        }
        detectedDevicePath = detected
      }
    }, "Detecting MicroPython devices", true, module.project, null)
    return detectedDevicePath
  }

  private fun removeLegacyLibraries() {
    FacetLibraryConfigurator.detachPythonLibrary(module, "Micro:bit")
  }
}

val Module.microPythonFacet: MicroPythonFacet?
  get() = FacetManager.getInstance(this).getFacetByType(MicroPythonFacetType.ID)

val Project.firstMicroPythonFacet: MicroPythonFacet?
  get() = ModuleManager.getInstance(this).modules
      .asSequence()
      .map { it.microPythonFacet }
      .firstOrNull()


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetConfiguration.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.facet.FacetConfiguration
import com.intellij.facet.ui.FacetEditorContext
import com.intellij.facet.ui.FacetEditorTab
import com.intellij.facet.ui.FacetEditorValidator
import com.intellij.facet.ui.FacetValidatorsManager
import com.jetbrains.micropython.devices.MicroPythonDeviceProvider
import org.jdom.Element

/**
 * @author vlan
 */
class MicroPythonFacetConfiguration : FacetConfiguration {
  var deviceProvider = MicroPythonDeviceProvider.default

  override fun createEditorTabs(editorContext: FacetEditorContext, validatorsManager: FacetValidatorsManager): Array<FacetEditorTab> {
    val facet = editorContext.facet as MicroPythonFacet
    validatorsManager.registerValidator(object: FacetEditorValidator() {
      override fun check() = facet.checkValid()
    })
    return arrayOf(MicroPythonFacetEditorTab(this, facet))
  }

  @Deprecated("Deprecated in Java")
  override fun readExternal(element: Element?) {
    val deviceName = element?.getChild("device")?.getAttribute("name")?.value
    val device = MicroPythonDeviceProvider.providers.firstOrNull { it.persistentName == deviceName }
    deviceProvider = device ?: MicroPythonDeviceProvider.default
  }

  @Deprecated("Deprecated in Java")
  override fun writeExternal(element: Element?) {
    val deviceElement = Element("device")
    deviceElement.setAttribute("name", deviceProvider.persistentName)
    element?.addContent(deviceElement)
  }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetDetector.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.framework.detection.FacetBasedFrameworkDetector
import com.intellij.framework.detection.FileContentPattern
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.patterns.PatternCondition
import com.intellij.util.ProcessingContext
import com.intellij.util.indexing.FileContent
import com.jetbrains.micropython.devices.MicroPythonDeviceProvider
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFromImportStatement
import com.jetbrains.python.psi.PyImportStatement

/**
 * @author Mikhail Golubev
 */
class MicroPythonFacetDetector : FacetBasedFrameworkDetector<MicroPythonFacet, MicroPythonFacetConfiguration>("MicroPython") {
  override fun getFacetType() = MicroPythonFacetType.getInstance()

  override fun createSuitableFilePattern() =
      FileContentPattern.fileContent().with(object : PatternCondition<FileContent>("Contains MicroPython imports") {
        override fun accepts(fileContent: FileContent, context: ProcessingContext?): Boolean {
          val fileIndex = ProjectRootManager.getInstance(fileContent.project).fileIndex
          if (!fileIndex.isInContent(fileContent.file) || fileIndex.isInLibraryClasses(fileContent.file)) {
            return false
          }
          val detected = MicroPythonDeviceProvider.providers
              .asSequence()
              .flatMap { it.detectedModuleNames.asSequence() }
              .toSet()
          return when (val psiFile = fileContent.psiFile) {
            is PyFile -> {
              return psiFile.importBlock.any { imp ->
                when (imp) {
                  is PyFromImportStatement -> imp.importSourceQName?.firstComponent in detected
                  is PyImportStatement -> imp.importElements.any { it.importedQName?.firstComponent in detected }
                  else -> false
                }
              }
            }
            else -> false
          }
        }
      })

  override fun getFileType(): FileType = PythonFileType.INSTANCE
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetEditorTab.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.facet.ui.FacetEditorTab
import javax.swing.JComponent

/**
 * @author vlan
 */
class MicroPythonFacetEditorTab(val configuration: MicroPythonFacetConfiguration,
                                private val facet: MicroPythonFacet) : FacetEditorTab() {
  private val panel: MicroPythonSettingsPanel by lazy {
    MicroPythonSettingsPanel(facet.module)
  }

  override fun isModified(): Boolean = panel.isModified(configuration, facet)

  override fun getDisplayName(): String = panel.getDisplayName()

  override fun createComponent(): JComponent = panel

  override fun apply() {
    panel.apply(configuration, facet)
    facet.updateLibrary()
  }

  override fun reset() {
    panel.reset(configuration, facet)
  }
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetType.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.facet.Facet
import com.intellij.facet.FacetType
import com.intellij.facet.FacetTypeId
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.util.IconLoader
import com.jetbrains.python.PythonModuleTypeBase
import javax.swing.Icon

/**
 * @author vlan
 */
class MicroPythonFacetType : FacetType<MicroPythonFacet, MicroPythonFacetConfiguration>(ID, STRING_ID, PRESENTABLE_NAME) {

  companion object {
    const val STRING_ID = "MicroPython"
    const val PRESENTABLE_NAME = "MicroPython"
    val ID = FacetTypeId<MicroPythonFacet>(STRING_ID)
    val LOGO = IconLoader.getIcon("/icons/micropython.svg", MicroPythonFacetType::class.java)

    fun getInstance() = findInstance(MicroPythonFacetType::class.java)!!
  }

  override fun createDefaultConfiguration() = MicroPythonFacetConfiguration()

  override fun createFacet(module: Module, name: String, configuration: MicroPythonFacetConfiguration,
                           underlyingFacet: Facet<*>?) =
      MicroPythonFacet(this, module, name, configuration, underlyingFacet)

  override fun isSuitableModuleType(moduleType: ModuleType<*>?) = moduleType is PythonModuleTypeBase

  override fun getIcon(): Icon = LOGO
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonModuleConfigurable.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.facet.FacetManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.options.Configurable
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JPanel

/**
 * @author vlan
 */
class MicroPythonModuleConfigurable(private val module: Module) : Configurable {
  private val panel: MicroPythonSettingsPanel by lazy {
    MicroPythonSettingsPanel(module)
  }

  private val enabledCheckbox by lazy {
    val checkBox = JCheckBox("Enable MicroPython support")
    checkBox.addActionListener {
      update()
    }
    checkBox
  }

  override fun isModified(): Boolean {
    val facet = module.microPythonFacet
    val enabled = facet != null

    if (enabledCheckbox.isSelected != enabled) return true
    val c = facet?.configuration ?: return false
    return panel.isModified(c, facet)
  }

  override fun getDisplayName() = "MicroPython"

  override fun apply() {
    val facet = module.microPythonFacet
    val application = ApplicationManager.getApplication()
    val facetManager = FacetManager.getInstance(module)

    if (enabledCheckbox.isSelected) {
      if (facet != null) {
        panel.apply(facet.configuration, facet)
        FacetManager.getInstance(module).facetConfigurationChanged(facet)
        facet.updateLibrary()
      }
      else {
        val facetType = MicroPythonFacetType.getInstance()
        val newFacet = facetManager.createFacet(facetType, facetType.defaultFacetName, null)
        panel.apply(newFacet.configuration, newFacet)

        val facetModel = facetManager.createModifiableModel()
        facetModel.addFacet(newFacet)
        application.runWriteAction { facetModel.commit() }
      }
    }
    else if (facet != null) {
      val facetModel = facetManager.createModifiableModel()
      facetModel.removeFacet(facet)
      application.runWriteAction { facetModel.commit() }
    }
  }

  override fun createComponent(): JComponent {
    val mainPanel = JPanel()
    with(mainPanel) {
      layout = BorderLayout()
      add(enabledCheckbox, BorderLayout.NORTH)
      add(panel, BorderLayout.CENTER)
    }
    update()
    return mainPanel
  }

  override fun reset() {
    val facet = module.microPythonFacet
    val enabled = facet != null

    enabledCheckbox.isSelected = enabled
    panel.isEnabled = enabled
    update()

    if (facet != null) {
      panel.reset(facet.configuration, facet)
    }
  }

  private fun update() {
    UIUtil.setEnabled(panel, enabledCheckbox.isSelected, true)
  }
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonProjectConfigurable.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.application.options.ModuleAwareProjectConfigurable
import com.intellij.openapi.module.Module
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project

/**
 * @author vlan
 */
class MicroPythonProjectConfigurable(project: Project)
  : ModuleAwareProjectConfigurable<Configurable>(project, "MicroPython", null) {

  override fun createModuleConfigurable(module: Module?) = MicroPythonModuleConfigurable(module!!)
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonSettingsPanel.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

import com.intellij.ide.BrowserUtil
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.CheckBox
import com.intellij.util.text.nullize
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import com.jetbrains.micropython.devices.MicroPythonDeviceProvider
import java.awt.BorderLayout
import javax.swing.JButton
import javax.swing.JList
import javax.swing.JPanel

/**
 * @author vlan
 */
class MicroPythonSettingsPanel(private val module: Module) : JPanel() {
  private val deviceTypeCombo = ComboBox(MicroPythonDeviceProvider.providers.toTypedArray())
  private var docsHyperlink = object : ActionLink() {
    var url = ""

    init {
      addActionListener {
        BrowserUtil.browse(url)
      }
    }
  }
  private val devicePath = TextFieldWithBrowseButton()
  private val autoDetectDevicePath = CheckBox("Auto-detect device path").apply {
    addActionListener {
      update()
    }
  }

  private val devicePathPanel: JPanel by lazy {
    FormBuilder.createFormBuilder()
        .addLabeledComponent("Device path:", JPanel(BorderLayout()).apply {
          add(devicePath, BorderLayout.CENTER)
          add(JButton("Detect").apply {
            addActionListener {
              devicePath.text = module.microPythonFacet?.detectDevicePathSynchronously(selectedProvider) ?: ""
            }
          }, BorderLayout.EAST)
        })
        .panel
  }

  init {
    layout = BorderLayout()
    border = IdeBorderFactory.createEmptyBorder(UIUtil.PANEL_SMALL_INSETS)

    val deviceContentPanel = FormBuilder.createFormBuilder()
        .addLabeledComponent("Device type:", deviceTypeCombo)
        .addComponent(autoDetectDevicePath)
        .addComponent(devicePathPanel)
        .addComponent(docsHyperlink)
        .panel

    add(deviceContentPanel, BorderLayout.NORTH)

    deviceTypeCombo.apply {
      renderer = object: SimpleListCellRenderer<MicroPythonDeviceProvider>() {
        override fun customize(list: JList<out MicroPythonDeviceProvider>, value: MicroPythonDeviceProvider?,
                               index: Int, selected: Boolean, hasFocus: Boolean) {
          text = value?.presentableName ?: return
        }
      }
      addActionListener {
        docsHyperlink.apply {
          url = selectedProvider.documentationURL
          text = "Learn more about setting up ${selectedProvider.presentableName} devices"
          repaint()
        }
      }
    }

    devicePath.apply {
      val descriptor = FileChooserDescriptor(true, false, false, false, false, false)
      addBrowseFolderListener("My Title", null, module.project, descriptor)
    }

    update()
  }

  fun isModified(configuration: MicroPythonFacetConfiguration, facet: MicroPythonFacet): Boolean =
      deviceTypeCombo.selectedItem != configuration.deviceProvider
          || devicePath.text.nullize(true) != facet.devicePath
          || autoDetectDevicePath.isSelected != facet.autoDetectDevicePath

  fun getDisplayName(): String = "MicroPython"

  fun apply(configuration: MicroPythonFacetConfiguration, facet: MicroPythonFacet) {
    configuration.deviceProvider = selectedProvider
    facet.devicePath = devicePath.text.nullize(true)
    facet.autoDetectDevicePath = autoDetectDevicePath.isSelected
  }

  fun reset(configuration: MicroPythonFacetConfiguration, facet: MicroPythonFacet) {
    deviceTypeCombo.selectedItem = configuration.deviceProvider
    devicePath.text = facet.devicePath ?: ""
    autoDetectDevicePath.isSelected = facet.autoDetectDevicePath
    update()
  }

  private fun update() {
    UIUtil.setEnabled(devicePathPanel, !autoDetectDevicePath.isSelected, true)
  }

  private val selectedProvider: MicroPythonDeviceProvider
    get() = deviceTypeCombo.selectedItem as MicroPythonDeviceProvider
}

================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonTypeHints.kt
================================================
/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jetbrains.micropython.settings

/**
 * @author vlan
 */
data class MicroPythonTypeHints(val paths: List<String>)


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonUsbId.kt
================================================
package com.jetbrains.micropython.settings

/**
 * @author vlan
 */
data class MicroPythonUsbId(val vendorId: Int, val productId: Int) {
    companion object {
        fun parse(vendorAndProductId: String): MicroPythonUsbId {
            val ints = vendorAndProductId.split(':').map { Integer.decode(it) }
            return MicroPythonUsbId(ints[0], ints[1])
        }
    }
}


================================================
FILE: src/main/kotlin/com/jetbrains/micropython/ui/MicroPythonToolWindowFactory.kt
================================================
package com.jetbrains.micropython.ui

import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import com.jetbrains.micropython.repl.MicroPythonReplManager
import com.jetbrains.micropython.repl.ToolWindowReplTab
import com.jetbrains.micropython.settings.firstMicroPythonFacet

class MicroPythonToolWindowFactory : ToolWindowFactory, DumbAware {
    override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
        val contentFactory = ContentFactory.getInstance()
        val terminalContent = contentFactory.createContent(null, "REPL", false)

        project.firstMicroPythonFacet?.let {
            terminalContent.component = ToolWindowReplTab(it.module, terminalContent).createUI()
            toolWindow.contentManager.addContent(terminalContent)
            project.service<MicroPythonReplManager>().startOrRestartRepl()
        }
    }

}


================================================
FILE: src/main/resources/META-INF/plugin.xml
================================================
<idea-plugin url="https://github.com/JetBrains/intellij-micropython">
  <name>MicroPython</name>
  <id>intellij-micropython</id>
  <change-notes><![CDATA[
      <p>See <a href="https://github.com/JetBrains/intellij-micropython/blob/master/CHANGES.md">CHANGES.md</a> on GitHub.</p>
    ]]></change-notes>
  <description><![CDATA[
      <p>Support for MicroPython devices in PyCharm and IntelliJ.</p>
      <br/>
      <p>Features:</p>
      <br/>
      <ul>
        <li>Code completion and docs for some MicroPython-specific modules</li>
        <li>Flash a Python file or directory to a device</li>
        <li>Run REPL on a device</li>
      </ul>
      <br/>
      <p>Currently the plugin supports ESP8266, Pyboard, Micro:bit, and Raspberry Pi Pico devices. Your feedback and contributions
        are welcome! See <a href="https://github.com/JetBrains/intellij-micropython">the project page</a> on GitHub.</p>
    ]]></description>
  <version>SNAPSHOT</version>
  <vendor>JetBrains</vendor>

  <depends>com.intellij.modules.lang</depends>
  <depends>com.intellij.modules.python</depends>
  <depends>org.jetbrains.plugins.terminal</depends>

  <idea-version since-build="242" until-build="242.*"/>

  <extensionPoints>
    <extensionPoint qualifiedName="com.jetbrains.micropython.deviceProvider"
                    interface="com.jetbrains.micropython.devices.MicroPythonDeviceProvider"/>
  </extensionPoints>

  <extensions defaultExtensionNs="com.intellij">
    <facetType implementation="com.jetbrains.micropython.settings.MicroPythonFacetType"/>
    <framework.detector implementation="com.jetbrains.micropython.settings.MicroPythonFacetDetector"/>
    <configurationType implementation="com.jetbrains.micropython.run.MicroPythonConfigurationType"/>
    <runConfigurationProducer implementation="com.jetbrains.micropython.run.MicroPythonRunConfigurationProducer"/>
    <projectConfigurable groupId="language"
                         id="com.jetbrains.micropython.configurable"
                         displayName="MicroPython"
                         instance="com.jetbrains.micropython.settings.MicroPythonProjectConfigurable"/>
    <projectService serviceImplementation="com.jetbrains.micropython.settings.MicroPythonDevicesConfiguration"/>
    <stepsBeforeRunProvider implementation="com.jetbrains.micropython.repl.StopReplBeforeRunTaskProvider"/>
    <localInspection language="Python"
                     displayName="MicroPython requirements inspection"
                     groupName="MicroPython"
                     enabledByDefault="true"
                     implementationClass="com.jetbrains.micropython.inspections.MicroPythonRequirementsInspection"/>
  </extensions>

  <extensions defaultExtensionNs="com.jetbrains.micropython">
    <deviceProvider implementation="com.jetbrains.micropython.devices.MicroBitDeviceProvider"/>
    <deviceProvider implementation="com.jetbrains.micropython.devices.MicroBitV2DeviceProvider"/>
    <deviceProvider implementation="com.jetbrains.micropython.devices.Esp8266DeviceProvider"/>
    <deviceProvider implementation="com.jetbrains.micropython.devices.PyboardDeviceProvider"/>
    <deviceProvider implementation="com.jetbrains.micropython.devices.RPiPicoDeviceProvider"/>
  </extensions>

  <extensions defaultExtensionNs="com.intellij">
    <facet.toolWindow id="MicroPython" anchor="bottom" factoryClass="com.jetbrains.micropython.ui.MicroPythonToolWindowFactory"
                      secondary="false" icon="/icons/micropython_tw.svg"
                      facetIdList="MicroPython"/>
  </extensions>

  <actions>
    <group text="MicroPython" id="micropython" popup="true" icon="/icons/micropython.svg">
      <add-to-group group-id="ToolsMenu"/>
      <action class="com.jetbrains.micropython.actions.RunMicroReplAction" id="RunMicroReplAction"
              text="MicroPython REPL"
              description="Run MicroPython REPL in a tool window"
              icon="AllIcons.Actions.Run_anything">
        <keyboard-shortcut first-keystroke="control shift R" keymap="Mac OS X 10.5+" />
        <keyboard-shortcut first-keystroke="alt shift R" keymap="$default" />
      </action>
      <action class="com.jetbrains.micropython.actions.RemoveAllFilesFromDeviceAction" id="RemoveAllFilesFromDeviceAction"
              text="Remove All Files from MicroPython Device"/>
    </group>
  </actions>
</idea-plugin>


================================================
FILE: src/main/resources/inspectionDescriptions/MicroPythonRequirements.html
================================================
<html>
<body>
<p>Detects missing Python packages that are required for communicating with your MicroPython device.
</p>
</body>
</html>

================================================
FILE: typehints/esp32/esp.pyi
================================================
from typing import Optional
from typing import Final

LOG_NONE: Final[int] = ...
LOG_ERROR: Final[int] = ...
LOG_WARN: Final[int] = ...
LOG_INFO: Final[int] = ...
LOG_DEBUG: Final[int] = ...
LOG_VERBOSE: Final[int] = ...

def flash_size():
    """Read the total size of the flash memory."""
    ...

def flash_user_start():
    """Read the memory offset at which the user flash space begins."""
    ...

def flash_read(byte_offset, length_or_buffer):
    ...

def flash_write(byte_offset, bytes):
    ...

def flash_erase(sector_no):
    ...

def osdebug(level: Optional[int]):
    """
    Turn esp os debugging messages on or off.

    The level parameter sets the threshold for the log messages for all esp components. The log levels are defined as constants:

    * ``LOG_NONE`` – No log output
    * ``LOG_ERROR`` – Critical errors, software module can not recover on its own
    * ``LOG_WARN`` – Error conditions from which recovery measures have been taken
    * ``LOG_INFO`` – Information messages which describe normal flow of events
    * ``LOG_DEBUG`` – Extra information which is not necessary for normal use (values, pointers, sizes, etc)
    * ``LOG_VERBOSE`` – Bigger chunks of debugging information, or frequent messages which can potentially flood the output
    """
    ...


================================================
FILE: typehints/esp32/esp32.pyi
================================================
from machine import Pin
from typing import Optional
from typing import overload
from typing import Final

HEAP_DATA: Final[int] = ...
"""Used in ``idf_heap_info``."""

HEAP_EXEC: Final[int] = ...
"""Used in ``idf_heap_info``."""

WAKEUP_ALL_LOW: Final[int] = ...
"""Selects the wake level for pins."""

WAKEUP_ANY_HIGH: Final[int] = ...
"""Selects the wake level for pins."""

def wake_on_touch(wake: bool):
    """
    :param wake: Configure whether or not a touch will wake the device from sleep.
    """

def wake_on_ulp(wake: bool):
    """
    :param wake: Configure whether or not the Ultra-Low-Power co-processor can wake the device from sleep.
    """

def wake_on_ext0(pin: Pin, level: Optional[int]):
    """
    Configure how EXT0 wakes the device from sleep.

    :param pin: None or a valid Pin object.
    :param level: ``esp32.WAKEUP_ALL_LOW`` or ``esp32.WAKEUP_ANY_HIGH``.
    """

def wake_on_ext1(pin: Pin, level: Optional[int]):
    """
    Configure how EXT1 wakes the device from sleep.

    :param pin: None or a valid Pin object.
    :param level: ``esp32.WAKEUP_ALL_LOW`` or ``esp32.WAKEUP_ANY_HIGH``.
    """

def gpio_deep_sleep_hold(enable: bool):
    """
    :param enable: Whether non-RTC GPIO pin configuration is retained during deep-sleep mode for held pads.
    """

def raw_temperature() -> int:
    """
    :return: The raw value of the internal temperature sensor.
    """

def hall_sensor() -> int:
    """
    :return: The raw value of the internal Hall sensor.
    """

def idf_heap_info(capabilities: Optional[int]) -> list:
    """
    Returns information about the ESP-IDF heap memory regions. One of them contains the MicroPython heap and the others
    are used by ESP-IDF, e.g., for network buffers and other data. This data is useful to get a sense of how much
    memory is available to ESP-IDF and the networking stack in particular. It may shed some light on situations where
    ESP-IDF operations fail due to allocation failures. The information returned is not useful to troubleshoot Python
    allocation failures, use ``micropython.mem_info()`` instead.

    The capabilities parameter corresponds to ESP-IDF’s ``MALLOC_CAP_XXX`` values but the two most useful ones are
    predefined as ``esp32.HEAP_DATA`` for data heap regions and ``esp32.HEAP_EXEC`` for executable regions as used by
    the native code emitter.

    The return value is a list of 4-tuples, where each 4-tuple corresponds to one heap and contains: the total bytes,
    the free bytes, the largest free block, and the minimum free seen over time.
    """

class Partition:
    """
    This class gives access to the partitions in the device’s flash memory and includes methods to
    enable over-the-air (OTA) updates.
    """

    BOOT: Final[str] = ...
    """Used in ``Partition`` constructor - The partition that will be booted at the next reset."""

    RUNNING: Final[str] = ...
    """Used in ``Partition`` constructor - The currently running partition."""

    TYPE_APP: Final[int] = ...
    """
    Used in ``Partition.find``
    - for bootable firmware partitions (typically labelled ``factory``, ``ota_0``, ``ota_1``)
    """

    TYPE_DATA: Final[int] = ...
    """
    Used in Partition.find
    - for other partitions, e.g. ``nvs``, ``otadata``, ``phy_init``, ``vfs``.
    """

    def __init__(self, id: str, block_size=4096, /):
        """
        Create an object representing a partition.

        :param id: Can be a string which is the label of the partition to retrieve or one of the
        constants: ``BOOT`` or ``RUNNING``.
        :param block_size: Specifies the byte size of an individual block.
        """

    @classmethod
    def find(self, type=TYPE_APP, subtype=0xFF, label=None, block_size=4096) -> list:
        """
        Find a partition specified by type, subtype and label.

        Note: ``subtype=0xff`` matches any subtype and ``label=None`` matches any label.

        :param block_size: Specifies the byte size of an individual block used by the returned objects.
        :return: A (possibly empty) list of Partition objects.
        """

    def info(self) -> tuple:
        """
        :return: A 6-tuple ``(type, subtype, addr, size, label, encrypted)``.
        """

    @overload
    def readblocks(self, block_num, buf): ...
    @overload
    def readblocks(self, block_num, buf, offset): ...
    @overload
    def writeblocks(self, block_num, buf): ...
    @overload
    def writeblocks(self, block_num, buf, offset): ...

    def ioctl(self, cmd, arg):
        """These methods implement the simple and extended block protocol defined by ``os.AbstractBlockDev``."""

    def set_boot(self):
        """Sets the partition as the boot partition."""

    def get_next_update(self):
        """
        Gets the next update partition after this one, and returns a new Partition object.

        Typical usage is ``Partition(Partition.RUNNING).get_next_update()``.

        :return: The next partition to update given the current running one.
        """

    def mark_app_valid_cancel_rollback(self):
        """
        Signals that the current boot is considered successful. Calling ``mark_app_valid_cancel_rollback`` is required
        on the first boot of a new partition to avoid an automatic rollback at the next boot. This uses the
        ESP-IDF “app rollback” feature with “CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE” and an ``OSError(-261)`` is raised
        if called on firmware that doesnt have the feature enabled. It is OK to call ``mark_app_valid_cancel_rollback``
        on every boot and it is not necessary when booting firmware that was loaded using esptool.
        """

class RMT:
    """
    This class provides access to one of the eight RMT channels.

    WARNING: The current MicroPython RMT implementation lacks some features, most notably receiving pulses. RMT should
    be considered a beta feature and the interface may change in the future.
    """

    def __init__(self, channel: int, *, pin=None, clock_div=8, idle_level=False, tx_carrier=None):
        """
        :param channel: Identifies which RMT channel (0-7) will be configured.
        :param pin: Configures which Pin is bound to the RMT channel
        :param clock_div: An 8-bit clock divider that divides the source clock (80MHz) to the RMT channel allowing the
        resolution to be specified.
        :param idle_level: Specifies what level the output will be when no transmission is in progress

        To enable the transmission carrier feature, ``tx_carrier`` should be a tuple of three positive integers: carrier
        frequency, duty percent (0 to 100) and the output level to apply the carrier to (a boolean as per idle_level).
        """

    def source_freq(self):
        """
        :return: The source clock frequency. Currently the source clock is not configurable so this will always
        return 80MHz.
        """

    def clock_div(self):
        """
        :return: The clock divider. Note that the channel resolution is ``1 / (source_freq / clock_div)``.
        """

    def wait_done(self, *, timeout=0):
        """
        If the timeout keyword argument is given then block for up to this many milliseconds for transmission to
        complete.

        :return: ``True`` if the channel is idle or ``False`` if a sequence of pulses started with ``RMT.write_pulses``
        is being transmitted.
        """

    def loop(self, enable_loop: bool):
        """
        Configure looping on the channel.

        :param enable_loop: ``True`` to enable looping on the next call to ``RMT.write_pulses``. If called with
        ``False`` while a looping sequence is currently being transmitted then the current loop iteration will be
        completed and then transmission will stop.
        """

    def write_pulses(self, duration, data=True):
        """
        Begin transmitting a sequence. There are three ways to specify this:

        Mode 1: duration is a list or tuple of durations. The optional data argument specifies the initial output level.
        The output level will toggle after each duration.

        Mode 2: duration is a positive integer and data is a list or tuple of output levels.
        duration specifies a fixed duration for each.

        Mode 3: duration and data are lists or tuples of equal length, specifying individual durations and the output
        level for each.

        Durations are in integer units of the channel resolution (as described above), between 1 and 32767 units.
        Output levels are any value that can be converted to a boolean, with ``True`` representing high voltage and
        ``False`` representing low.

        If transmission of an earlier sequence is in progress then this method will block until that transmission is
        complete before beginning the new sequence.

        If looping has been enabled with RMT.loop, the sequence will be repeated indefinitely. Further calls to this
        method will block until the end of the current loop iteration before immediately beginning to loop the new
        sequence of pulses. Looping sequences longer than 126 pulses is not supported by the hardware.
        """

    @staticmethod
    def bitstream_channel(value: Optional[int]) -> int:
        """
        Select which RMT channel is used by the ``machine.bitstream`` implementation.

        :param value: Can be None or a valid RMT channel number. The default RMT channel is the highest numbered one.
        Passing in None disables the use of RMT and instead selects a bit-banging implementation for
        ``machine.bitstream``. Passing in no argument will not change the channel. This function returns the current
        channel number.
        :type value: int
        """

class ULP:
    """This class provides access to the Ultra-Low-Power co-processor."""

    def set_wakeup_period(self, period_index: int, period_us):
        """Set the wake-up period."""

    def load_binary(self, load_addr, program_binary):
        """Load a program_binary into the ULP at the given load_addr."""

    def run(self, entry_point):
        """Start the ULP running at the given entry_point."""

class NVS:
    """
    This class gives access to the Non-Volatile storage managed by ESP-IDF. The NVS is partitioned into namespaces
    and each namespace contains typed key-value pairs. The keys are strings and the values may be various integer types,
    strings, and binary blobs. The driver currently only supports 32-bit signed integers and blobs.
    """

    def __init__(self, namespace: str):
        """Create an object providing access to a namespace (which is automatically created if not present)."""

    def set_i32(self, key, value):
        """Sets a 32-bit signed integer value for the specified key. Remember to call commit!"""

    def get_i32(self, key):
        """
        Returns the signed integer value for the specified key. Raises an OSError if the key does not exist or has
        a different type.
        """

    def set_blob(self, key, value):
        """
        Sets a binary blob value for the specified key. The value passed in must support the buffer protocol,
        e.g. bytes, bytearray, str. (Note that esp-idf distinguishes blobs and strings, this method always writes a
        blob even if a string is passed in as value.) Remember to call commit!
        """

    def get_blob(self, key, buffer):
        """
        Reads the value of the blob for the specified key into the buffer, which must be a bytearray.
        Returns the actual length read. Raises an OSError if the key does not exist, has a different type, or if the
        buffer is too small.
        """

    def erase_key(self, key):
        """Erases a key-value pair."""

    def commit(self):
        """Commits changes made by set_xxx methods to flash."""


================================================
FILE: typehints/esp32/network.pyi
================================================
"""network configuration

This module provides network drivers and routing configuration. To use this
module, a MicroPython variant/build with network capabilities must be installed.
Network drivers for specific hardware are available within this module and are
used to configure hardware network interface(s). Network services provided
by configured interfaces are then available for use via the :mod:`usocket`
module.

For example::

    # connect/ show IP config a specific network interface
    # see below for examples of specific drivers
    import network
    import utime
    nic = network.Driver(...)
    if not nic.isconnected():
        nic.connect()
        print("Waiting for connection...")
        while not nic.isconnected():
            utime.sleep(1)
    print(nic.ifconfig())

    # now use usocket as usual
    import usocket as socket
    addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
    data = s.recv(1000)
    s.close()
"""

from typing import overload, Optional, List, Tuple, Union, Any, Final

STA_IF: Final[int] = ...
AP_IF: Final[int] = ...

@overload
def phy_mode() -> int:
    """Get the PHY mode."""
    ...


@overload
def phy_mode(mode: int) -> None:
    """Set the PHY mode.

    The possible modes are defined as constants:
    * ``MODE_11B`` -- IEEE 802.11b,
    * ``MODE_11G`` -- IEEE 802.11g,
    * ``MODE_11N`` -- IEEE 802.11n.
    """
    ...


class WLAN:
    def __init__(self, interface_id: int) -> None:
        """Create a WLAN network interface object. Supported interfaces are
        ``network.STA_IF`` (station aka client, connects to upstream WiFi access
        points) and ``network.AP_IF`` (access point, allows other WiFi clients to
        connect). Availability of the methods below depends on interface type.
        For example, only STA interface may `connect()` to an access point.
        """
        ...

    @overload
    def active(self) -> bool:
        """Query current state of the interface."""
        ...

    @overload
    def active(self, is_active: bool) -> None:
        """Activate ("up") or deactivate ("down") network interface."""
        ...

    def connect(self, ssid: Optional[Union[bytes, str]] = None,
                password: Optional[Union[bytes, str]] = None, *,
                bssid: Optional[Union[bytes, str]] = None) -> None:
        """Connect to the specified wireless network, using the specified password.
        If *bssid* is given then the connection will be restricted to the
        access-point with that MAC address (the *ssid* must also be specified
        in this case).
        """
        ...

    def disconnect(self) -> None:
        """Disconnect from the currently connected wireless network."""
        ...

    def scan(self) -> List[Tuple[bytes, bytes, int, int, int, int]]:
        """Scan for the available wireless networks.

        Scanning is only possible on STA interface. Returns list of tuples with
        the information about WiFi access points:

            (ssid, bssid, channel, RSSI, authmode, hidden)

        *bssid* is hardware address of an access point, in binary form, returned as
        bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form.

        There are five values for authmode:

            * 0 -- open
            * 1 -- WEP
            * 2 -- WPA-PSK
            * 3 -- WPA2-PSK
            * 4 -- WPA/WPA2-PSK

        and two for hidden:

            * 0 -- visible
            * 1 -- hidden
        """
        ...

    def status(self) -> int:
        """Return the current status of the wireless connection.

        The possible statuses are defined as constants:

            * ``STAT_IDLE`` -- no connection and no activity,
            * ``STAT_CONNECTING`` -- connecting in progress,
            * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password,
            * ``STAT_NO_AP_FOUND`` -- failed because no access point replied,
            * ``STAT_CONNECT_FAIL`` -- failed due to other problems,
            * ``STAT_GOT_IP`` -- connection successful.
        """
        ...

    def isconnected(self) -> bool:
        """In case of STA mode, returns ``True`` if connected to a WiFi access
        point and has a valid IP address.  In AP mode returns ``True`` when a
        station is connected. Returns ``False`` otherwise.
        """
        ...

    @overload
    def ifconfig(self) -> Tuple[str, str, str, str]:
        """Get IP-level network interface parameters: IP address, subnet mask,
        gateway and DNS server.
        """
        ...

    @overload
    def ifconfig(self, ip: str, subnet: str, gateway: str, dns: str) -> None:
        """Get/set IP-level network interface parameters: IP address, subnet mask,
        gateway and DNS server.
        """
        ...

    @overload
    def config(self, param: str) -> Any:
        """Get general network interface parameters."""
        ...

    @overload
    def config(self, **kwargs: Any) -> None:
        """Get or set general network interface parameters. These methods allow to work
        with additional parameters beyond standard IP configuration (as dealt with by
        `wlan.ifconfig()`). These include network-specific and hardware-specific
        parameters. For setting parameters, keyword argument syntax should be used,
        multiple parameters can be set at once. For querying, parameters name should
        be quoted as a string, and only one parameter can be queries at time::

            # Set WiFi access point name (formally known as ESSID) and WiFi channel
            ap.config(essid='My AP', channel=11)
            # Query params one by one
            print(ap.config('essid'))
            print(ap.config('channel'))

        Following are commonly supported parameters (availability of a specific parameter
        depends on network technology type, driver, and `MicroPython port`).

        =============  ===========
        Parameter      Description
        =============  ===========
        mac            MAC address (bytes)
        essid          WiFi access point name (string)
        channel        WiFi channel (integer)
        hidden         Whether ESSID is hidden (boolean)
        authmode       Authentication mode supported (enumeration, see module constants)
        password       Access password (string)
        dhcp_hostname  The DHCP hostname to use
        =============  ===========
        """
        ...


STA_IF: int
AP_IF: int


STAT_IDLE: int
STAT_CONNECTING: int
STAT_WRONG_PASSWORD: int
STAT_NO_AP_FOUND: int
STAT_CONNECT_FAIL: int
STAT_GOT_IP: int


MODE_11B: int
MODE_11G: int
MODE_11N: int



================================================
FILE: typehints/esp8266/esp.pyi
================================================

from typing import Optional

def sleep_type(sleep_type: Optional[int]) -> Optional[int]:
    """
    Get or set the sleep type.

    If the sleep_type parameter is provided, sets the sleep type to its value.
    If the function is called without parameters, returns the current sleep type.

    The possible sleep types are defined as constants:

    * ``SLEEP_NONE`` – all functions enabled,\n
    * ``SLEEP_MODEM`` – modem sleep, shuts down the WiFi Modem circuit.\n
    * ``SLEEP_LIGHT`` – light sleep, shuts down the WiFi Modem circuit and suspends the processor periodically.\n
    The system enters the set sleep mode automatically when possible.

    :param sleep_type: Sleep type.
    :type sleep_type: int
    :return: Current sleep type
    :rtype: int
    """

def deepsleep(time: int = 0) -> None:
    """
    Enter deep sleep.

    The whole module powers down, except for the RTC clock circuit, which can
    be used to restart the module after the specified time if the pin 16 is
    connected to the reset pin. Otherwise the module will sleep until manually reset.

    :param time: Amount of time in milliseconds to sleep.
    """

def set_native_code_location(start: Optional[int], length: Optional[int]) -> None:
    """
    Set the location that native code will be placed for execution after it is
    compiled. Native code is emitted when the ``@micropython.native``, ``@micropython.viper``
    and ``@micropython.asm_xtensa`` decorators are applied to a function. The
    ESP8266 must execute code from either iRAM or the lower 1MByte of flash
    (which is memory mapped), and this function controls the location.

    If start and length are both **None** then the native code location is
    set to the unused portion of memory at the end of the iRAM1 region. The
    size of this unused portion depends on the firmware and is typically
    quite small (around 500 bytes), and is enough to store a few very small
    functions. The advantage of using this iRAM1 region is that it does not
    get worn out by writing to it.

    If neither start nor length are None then they should be integers. start
    should specify the byte offset from the beginning of the flash at which
    native code should be stored. length specifies how many bytes of flash
    from start can be used to store native code. start and length should be
    multiples of the sector size (being 4096 bytes). The flash will be
    automatically erased before writing to it so be sure to use a region of
    flash that is not otherwise used, for example by the firmware or the filesystem.

    When using the flash to store native code *start*+*length* must be less
    than or  equal to 1MByte. Note that the flash can be worn out if repeated
    erasures (and writes) are made so use this feature sparingly. In particular,
    native code needs to be recompiled and rewritten to flash on each boot
    (including wake from deepsleep).

    In both cases above, using iRAM1 or flash, if there is no more room left in
    the specified region then the use of a native decorator on a function will
    lead to ``MemoryError`` exception being raised during compilation of that function.

    :param start: Start of native code region.
    :param length: End of native code region.
    """

================================================
FILE: typehints/esp8266/network.pyi
================================================
"""network configuration

This module provides network drivers and routing configuration. To use this
module, a MicroPython variant/build with network capabilities must be installed.
Network drivers for specific hardware are available within this module and are
used to configure hardware network interface(s). Network services provided
by configured interfaces are then available for use via the :mod:`usocket`
module.

For example::

    # connect/ show IP config a specific network interface
    # see below for examples of specific drivers
    import network
    import utime
    nic = network.Driver(...)
    if not nic.isconnected():
        nic.connect()
        print("Waiting for connection...")
        while not nic.isconnected():
            utime.sleep(1)
    print(nic.ifconfig())

    # now use usocket as usual
    import usocket as socket
    addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
    data = s.recv(1000)
    s.close()
"""

from typing import overload, Optional, List, Tuple, Union, Any, Final

STA_IF: Final[int] = ...
AP_IF: Final[int] = ...

@overload
def phy_mode() -> int:
    """Get the PHY mode."""
    ...


@overload
def phy_mode(mode: int) -> None:
    """Set the PHY mode.

    The possible modes are defined as constants:
    * ``MODE_11B`` -- IEEE 802.11b,
    * ``MODE_11G`` -- IEEE 802.11g,
    * ``MODE_11N`` -- IEEE 802.11n.
    """
    ...


class WLAN:
    def __init__(self, interface_id: int) -> None:
        """Create a WLAN network interface object. Supported interfaces are
        ``network.STA_IF`` (station aka client, connects to upstream WiFi access
        points) and ``network.AP_IF`` (access point, allows other WiFi clients to
        connect). Availability of the methods below depends on interface type.
        For example, only STA interface may `connect()` to an access point.
        """
        ...

    @overload
    def active(self) -> bool:
        """Query current state of the interface."""
        ...

    @overload
    def active(self, is_active: bool) -> None:
        """Activate ("up") or deactivate ("down") network interface."""
        ...

    def connect(self, ssid: Optional[Union[bytes, str]] = None,
                password: Optional[Union[bytes, str]] = None, *,
                bssid: Optional[Union[bytes, str]] = None) -> None:
        """Connect to the specified wireless network, using the specified password.
        If *bssid* is given then the connection will be restricted to the
        access-point with that MAC address (the *ssid* must also be specified
        in this case).
        """
        ...

    def disconnect(self) -> None:
        """Disconnect from the currently connected wireless network."""
        ...

    def scan(self) -> List[Tuple[bytes, bytes, int, int, int, int]]:
        """Scan for the available wireless networks.

        Scanning is only possible on STA interface. Returns list of tuples with
        the information about WiFi access points:

            (ssid, bssid, channel, RSSI, authmode, hidden)

        *bssid* is hardware address of an access point, in binary form, returned as
        bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form.

        There are five values for authmode:

            * 0 -- open
            * 1 -- WEP
            * 2 -- WPA-PSK
            * 3 -- WPA2-PSK
            * 4 -- WPA/WPA2-PSK

        and two for hidden:

            * 0 -- visible
            * 1 -- hidden
        """
        ...

    def status(self) -> int:
        """Return the current status of the wireless connection.

        The possible statuses are defined as constants:

            * ``STAT_IDLE`` -- no connection and no activity,
            * ``STAT_CONNECTING`` -- connecting in progress,
            * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password,
            * ``STAT_NO_AP_FOUND`` -- failed because no access point replied,
            * ``STAT_CONNECT_FAIL`` -- failed due to other problems,
            * ``STAT_GOT_IP`` -- connection successful.
        """
        ...

    def isconnected(self) -> bool:
        """In case of STA mode, returns ``True`` if connected to a WiFi access
        point and has a valid IP address.  In AP mode returns ``True`` when a
        station is connected. Returns ``False`` otherwise.
        """
        ...

    @overload
    def ifconfig(self) -> Tuple[str, str, str, str]:
        """Get IP-level network interface parameters: IP address, subnet mask,
        gateway and DNS server.
        """
        ...

    @overload
    def ifconfig(self, ip: str, subnet: str, gateway: str, dns: str) -> None:
        """Get/set IP-level network interface parameters: IP address, subnet mask,
        gateway and DNS server.
        """
        ...

    @overload
    def config(self, param: str) -> Any:
        """Get general network interface parameters."""
        ...

    @overload
    def config(self, **kwargs: Any) -> None:
        """Get or set general network interface parameters. These methods allow to work
        with additional parameters beyond standard IP configuration (as dealt with by
        `wlan.ifconfig()`). These include network-specific and hardware-specific
        parameters. For setting parameters, keyword argument syntax should be used,
        multiple parameters can be set at once. For querying, parameters name should
        be quoted as a string, and only one parameter can be queries at time::

            # Set WiFi access point name (formally known as ESSID) and WiFi channel
            ap.config(essid='My AP', channel=11)
            # Query params one by one
            print(ap.config('essid'))
            print(ap.config('channel'))

        Following are commonly supported parameters (availability of a specific parameter
        depends on network technology type, driver, and `MicroPython port`).

        =============  ===========
        Parameter      Description
        =============  ===========
        mac            MAC address (bytes)
        essid          WiFi access point name (string)
        channel        WiFi channel (integer)
        hidden         Whether ESSID is hidden (boolean)
        authmode       Authentication mode supported (enumeration, see module constants)
        password       Access password (string)
        dhcp_hostname  The DHCP hostname to use
        =============  ===========
        """
        ...


STA_IF: int
AP_IF: int


STAT_IDLE: int
STAT_CONNECTING: int
STAT_WRONG_PASSWORD: int
STAT_NO_AP_FOUND: int
STAT_CONNECT_FAIL: int
STAT_GOT_IP: int


MODE_11B: int
MODE_11G: int
MODE_11N: int



================================================
FILE: typehints/microbit/microbit/__init__.pyi
================================================
"""micro:bit Micropython API

Everything directly related to interacting with the hardware lives in the
`microbit` module.  For ease of use it's recommended you start all scripts
with::

    from microbit import *

The following documentation assumes you have done this.

There are a few functions available directly::

    # sleep for the given number of milliseconds.
    sleep(ms)
    # returns the number of milliseconds since the micro:bit was last switched on.
    running_time()
    # makes the micro:bit enter panic mode (this usually happens when the DAL runs
    # out of memory, and causes a sad face to be drawn on the display). The error
    # code can be any arbitrary integer value.
    panic(error_code)
    # resets the micro:bit.
    reset()

The rest of the functionality is provided by objects and classes in the
microbit module, as described below.

Note that the API exposes integers only (ie no floats are needed, but they may
be accepted).  We thus use milliseconds for the standard time unit.
"""

from . import (display as display, uart as uart, spi as spi, i2c as i2c,
               accelerometer as accelerometer, compass as compass)

from typing import Any, List, overload


def panic(n: int) -> None:
    """Enter a panic mode. Requires restart. Pass in an arbitrary integer <= 255
    to indicate a status::

        microbit.panic(255)
    """


def reset() -> None:
    """Restart the board."""


def sleep(n: int) -> None:
    """Wait for ``n`` milliseconds. One second is 1000 milliseconds, so::

        microbit.sleep(1000)

    will pause the execution for one second.  ``n`` can be an integer or
    a floating point number.
    """


def running_time() -> int:
    """Return the number of milliseconds since the board was switched on or
    restarted.
    """


def temperature() -> int:
    """Return the temperature of the micro:bit in degrees Celcius."""


class Button:
    """Represents a button.

    .. note::
        This class is not actually available to the user, it is only used by
        the two button instances, which are provided already initialized.
        """

    def is_pressed(self) -> bool:
        """Returns ``True`` if the specified button ``button`` is pressed, and
        ``False`` otherwise.
        """

    def was_pressed(self) -> bool:
        """Returns ``True`` or ``False`` to indicate if the button was pressed
        since the device started or the last time this method was called.
        """

    def get_presses(self) -> int:
        """Returns the running total of button presses, and resets this total
        to zero before returning.
        """


button_a: Button
"""A ``Button`` instance (see below) representing the left button."""

button_b: Button
"""Represents the right button."""


class MicroBitDigitalPin:
    """
    The pull mode for a pin is automatically configured when the pin changes to an
    input mode. Input modes are when you call ``read_analog`` / ``read_digital`` /
    ``is_touched``. The pull mode for these is, respectively, ``NO_PULL``,
    ``PULL_DOWN``, ``PULL_UP``. Only when in ``read_digital`` mode can you call
    ``set_pull`` to change the pull mode from the default.
    """

    NO_PULL: int = 0
    PULL_UP: int = 1
    PULL_DOWN: int = 2

    def read_digital(self) -> int:
        """Return 1 if the pin is high, and 0 if it's low."""

    def set_pull(self, value: int = (NO_PULL or PULL_UP or PULL_DOWN)) -> None:
        """Set the pull state to one of three possible values: ``pin.PULL_UP``,
        ``pin.PULL_DOWN`` or ``pin.NO_PULL`` (where ``pin`` is an instance of
        a pin). See below for discussion of default pull states.
        """

    def write_digital(self, value: int) -> None:
        """Set the pin to high if ``value`` is 1, or to low, if it is 0."""

    def write_analog(self, value: int) -> None:
        """Output a PWM signal on the pin, with the duty cycle proportional to
        the provided ``value``. The ``value`` may be either an integer or a
        floating point number between 0 (0% duty cycle) and 1023 (100% duty).
        """

    def set_analog_period(self, period: int) -> None:
        """Set the period of the PWM signal being output to ``period`` in
        milliseconds. The minimum valid value is 1ms.
        """

    def set_analog_period_microseconds(self, period: int) -> None:
        """Set the period of the PWM signal being output to ``period`` in
        microseconds. The minimum valid value is 35µs.
        """

class MicroBitAnalogDigitalPin(MicroBitDigitalPin):
    def read_analog(self) -> int:
        """Read the voltage applied to the pin, and return it as an integer
        between 0 (meaning 0V) and 1023 (meaning 3.3V).
        """

class MicroBitTouchPin(MicroBitAnalogDigitalPin):
    def is_touched(self) -> bool:
        """Return ``True`` if the pin is being touched with a finger, otherwise
        return ``False``.

        This test is done by measuring the capacitance of the pin together with
        whatever is connected to it. Human body has quite a large capacitance,
        so touching the pin gives a dramatic change in reading, which can be
        detected.
        """

pin0: MicroBitTouchPin
"""Pad 0."""

pin1: MicroBitTouchPin
"""Pad 1."""

pin2: MicroBitTouchPin
"""Pad 2."""

pin3: MicroBitAnalogDigitalPin
"""Column 1."""

pin4: MicroBitAnalogDigitalPin
"""Column 2."""

pin5: MicroBitDigitalPin
"""Button A."""

pin6: MicroBitDigitalPin
"""Row 2."""

pin7: MicroBitDigitalPin
"""Row 1."""

pin8: MicroBitDigitalPin

pin9: MicroBitDigitalPin
"""Row 3."""

pin10: MicroBitAnalogDigitalPin
"""Column 3."""

pin11: MicroBitDigitalPin
"""Button B."""

pin12: MicroBitDigitalPin

pin13: MicroBitDigitalPin
"""SPI MOSI."""

pin14: MicroBitDigitalPin
"""SPI MISO."""

pin15: MicroBitDigitalPin
"""SPI SCK."""

pin16: MicroBitDigitalPin

pin19: MicroBitDigitalPin
"""I2C SCL."""

pin20: MicroBitDigitalPin
"""I2C SDA."""


class Image:
    """The ``Image`` class is used to create images that can be displayed
    easily on the device's LED matrix. Given an image object it's possible to
    display it via the ``display`` API::

        display.show(Image.HAPPY)
    """

    HEART: Image
    HEART_SMALL: Image
    HAPPY: Image
    SMILE: Image
    SAD: Image
    CONFUSED: Image
    ANGRY: Image
    ASLEEP: Image
    SURPRISED: Image
    SILLY: Image
    FABULOUS: Image
    MEH: Image
    YES: Image
    NO: Image
    CLOCK12: Image
    CLOCK11: Image
    CLOCK10: Image
    CLOCK9: Image
    CLOCK8: Image
    CLOCK7: Image
    CLOCK6: Image
    CLOCK5: Image
    CLOCK4: Image
    CLOCK3: Image
    CLOCK2: Image
    CLOCK1: Image
    ARROW_N: Image
    ARROW_NE: Image
    ARROW_E: Image
    ARROW_SE: Image
    ARROW_S: Image
    ARROW_SW: Image
    ARROW_W: Image
    ARROW_NW: Image
    TRIANGLE: Image
    TRIANGLE_LEFT: Image
    CHESSBOARD: Image
    DIAMOND: Image
    DIAMOND_SMALL: Image
    SQUARE: Image
    SQUARE_SMALL: Image
    RABBIT: Image
    COW: Image
    MUSIC_CROTCHET: Image
    MUSIC_QUAVER: Image
    MUSIC_QUAVERS: Image
    PITCHFORK: Image
    XMAS: Image
    PACMAN: Image
    TARGET: Image
    TSHIRT: Image
    ROLLERSKATE: Image
    DUCK: Image
    HOUSE: Image
    TORTOISE: Image
    BUTTERFLY: Image
    STICKFIGURE: Image
    GHOST: Image
    SWORD: Image
    GIRAFFE: Image
    SKULL: Image
    UMBRELLA: Image
    SNAKE: Image

    ALL_CLOCKS: List[Image]
    ALL_ARROWS: List[Image]

    @overload
    def __init__(self, string: str) -> None:
        """``string`` has to consist of digits 0-9 arranged into lines,
        describing the image, for example::

            image = Image("90009:"
                          "09090:"
                          "00900:"
                          "09090:"
                          "90009")

        will create a 5×5 image of an X. The end of a line is indicated by a
        colon. It's also possible to use a newline (\n) to indicate the end of
        a line like this::

            image = Image("90009\n"
                          "09090\n"
                          "00900\n"
                          "09090\n"
                          "90009")
        """

    @overload
    def __init__(self, width: int = None, height: int = None,
                 buffer: Any = None) -> None:
        """Create an empty image with ``width`` columns and ``height`` rows.
        Optionally ``buffer`` can be an array of ``width``×``height`` integers
        in range 0-9 to initialize the image.
        """

    def width(self) -> int:
        """Return the number of columns in the image."""

    def height(self) -> int:
        """Return the numbers of rows in the image."""

    def set_pixel(self, x: int, y: int, value: int) -> None:
        """Set the brightness of the pixel at column ``x`` and row ``y`` to the
        ``value``, which has to be between 0 (dark) and 9 (bright).

        This method will raise an exception when called on any of the built-in
        read-only images, like ``Image.HEART``.
        """

    def get_pixel(self, x: int, y: int) -> int:
        """Return the brightness of pixel at column ``x`` and row ``y`` as an
        integer between 0 and 9.
        """

    def shift_left(self, n: int) -> Image:
        """Return a new image created by shifting the picture left by ``n``
        columns.
        """

    def shift_right(self, n: int) -> Image:
        """Same as ``image.shift_left(-n)``."""

    def shift_up(self, n: int) -> Image:
        """Return a new image created by shifting the picture up by ``n``
        rows.
        """

    def shift_down(self, n: int) -> Image:
        """Same as ``image.shift_up(-n)``."""

    def crop(self, x: int, y: int, w: int, h: int) -> Image:
        """Return a new image by cropping the picture to a width of ``w`` and a
        height of ``h``, starting with the pixel at column ``x`` and row
        ``y``.
        """

    def copy(self) -> Image:
        """Return an exact copy of the image."""

    def invert(self) -> Image:
        """Return a new image by inverting the brightness of the pixels in the
        source image."""

    def fill(self, value: int) -> None:
        """Set the brightness of all the pixels in the image to the
        ``value``, which has to be between 0 (dark) and 9 (bright).

        This method will raise an exception when called on any of the built-in
        read-only images, like ``Image.HEART``.
        """

    def blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int = 0,
             ydest: int = 0) -> None:
        """Copy the rectangle defined by ``x``, ``y``, ``w``, ``h`` from the
        image ``src`` into this image at ``xdest``, ``ydest``. Areas in the
        source rectangle, but outside the source image are treated as having a
        value of 0.

        ``shift_left()``, ``shift_right()``, ``shift_up()``, ``shift_down()``
        and ``crop()`` can are all implemented by using ``blit()``.

        For example, img.crop(x, y, w, h) can be implemented as::

            def crop(self, x, y, w, h):
                res = Image(w, h)
                res.blit(self, x, y, w, h)
                return res
        """

    def __repr__(self) -> str:
        """Get a compact string representation of the image."""

    def __str__(self) -> str:
        """Get a readable string representation of the image."""

    def __add__(self, other: Image) -> Image:
        """Create a new image by adding the brightness values from the two
        images for each pixel.
        """

    def __mul__(self, n: float) -> Image:
        """Create a new image by multiplying the brightness of each pixel by
        ``n``.
        """


================================================
FILE: typehints/microbit/microbit/accelerometer.pyi
================================================
"""This object gives you access to the on-board accelerometer. The accelerometer
also provides convenience functions for detecting gestures. The
recognised gestures are: ``up``, ``down``, ``left``, ``right``, ``face up``,
``face down``, ``freefall``, ``3g``, ``6g``, ``8g``, ``shake``.
"""


from typing import Tuple


def get_x() -> int:
    """Get the acceleration measurement in the ``x`` axis, as a positive or
    negative integer, depending on the direction.
    """


def get_y() -> int:
    """Get the acceleration measurement in the ``y`` axis, as a positive or
    negative integer, depending on the direction.
    """


def get_z() -> int:
    """Get the acceleration measurement in the ``z`` axis, as a positive or
    negative integer, depending on the direction.
    """


def get_values() -> Tuple[int, int, int]:
    """Get the acceleration measurements in all axes at once, as a three-element
    tuple of integers ordered as X, Y, Z.
    """


def current_gesture() -> str:
    """Return the name of the current gesture.

    .. note::

        MicroPython understands the following gesture names: ``"up"``, ``"down"``,
        ``"left"``, ``"right"``, ``"face up"``, ``"face down"``, ``"freefall"``,
        ``"3g"``, ``"6g"``, ``"8g"``, ``"shake"``. Gestures are always
        represented as strings."""


def is_gesture(name: str) -> bool:
    """Return True or False to indicate if the named gesture is currently
    active."""


def was_gesture(name: str) -> bool:
    """Return True or False to indicate if the named gesture was active since the
    last call.
    """


def get_gestures() -> Tuple[str, ...]:
    """Return a tuple of the gesture history. The most recent is listed last.
    Also clears the gesture history before returning.
    """

================================================
FILE: typehints/microbit/microbit/compass.pyi
================================================
"""This module lets you access the built-in electronic compass. Before using,
the compass should be calibrated, otherwise the readings may be wrong.

.. warning::

    Calibrating the compass will cause your program to pause until calibration
    is complete. Calibration consists of a little game to draw a circle on the
    LED display by rotating the device.
"""


def calibrate() -> None:
    """Starts the calibration process. An instructive message will be scrolled
    to the user after which they will need to rotate the device in order to
    draw a circle on the LED display.
    """


def is_calibrated() -> bool:
    """Returns ``True`` if the compass has been successfully calibrated, and
    returns ``False`` otherwise.
    """


def clear_calibration() -> None:
    """Undoes the calibration, making the compass uncalibrated again."""


def get_x() -> int:
    """Gives the reading of the magnetic force on the ``x`` axis, as a
    positive or negative integer, depending on the direction of the
    force.
    """


def get_y() -> int:
    """Gives the reading of the magnetic force on the ``x`` axis, as a
    positive or negative integer, depending on the direction of the
    force.
    """


def get_z() -> int:
    """Gives the reading of the magnetic force on the ``x`` axis, as a
    positive or negative integer, depending on the direction of the
    force.
    """


def heading() -> int:
    """Gives the compass heading, calculated from the above readings, as an
    integer in the range from 0 to 360, representing the angle in degrees,
    clockwise, with north as 0.
    If the compass has not been calibrated, then this will call ``calibrate``.
    """


def get_field_strength() -> int:
    """Returns an integer indication of the magnitude of the magnetic field
    around the device."""


================================================
FILE: typehints/microbit/microbit/display.pyi
================================================
"""This module controls the 5×5 LED display on the front of your board. It can
be used to display images, animations and even text.

To continuously scroll a string across the display, and do it in the background,
you can use::

    import microbit

    microbit.display.scroll('Hello!', wait=False, loop=True)
"""

from . import Image
from typing import overload, Iterable

def get_pixel(x: int, y: int) -> int:
    """Return the brightness of the LED at column ``x`` and row ``y`` as an
    integer between 0 (off) and 9 (bright).
    """

def set_pixel(x: int, y: int, value: int) -> None:
    """Set the brightness of the LED at column ``x`` and row ``y`` to ``value``,
    which has to be an integer between 0 and 9.
    """

def clear() -> None:
    """Set the brightness of all LEDs to 0 (off)."""


@overload
def show(image: Image) -> None:
    """Display the ``image``."""


@overload
def show(iterable: Iterable[Image, str], delay: int = 400, *,
         wait: bool = True, loop: bool =False, clear: bool = False) -> None:
    """Display images or letters from the ``iterable`` in sequence, with
    ``delay`` milliseconds between them.

    If ``wait`` is ``True``, this function will block until the animation is
    finished, otherwise the animation will happen in the background.

    If ``loop`` is ``True``, the animation will repeat forever.

    If ``clear`` is ``True``, the display will be cleared after the iterable
    has finished.

    Note that the ``wait``, ``loop`` and ``clear`` arguments must be specified
    using their keyword.

    .. note::

        If using a generator as the ``iterable``, then take care not to
        allocate any memory in the generator as allocating memory in an
        interrupt is prohibited and will raise a ``MemoryError``.
    """


def scroll(string: str, delay: int = 150, *, wait: bool = True,
           loop: bool = False, monospace: bool = False) -> None:
    """Similar to ``show``, but scrolls the ``string`` horizontally instead. The
    ``delay`` parameter controls how fast the text is scrolling.

    If ``wait`` is ``True``, this function will block until the animation is
    finished, otherwise the animation will happen in the background.

    If ``loop`` is ``True``, the animation will repeat forever.

    If ``monospace`` is ``True``, the characters will all take up 5 pixel-columns
    in width, otherwise there will be exactly 1 blank pixel-column between each
    character as they scroll.

    Note that the ``wait``, ``loop`` and ``monospace`` arguments must be specified
    using their keyword.
    """


def on() -> None:
    """Use on() to turn on the display."""


def off() -> None:
    """Use off() to turn off the display (thus allowing you to re-use the GPIO
    pins associated with the display for other purposes).
    """


def is_on() -> bool:
    """Returns ``True`` if the display is on, otherwise returns ``False``."""


================================================
FILE: typehints/microbit/microbit/i2c.pyi
================================================
"""The ``i2c`` module lets you communicate with devices connected to your board
using the I²C bus protocol. There can be multiple slave devices connected at
the same time, and each one has its own unique address, that is either fixed
for the device or configured on it. Your board acts as the I²C master.

We use 7-bit addressing for devices because of the reasons stated
`here <http://www.totalphase.com/support/articles/200349176-7-bit-8-bit-and-10-bit-I2C-Slave-Addressing>`_.

This may be different to other micro:bit related solutions.

How exactly you should communicate with the devices, that is, what bytes to
send and how to interpret the responses, depends on the device in question and
should be described separately in that device's documentation.

You should connect the device's ``SCL`` pin to micro:bit pin 19, and the
device's ``SDA`` pin to micro:bit pin 20. You also must connect the device's
ground to the micro:bit ground (pin ``GND``). You may need to power the device
using an external power supply or the micro:bit.

There are internal pull-up resistors on the I²C lines of the board, but with
particularly long wires or large number of devices you may need to add
additional pull-up resistors, to ensure noise-free communication.
"""

from . import pin19, pin20
from typing import Union
from . import pin19, pin20


def init(freq: int = 100000, sda: int = pin20, scl: int = pin19) -> None:
    """Re-initialize peripheral with the specified clock frequency ``freq`` on the
    specified ``sda`` and ``scl`` pins.

    .. warning::

        Changing the I²C pins from defaults will make the accelerometer and
        compass stop working, as they are connected internally to those pins.
    """


def read(addr: int, n: int, repeat: bool = False) -> bytes:
    """Read ``n`` bytes from the device with 7-bit address ``addr``. If ``repeat``
    is ``True``, no stop bit will be sent.
    """


def write(addr: int, buf: Union[bytes, bytearray], repeat=False) -> None:
    """Write bytes from ``buf`` to the device with 7-bit address ``addr``. If
    ``repeat`` is ``True``, no stop bit will be sent.
    """

================================================
FILE: typehints/microbit/microbit/spi.pyi
================================================
"""The ``spi`` module lets you talk to a device connected to your board using
a serial peripheral interface (SPI) bus. SPI uses a so-called master-slave
architecture with a single master. You will need to specify the connections
for three signals:

* SCLK : Serial Clock (output from master).
* MOSI : Master Output, Slave Input (output from master).
* MISO : Master Input, Slave Output (output from slave).
"""


from . import pin13, pin14, pin15, MicroBitDigitalPin
from typing import Union


def init(baudrate: int = 1000000, bits: int = 8, mode: int = 0,
         sclk: MicroBitDigitalPin = pin13,
         mosi: MicroBitDigitalPin = pin15,
         miso: MicroBitDigitalPin = pin14) -> None:
    """Initialize SPI communication with the specified parameters on the
    specified ``pins``. Note that for correct communication, the parameters
    have to be the same on both communicating devices.

    The ``baudrate`` defines the speed of communication.

    The ``bits`` defines the size of bytes being transmitted. Currently only
    ``bits=8`` is supported. However, this may change in the future.

    The ``mode`` determines the combination of clock polarity and phase
    according to the following convention, with polarity as the high order bit
    and phase as the low order bit:

    +----------+-----------------+--------------+
    | SPI Mode | Polarity (CPOL) | Phase (CPHA) |
    +==========+=================+==============+
    | 0        | 0               | 0            |
    +----------+-----------------+--------------+
    | 1        | 0               | 1            |
    +----------+-----------------+--------------+
    | 2        | 1               | 0            |
    +----------+-----------------+--------------+
    | 3        | 1               | 1            |
    +----------+-----------------+--------------+

    Polarity (aka CPOL) 0 means that the clock is at logic value 0 when idle
    and goes high (logic value 1) when active; polarity 1 means the clock is
    at logic value 1 when idle and goes low (logic value 0) when active. Phase
    (aka CPHA) 0 means that data is sampled on the leading edge of the clock,
    and 1 means on the trailing edge
    (viz. https://en.wikipedia.org/wiki/Signal_edge).

    The ``sclk``, ``mosi`` and ``miso`` arguments specify the pins to use for
    each type of signal.
    """


def read(nbytes: int) -> bytes:
    """Read at most ``nbytes``. Returns what was read."""


def write(buffer: Union[bytes, bytearray]) -> None:
    """Write the ``buffer`` of bytes to the bus."""


def write_readinto(out: Union[bytes, bytearray], in_: bytearray) -> None:
    """Write the ``out`` buffer to the bus and read any response into the ``in``
   buffer. The length of the buffers should be the same. The buffers can be
   the same object."""

================================================
FILE: typehints/microbit/microbit/uart.pyi
================================================
"""The ``uart`` module lets you talk to a device connected to your board using
a serial interface.
"""

from . import MicroBitDigitalPin
from typing import Optional, Union


def init(baudrate: int = 9600, bits: int = 8, parity: int = None,
         stop: int = 1, *, tx: MicroBitDigitalPin = None,
         rx: MicroBitDigitalPin = None) -> None:
    """Initialize serial communication with the specified parameters on the
    specified ``tx`` and ``rx`` pins. Note that for correct communication, the
    parameters have to be the same on both communicating devices.

    .. warning::

        Initializing the UART on external pins will cause the Python console on
        USB to become unaccessible, as it uses the same hardware. To bring the
        console back you must reinitialize the UART without passing anything for
        ``tx'' or ``rx'' (or passing ``None'' to these arguments).  This means
        that calling ``uart.init(115200)'' is enough to restore the Python console.

    The ``baudrate`` defines the speed of communication. Common baud
    rates include:

        * 9600
        * 14400
        * 19200
        * 28800
        * 38400
        * 57600
        * 115200

    The ``bits`` defines the size of bytes being transmitted, and the board
    only supports 8. The ``parity`` parameter defines how parity is checked,
    and it can be ``None``, ``microbit.uart.ODD`` or ``microbit.uart.EVEN``.
    The ``stop`` parameter tells the number of stop bits, and has to be 1 for
    this board.

    If ``tx`` and ``rx`` are not specified then the internal USB-UART TX/RX pins
    are used which connect to the USB serial convertor on the micro:bit, thus
    connecting the UART to your PC.  You can specify any other pins you want by
    passing the desired pin objects to the ``tx`` and ``rx`` parameters.

    .. note::

        When connecting the device, make sure you "cross" the wires -- the TX
        pin on your board needs to be connected with the RX pin on the device,
        and the RX pin -- with the TX pin on the device. Also make sure the
        ground pins of both devices are connected.
    """


def any() -> bool:
    """Return ``True`` if any characters waiting, else ``False``."""


def read(nbytes: int = None) -> bytes:
    """Read characters.  If ``nbytes`` is specified then read at most that many
    bytes."""


def readall() -> Optional[bytes]:
    """Read as much data as possible.

    Return value: a bytes object or ``None`` on timeout.
    """


def readinto(buf: bytearray, nbytes: int = None) -> Optional[int]:
    """Read bytes into the ``buf``.  If ``nbytes`` is specified then read at most
    that many bytes.  Otherwise, read at most ``len(buf)`` bytes.

    Return value: number of bytes read and stored into ``buf`` or ``None`` on
    timeout.
    """


def readline() -> Optional[bytes]:
    """Read a line, ending in a newline character.

    Return value: the line read or ``None`` on timeout. The newline character is
    included in the returned bytes.
    """

def write(buf: Union[bytes, bytearray]) -> Optional[int]:
    """Write the buffer of bytes to the bus.

    Return value: number of bytes written or ``None`` on timeout.
    """

ODD: int
EVEN: int

================================================
FILE: typehints/microbit/music.pyi
================================================



"""
MicroPython on the BBC micro:bit comes with a powerful music and
sound module. It’s very easy to generate bleeps and bloops from
the device if you attach a speaker. Use crocodile clips to attach
pin 0 and GND to the positive and negative inputs on the speaker -
it doesn’t matter which way round they are connected to the speaker.

Musical Notation

    An individual note is specified thus:

    NOTE[octave][:duration]

    For example, A1:4 refers to the note “A” in octave 1 that lasts for four ticks
     (a tick is an arbitrary length of time defined by a tempo setting function -
     see below). If the note name R is used then it is treated as a rest (silence).

    Accidentals (flats and sharps) are denoted by the b
    (flat - a lower case b) and # (sharp - a hash symbol).
    For example, Ab is A-flat and C# is C-sharp.

    Note names are case-insensitive.

    The octave and duration parameters are states that carry over to
    subsequent notes until re-specified. The default states are octave = 4
    (containing middle C) and duration = 4 (a crotchet, given the default
    tempo settings - see below).

    For example, if 4 ticks is a crotchet, the following list is crotchet,
    quaver, quaver, crotchet based arpeggio:

    ['c1:4', 'e:2', 'g', 'c2:4']

    The opening of Beethoven’s 5th Symphony would be encoded thus:

    ['r4:2', 'g', 'g', 'g', 'eb:8', 'r:2', 'f', 'f', 'f', 'd:8']

    The definition and scope of an octave conforms to the table
    listed on this page about scientific pitch notation. For example, middle “C” is
    c4' and concert “A” (440) is 'a4'. Octaves start on the note “C”.
    The definition and scope of an octave conforms to the table
    listed on this page about scientific pitch notation. For example, middle
    “C” is 'c4' and concert “A” (440) is 'a4'. Octaves start on the note “C”.


        Built in Melodies

        For the purposes of education and entertainment, the module contains
        several example tunes that are expressed as Pytho
Download .txt
gitextract_ebr8_o39/

├── .github/
│   └── workflows/
│       └── check.yml
├── .gitignore
├── CHANGES.md
├── LICENSE.txt
├── Pipfile
├── README.md
├── build.gradle.kts
├── examples/
│   └── rpsls.py
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── licenses/
│   └── microrepl_license.txt
├── scripts/
│   ├── findusb.py
│   ├── microcleanfs.py
│   ├── microrepl.py
│   └── microupload.py
├── src/
│   └── main/
│       ├── kotlin/
│       │   └── com/
│       │       └── jetbrains/
│       │           └── micropython/
│       │               ├── actions/
│       │               │   ├── MicroPythonAction.kt
│       │               │   ├── MicroPythonCommandAction.kt
│       │               │   ├── RemoveAllFilesFromDeviceAction.kt
│       │               │   └── RunMicroReplAction.kt
│       │               ├── devices/
│       │               │   ├── Esp8266DeviceProvider.kt
│       │               │   ├── MicroBitDeviceProvider.kt
│       │               │   ├── MicroBitV2DeviceProvider.kt
│       │               │   ├── MicroPythonDeviceProvider.kt
│       │               │   ├── PyboardDeviceProvider.kt
│       │               │   └── RPiPicoDeviceProvider.kt
│       │               ├── inspections/
│       │               │   └── MicroPythonRequirementsInspection.kt
│       │               ├── repl/
│       │               │   ├── MicroPythonReplManager.kt
│       │               │   ├── StopReplBeforeRunTask.kt
│       │               │   └── ToolWindowReplTab.kt
│       │               ├── run/
│       │               │   ├── MicroPythonConfigurationType.kt
│       │               │   ├── MicroPythonRunConfiguration.kt
│       │               │   ├── MicroPythonRunConfigurationEditor.kt
│       │               │   ├── MicroPythonRunConfigurationProducer.kt
│       │               │   └── MicroUpload.kt
│       │               ├── settings/
│       │               │   ├── MicroPythonDevicesConfiguration.kt
│       │               │   ├── MicroPythonFacet.kt
│       │               │   ├── MicroPythonFacetConfiguration.kt
│       │               │   ├── MicroPythonFacetDetector.kt
│       │               │   ├── MicroPythonFacetEditorTab.kt
│       │               │   ├── MicroPythonFacetType.kt
│       │               │   ├── MicroPythonModuleConfigurable.kt
│       │               │   ├── MicroPythonProjectConfigurable.kt
│       │               │   ├── MicroPythonSettingsPanel.kt
│       │               │   ├── MicroPythonTypeHints.kt
│       │               │   └── MicroPythonUsbId.kt
│       │               └── ui/
│       │                   └── MicroPythonToolWindowFactory.kt
│       └── resources/
│           ├── META-INF/
│           │   └── plugin.xml
│           └── inspectionDescriptions/
│               └── MicroPythonRequirements.html
└── typehints/
    ├── esp32/
    │   ├── esp.pyi
    │   ├── esp32.pyi
    │   └── network.pyi
    ├── esp8266/
    │   ├── esp.pyi
    │   └── network.pyi
    ├── microbit/
    │   ├── microbit/
    │   │   ├── __init__.pyi
    │   │   ├── accelerometer.pyi
    │   │   ├── compass.pyi
    │   │   ├── display.pyi
    │   │   ├── i2c.pyi
    │   │   ├── spi.pyi
    │   │   └── uart.pyi
    │   ├── music.pyi
    │   ├── neopixel.pyi
    │   ├── radio.pyi
    │   └── speech.pyi
    ├── micropython/
    │   ├── bluetooth.pyi
    │   ├── btree.pyi
    │   ├── cryptolib.pyi
    │   ├── framebuf.pyi
    │   ├── machine.pyi
    │   ├── micropython.pyi
    │   ├── neopixel.pyi
    │   ├── network.pyi
    │   ├── ubluetooth.pyi
    │   ├── ucryptolib.pyi
    │   └── uctypes.pyi
    ├── pyboard/
    │   ├── lcd160cr.pyi
    │   ├── pyb.pyi
    │   └── stm.pyi
    ├── rpi_pico/
    │   └── rp2.pyi
    └── stdlib/
        ├── _thread.pyi
        ├── array.pyi
        ├── binascii.pyi
        ├── cmath.pyi
        ├── collections.pyi
        ├── errno.pyi
        ├── gc.pyi
        ├── hashlib.pyi
        ├── heapq.pyi
        ├── io.pyi
        ├── json.pyi
        ├── math.pyi
        ├── os.pyi
        ├── re.pyi
        ├── select.pyi
        ├── socket.pyi
        ├── ssl.pyi
        ├── struct.pyi
        ├── sys.pyi
        ├── time.pyi
        ├── uarray.pyi
        ├── uasyncio.pyi
        ├── ubinascii.pyi
        ├── ucollections.pyi
        ├── uerrno.pyi
        ├── uhashlib.pyi
        ├── uheapq.pyi
        ├── uio.pyi
        ├── ujson.pyi
        ├── uos.pyi
        ├── ure.pyi
        ├── uselect.pyi
        ├── usocket.pyi
        ├── ussl.pyi
        ├── ustruct.pyi
        ├── usys.pyi
        ├── utime.pyi
        ├── uzlib.pyi
        └── zlib.pyi
Download .txt
SYMBOL INDEX (1409 symbols across 72 files)

FILE: examples/rpsls.py
  function sketch_to_image (line 67) | def sketch_to_image(sketch):
  function parse_story (line 74) | def parse_story(story):
  function random_outcome (line 85) | def random_outcome():
  function expired (line 89) | def expired(time):
  function beats (line 93) | def beats(actor, victim):
  function wait_for_outcome (line 97) | def wait_for_outcome():
  function main (line 105) | def main():

FILE: scripts/findusb.py
  function main (line 25) | def main() -> None:

FILE: scripts/microcleanfs.py
  function main (line 36) | def main(args: List[str]) -> None:
  function wait_for_board (line 65) | def wait_for_board() -> None:

FILE: scripts/microrepl.py
  function character (line 38) | def character(b):
  function character (line 41) | def character(b):
  function connect_miniterm (line 45) | def connect_miniterm(port):
  function main (line 78) | def main():

FILE: scripts/microupload.py
  function main (line 44) | def main(args: List[str]) -> None:
  function make_dirs (line 85) | def make_dirs(files: Files, path: str,
  function soft_reset (line 101) | def soft_reset(board: Pyboard) -> None:
  function list_files (line 106) | def list_files(path: str, excluded: List[str]) -> Iterable[str]:
  function wait_for_board (line 119) | def wait_for_board() -> None:
  function progress (line 124) | def progress(msg: str, xs: Sequence[T]) -> Iterable[T]:

FILE: typehints/esp32/esp.pyi
  function flash_size (line 11) | def flash_size():
  function flash_user_start (line 15) | def flash_user_start():
  function flash_read (line 19) | def flash_read(byte_offset, length_or_buffer):
  function flash_write (line 22) | def flash_write(byte_offset, bytes):
  function flash_erase (line 25) | def flash_erase(sector_no):
  function osdebug (line 28) | def osdebug(level: Optional[int]):

FILE: typehints/esp32/esp32.pyi
  function wake_on_touch (line 18) | def wake_on_touch(wake: bool):
  function wake_on_ulp (line 23) | def wake_on_ulp(wake: bool):
  function wake_on_ext0 (line 28) | def wake_on_ext0(pin: Pin, level: Optional[int]):
  function wake_on_ext1 (line 36) | def wake_on_ext1(pin: Pin, level: Optional[int]):
  function gpio_deep_sleep_hold (line 44) | def gpio_deep_sleep_hold(enable: bool):
  function raw_temperature (line 49) | def raw_temperature() -> int:
  function hall_sensor (line 54) | def hall_sensor() -> int:
  function idf_heap_info (line 59) | def idf_heap_info(capabilities: Optional[int]) -> list:
  class Partition (line 75) | class Partition:
    method __init__ (line 99) | def __init__(self, id: str, block_size=4096, /):
    method find (line 109) | def find(self, type=TYPE_APP, subtype=0xFF, label=None, block_size=409...
    method info (line 119) | def info(self) -> tuple:
    method readblocks (line 125) | def readblocks(self, block_num, buf): ...
    method readblocks (line 127) | def readblocks(self, block_num, buf, offset): ...
    method writeblocks (line 129) | def writeblocks(self, block_num, buf): ...
    method writeblocks (line 131) | def writeblocks(self, block_num, buf, offset): ...
    method ioctl (line 133) | def ioctl(self, cmd, arg):
    method set_boot (line 136) | def set_boot(self):
    method get_next_update (line 139) | def get_next_update(self):
    method mark_app_valid_cancel_rollback (line 148) | def mark_app_valid_cancel_rollback(self):
  class RMT (line 157) | class RMT:
    method __init__ (line 165) | def __init__(self, channel: int, *, pin=None, clock_div=8, idle_level=...
    method source_freq (line 177) | def source_freq(self):
    method clock_div (line 183) | def clock_div(self):
    method wait_done (line 188) | def wait_done(self, *, timeout=0):
    method loop (line 197) | def loop(self, enable_loop: bool):
    method write_pulses (line 206) | def write_pulses(self, duration, data=True):
    method bitstream_channel (line 232) | def bitstream_channel(value: Optional[int]) -> int:
  class ULP (line 243) | class ULP:
    method set_wakeup_period (line 246) | def set_wakeup_period(self, period_index: int, period_us):
    method load_binary (line 249) | def load_binary(self, load_addr, program_binary):
    method run (line 252) | def run(self, entry_point):
  class NVS (line 255) | class NVS:
    method __init__ (line 262) | def __init__(self, namespace: str):
    method set_i32 (line 265) | def set_i32(self, key, value):
    method get_i32 (line 268) | def get_i32(self, key):
    method set_blob (line 274) | def set_blob(self, key, value):
    method get_blob (line 281) | def get_blob(self, key, buffer):
    method erase_key (line 288) | def erase_key(self, key):
    method commit (line 291) | def commit(self):

FILE: typehints/esp32/network.pyi
  function phy_mode (line 40) | def phy_mode() -> int:
  function phy_mode (line 46) | def phy_mode(mode: int) -> None:
  class WLAN (line 57) | class WLAN:
    method __init__ (line 58) | def __init__(self, interface_id: int) -> None:
    method active (line 68) | def active(self) -> bool:
    method active (line 73) | def active(self, is_active: bool) -> None:
    method connect (line 77) | def connect(self, ssid: Optional[Union[bytes, str]] = None,
    method disconnect (line 87) | def disconnect(self) -> None:
    method scan (line 91) | def scan(self) -> List[Tuple[bytes, bytes, int, int, int, int]]:
    method status (line 117) | def status(self) -> int:
    method isconnected (line 131) | def isconnected(self) -> bool:
    method ifconfig (line 139) | def ifconfig(self) -> Tuple[str, str, str, str]:
    method ifconfig (line 146) | def ifconfig(self, ip: str, subnet: str, gateway: str, dns: str) -> None:
    method config (line 153) | def config(self, param: str) -> Any:
    method config (line 158) | def config(self, **kwargs: Any) -> None:

FILE: typehints/esp8266/esp.pyi
  function sleep_type (line 4) | def sleep_type(sleep_type: Optional[int]) -> Optional[int]:
  function deepsleep (line 24) | def deepsleep(time: int = 0) -> None:
  function set_native_code_location (line 35) | def set_native_code_location(start: Optional[int], length: Optional[int]...

FILE: typehints/esp8266/network.pyi
  function phy_mode (line 40) | def phy_mode() -> int:
  function phy_mode (line 46) | def phy_mode(mode: int) -> None:
  class WLAN (line 57) | class WLAN:
    method __init__ (line 58) | def __init__(self, interface_id: int) -> None:
    method active (line 68) | def active(self) -> bool:
    method active (line 73) | def active(self, is_active: bool) -> None:
    method connect (line 77) | def connect(self, ssid: Optional[Union[bytes, str]] = None,
    method disconnect (line 87) | def disconnect(self) -> None:
    method scan (line 91) | def scan(self) -> List[Tuple[bytes, bytes, int, int, int, int]]:
    method status (line 117) | def status(self) -> int:
    method isconnected (line 131) | def isconnected(self) -> bool:
    method ifconfig (line 139) | def ifconfig(self) -> Tuple[str, str, str, str]:
    method ifconfig (line 146) | def ifconfig(self, ip: str, subnet: str, gateway: str, dns: str) -> None:
    method config (line 153) | def config(self, param: str) -> Any:
    method config (line 158) | def config(self, **kwargs: Any) -> None:

FILE: typehints/microbit/microbit/__init__.pyi
  function panic (line 37) | def panic(n: int) -> None:
  function reset (line 45) | def reset() -> None:
  function sleep (line 49) | def sleep(n: int) -> None:
  function running_time (line 59) | def running_time() -> int:
  function temperature (line 65) | def temperature() -> int:
  class Button (line 69) | class Button:
    method is_pressed (line 77) | def is_pressed(self) -> bool:
    method was_pressed (line 82) | def was_pressed(self) -> bool:
    method get_presses (line 87) | def get_presses(self) -> int:
  class MicroBitDigitalPin (line 100) | class MicroBitDigitalPin:
    method read_digital (line 113) | def read_digital(self) -> int:
    method set_pull (line 116) | def set_pull(self, value: int = (NO_PULL or PULL_UP or PULL_DOWN)) -> ...
    method write_digital (line 122) | def write_digital(self, value: int) -> None:
    method write_analog (line 125) | def write_analog(self, value: int) -> None:
    method set_analog_period (line 131) | def set_analog_period(self, period: int) -> None:
    method set_analog_period_microseconds (line 136) | def set_analog_period_microseconds(self, period: int) -> None:
  class MicroBitAnalogDigitalPin (line 141) | class MicroBitAnalogDigitalPin(MicroBitDigitalPin):
    method read_analog (line 142) | def read_analog(self) -> int:
  class MicroBitTouchPin (line 147) | class MicroBitTouchPin(MicroBitAnalogDigitalPin):
    method is_touched (line 148) | def is_touched(self) -> bool:
  class Image (line 213) | class Image:
    method __init__ (line 289) | def __init__(self, string: str) -> None:
    method __init__ (line 311) | def __init__(self, width: int = None, height: int = None,
    method width (line 318) | def width(self) -> int:
    method height (line 321) | def height(self) -> int:
    method set_pixel (line 324) | def set_pixel(self, x: int, y: int, value: int) -> None:
    method get_pixel (line 332) | def get_pixel(self, x: int, y: int) -> int:
    method shift_left (line 337) | def shift_left(self, n: int) -> Image:
    method shift_right (line 342) | def shift_right(self, n: int) -> Image:
    method shift_up (line 345) | def shift_up(self, n: int) -> Image:
    method shift_down (line 350) | def shift_down(self, n: int) -> Image:
    method crop (line 353) | def crop(self, x: int, y: int, w: int, h: int) -> Image:
    method copy (line 359) | def copy(self) -> Image:
    method invert (line 362) | def invert(self) -> Image:
    method fill (line 366) | def fill(self, value: int) -> None:
    method blit (line 374) | def blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int ...
    method __repr__ (line 392) | def __repr__(self) -> str:
    method __str__ (line 395) | def __str__(self) -> str:
    method __add__ (line 398) | def __add__(self, other: Image) -> Image:
    method __mul__ (line 403) | def __mul__(self, n: float) -> Image:

FILE: typehints/microbit/microbit/accelerometer.pyi
  function get_x (line 11) | def get_x() -> int:
  function get_y (line 17) | def get_y() -> int:
  function get_z (line 23) | def get_z() -> int:
  function get_values (line 29) | def get_values() -> Tuple[int, int, int]:
  function current_gesture (line 35) | def current_gesture() -> str:
  function is_gesture (line 46) | def is_gesture(name: str) -> bool:
  function was_gesture (line 51) | def was_gesture(name: str) -> bool:
  function get_gestures (line 57) | def get_gestures() -> Tuple[str, ...]:

FILE: typehints/microbit/microbit/compass.pyi
  function calibrate (line 12) | def calibrate() -> None:
  function is_calibrated (line 19) | def is_calibrated() -> bool:
  function clear_calibration (line 25) | def clear_calibration() -> None:
  function get_x (line 29) | def get_x() -> int:
  function get_y (line 36) | def get_y() -> int:
  function get_z (line 43) | def get_z() -> int:
  function heading (line 50) | def heading() -> int:
  function get_field_strength (line 58) | def get_field_strength() -> int:

FILE: typehints/microbit/microbit/display.pyi
  function get_pixel (line 15) | def get_pixel(x: int, y: int) -> int:
  function set_pixel (line 20) | def set_pixel(x: int, y: int, value: int) -> None:
  function clear (line 25) | def clear() -> None:
  function show (line 30) | def show(image: Image) -> None:
  function show (line 35) | def show(iterable: Iterable[Image, str], delay: int = 400, *,
  function scroll (line 59) | def scroll(string: str, delay: int = 150, *, wait: bool = True,
  function on (line 78) | def on() -> None:
  function off (line 82) | def off() -> None:
  function is_on (line 88) | def is_on() -> bool:

FILE: typehints/microbit/microbit/i2c.pyi
  function init (line 30) | def init(freq: int = 100000, sda: int = pin20, scl: int = pin19) -> None:
  function read (line 41) | def read(addr: int, n: int, repeat: bool = False) -> bytes:
  function write (line 47) | def write(addr: int, buf: Union[bytes, bytearray], repeat=False) -> None:

FILE: typehints/microbit/microbit/spi.pyi
  function init (line 16) | def init(baudrate: int = 1000000, bits: int = 8, mode: int = 0,
  function read (line 57) | def read(nbytes: int) -> bytes:
  function write (line 61) | def write(buffer: Union[bytes, bytearray]) -> None:
  function write_readinto (line 65) | def write_readinto(out: Union[bytes, bytearray], in_: bytearray) -> None:

FILE: typehints/microbit/microbit/uart.pyi
  function init (line 9) | def init(baudrate: int = 9600, bits: int = 8, parity: int = None,
  function any (line 55) | def any() -> bool:
  function read (line 59) | def read(nbytes: int = None) -> bytes:
  function readall (line 64) | def readall() -> Optional[bytes]:
  function readinto (line 71) | def readinto(buf: bytearray, nbytes: int = None) -> Optional[int]:
  function readline (line 80) | def readline() -> Optional[bytes]:
  function write (line 87) | def write(buf: Union[bytes, bytearray]) -> Optional[int]:

FILE: typehints/microbit/music.pyi
  function set_tempo (line 148) | def set_tempo(ticks: int = 4, bpm: int = 120) -> None:
  function get_tempo (line 169) | def get_tempo(self) -> Tuple[int, int]:
  function play (line 175) | def play(music: Union[str, List[str]],
  function pitch (line 197) | def pitch(frequency: int, len=-1, pin: MicroBitAnalogDigitalPin = pin0,
  function stop (line 213) | def stop(pin: MicroBitAnalogDigitalPin = pin0) -> None:
  function reset (line 219) | def reset() -> None:

FILE: typehints/microbit/neopixel.pyi
  function NeoPixel (line 82) | def NeoPixel(pin: MicroBitAnalogDigitalPin, n: int)-> None:
  function clear (line 91) | def clear()->None:
  function show (line 96) | def show()->None:

FILE: typehints/microbit/radio.pyi
  function on (line 37) | def on() -> None:
  function off (line 43) | def off() -> None:
  function config (line 47) | def config(length: int = 32, queue: int = 3, channel: int = 7,
  function reset (line 92) | def reset() -> None:
  function send_bytes (line 98) | def send_bytes(message: bytes) -> None:
  function receive_bytes (line 102) | def receive_bytes() -> Optional[bytes]:
  function receive_bytes_into (line 108) | def receive_bytes_into(buffer: bytearray) -> Optional[int]:
  function send (line 116) | def send(message: str) -> None:
  function receive (line 124) | def receive() -> Optional[str]:

FILE: typehints/microbit/speech.pyi
  function translate (line 42) | def translate(words: str) ->None:
  function pronounce (line 52) | def pronounce(phonemes: str, pitch: int=64, speed: int=72,
  function say (line 61) | def say(words: str, pitch: int=64, speed: int=72,
  function sing (line 71) | def sing(phonemes: str, pitch: int=64, speed: int=72,

FILE: typehints/micropython/bluetooth.pyi
  class BLE (line 30) | class BLE:
    method __init__ (line 36) | def __init__(self):
    method active (line 41) | def active(self) -> bool:
    method active (line 49) | def active(self, active: bool, /) -> None:
    method config (line 57) | def config(self, param: str, /) -> Any:
    method config (line 120) | def config(self, **kwargs) -> None:
    method irq (line 182) | def irq(self, handler: Callable[[int, tuple[memoryview, ...]], Any], /...
    method gap_advertise (line 376) | def gap_advertise(
    method gap_scan (line 399) | def gap_scan(
    method gap_connect (line 440) | def gap_connect(
    method gap_disconnect (line 472) | def gap_disconnect(self, conn_handle: memoryview, /) -> bool:
    method gatts_register_services (line 509) | def gatts_register_services(
    method gatts_read (line 596) | def gatts_read(self, value_handle: memoryview, /) -> bytes:
    method gatts_write (line 625) | def gatts_write(
    method gatts_notify (line 659) | def gatts_notify(self, value_handle: memoryview, data: bytes, /) -> None:
    method gatts_indicate (line 696) | def gatts_indicate(
    method gatts_set_buffer (line 733) | def gatts_set_buffer(
    method gattc_discover_services (line 770) | def gattc_discover_services(
    method gattc_discover_characteristics (line 792) | def gattc_discover_characteristics(
    method gattc_discover_descriptors (line 823) | def gattc_discover_descriptors(
    method gattc_read (line 843) | def gattc_read(self, conn_handle: memoryview, value_handle: memoryview...
    method gattc_write (line 862) | def gattc_write(
    method gattc_exchange_mtu (line 898) | def gattc_exchange_mtu(self, conn_handle: memoryview, /) -> None:
    method l2cap_listen (line 922) | def l2cap_listen(self, psm: memoryview, mtu: memoryview, /) -> None:
    method l2cap_connect (line 958) | def l2cap_connect(
    method l2cap_disconnect (line 991) | def l2cap_disconnect(self, conn_handle: memoryview, cid: memoryview, /...
    method l2cap_send (line 1017) | def l2cap_send(self, conn_handle: memoryview, cid: memoryview, /) -> N...
    method l2cap_recvinto (line 1052) | def l2cap_recvinto(
    method gap_pair (line 1094) | def gap_pair(self, conn_handle: memoryview, /) -> None:
    method gap_passkey (line 1119) | def gap_passkey(
  class UUID (line 1155) | class UUID:
    method __init__ (line 1161) | def __init__(self, value: int | str, /):

FILE: typehints/micropython/btree.pyi
  function open (line 89) | def open(
  class _BTree (line 134) | class _BTree:
    method close (line 139) | def close(self) -> None:
    method flush (line 147) | def flush(self) -> None:
    method __getitem__ (line 151) | def __getitem__(self, key: bytes, /) -> bytes:
    method get (line 155) | def get(self, key: bytes, default: bytes | None = None, /) -> bytes | ...
    method __setitem__ (line 159) | def __setitem__(self, key: bytes, val: bytes, /) -> None:
    method __delitem__ (line 163) | def __delitem__(self, key: bytes, /) -> None:
    method __contains__ (line 167) | def __contains__(self, key: bytes, /) -> bool:
    method __iter__ (line 171) | def __iter__(self) -> Iterable[bytes]:
    method keys (line 176) | def keys(
    method values (line 197) | def values(
    method items (line 218) | def items(

FILE: typehints/micropython/cryptolib.pyi
  class aes (line 22) | class aes:
    method __init__ (line 28) | def __init__(self, key: AnyReadableBuf, mode: int, /):
    method __init__ (line 48) | def __init__(self, key: AnyReadableBuf, mode: int, IV: AnyReadableBuf,...
    method encrypt (line 68) | def encrypt(self, in_buf: AnyReadableBuf, /) -> bytes:
    method encrypt (line 76) | def encrypt(self, in_buf: AnyReadableBuf, out_buf: AnyWritableBuf, /) ...
    method decrypt (line 84) | def decrypt(self, in_buf: AnyReadableBuf, /) -> bytes:
    method decrypt (line 89) | def decrypt(self, in_buf: AnyReadableBuf, out_buf: AnyWritableBuf, /) ...

FILE: typehints/micropython/framebuf.pyi
  class FrameBuffer (line 70) | class FrameBuffer:
    method __init__ (line 88) | def __init__(
    method fill (line 121) | def fill(self, c: int, /) -> None:
    method pixel (line 126) | def pixel(self, x: int, y: int, /) -> int:
    method pixel (line 132) | def pixel(self, x: int, y: int, c: int, /) -> None:
    method hline (line 137) | def hline(self, x: int, y: int, w: int, c: int, /) -> None:
    method vline (line 145) | def vline(self, x: int, y: int, h: int, c: int, /) -> None:
    method line (line 153) | def line(self, x1: int, y1: int, x2: int, y2: int, c: int, /) -> None:
    method rect (line 161) | def rect(self, x: int, y: int, w: int, h: int, c: int, /) -> None:
    method fill_rect (line 167) | def fill_rect(self, x: int, y: int, w: int, h: int, c: int, /) -> None:
    method text (line 173) | def text(self, s: str, x: int, y: int, c: int = 1, /) -> None:
    method scroll (line 180) | def scroll(self, xstep: int, ystep: int, /) -> None:
    method blit (line 185) | def blit(

FILE: typehints/micropython/machine.pyi
  function reset (line 40) | def reset() -> NoReturn:
  function soft_reset (line 46) | def soft_reset() -> NoReturn:
  function reset_cause (line 53) | def reset_cause() -> int:
  function disable_irq (line 58) | def disable_irq() -> bool:
  function enable_irq (line 66) | def enable_irq(state: bool = True, /) -> None:
  function freq (line 74) | def freq() -> int:
  function freq (line 82) | def freq(hz: int, /) -> None:
  function idle (line 89) | def idle() -> None:
  function sleep (line 97) | def sleep() -> None:
  function lightsleep (line 103) | def lightsleep() -> None:
  function lightsleep (line 128) | def lightsleep(time_ms: int, /) -> None:
  function deepsleep (line 153) | def deepsleep() -> NoReturn:
  function deepsleep (line 178) | def deepsleep(time_ms: int, /) -> NoReturn:
  function wake_reason (line 202) | def wake_reason() -> int:
  function unique_id (line 209) | def unique_id() -> bytes:
  function time_pulse_us (line 217) | def time_pulse_us(pin: Pin, pulse_level: int, timeout_us: int = 1_000_00...
  function rng (line 234) | def rng() -> int:
  class Pin (line 296) | class Pin:
    method __init__ (line 411) | def __init__(
    method init (line 482) | def init(
    method value (line 499) | def value(self) -> int:
    method value (line 532) | def value(self, x: Any, /) -> None:
    method __call__ (line 565) | def __call__(self) -> int:
    method __call__ (line 572) | def __call__(self, x: Any, /) -> None:
    method on (line 578) | def on(self) -> None:
    method off (line 582) | def off(self) -> None:
    method irq (line 586) | def irq(
    method low (line 636) | def low(self) -> None:
    method high (line 642) | def high(self) -> None:
    method mode (line 649) | def mode(self) -> int:
    method mode (line 657) | def mode(self, mode: int, /) -> None:
    method pull (line 665) | def pull(self) -> int:
    method pull (line 673) | def pull(self, pull: int, /) -> None:
    method drive (line 681) | def drive(self) -> int:
    method drive (line 689) | def drive(self, drive: int, /) -> None:
  class Signal (line 697) | class Signal:
    method __init__ (line 768) | def __init__(self, pin_obj: Pin, invert: bool = False, /):
    method __init__ (line 787) | def __init__(
    method value (line 817) | def value(self) -> int:
    method value (line 836) | def value(self, x: Any, /) -> None:
    method on (line 854) | def on(self) -> None:
    method off (line 858) | def off(self) -> None:
  class ADC (line 863) | class ADC:
    method __init__ (line 877) | def __init__(self, pin: int | Pin, /):
    method read_u16 (line 884) | def read_u16(self) -> int:
  class PWM (line 892) | class PWM:
    method __init__ (line 911) | def __init__(
    method init (line 935) | def init(self, *, freq: int = ..., duty_u16: int = ..., duty_ns: int =...
    method deinit (line 940) | def deinit(self) -> None:
    method freq (line 945) | def freq(self) -> int:
    method freq (line 955) | def freq(self, value: int, /,) -> None:
    method duty_u16 (line 965) | def duty_u16(self) -> int:
    method duty_u16 (line 976) | def duty_u16(self, value: int, /,) -> None:
    method duty_ns (line 987) | def duty_ns(self) -> int:
    method duty_ns (line 996) | def duty_ns(self, value: int, /,) -> None:
  class UART (line 1005) | class UART:
    method __init__ (line 1044) | def __init__(
    method __init__ (line 1065) | def __init__(
    method __init__ (line 1080) | def __init__(
    method init (line 1095) | def init(
    method init (line 1149) | def init(
    method init (line 1197) | def init(
    method deinit (line 1244) | def deinit(self) -> None:
    method any (line 1248) | def any(self) -> int:
    method read (line 1262) | def read(self) -> bytes | None:
    method read (line 1272) | def read(self, nbytes: int, /) -> bytes | None:
    method readinto (line 1282) | def readinto(self, buf: AnyWritableBuf, /) -> int | None:
    method readinto (line 1292) | def readinto(self, buf: AnyWritableBuf, nbytes: int, /) -> int | None:
    method readline (line 1301) | def readline(self) -> bytes | None:
    method write (line 1308) | def write(self, buf: AnyReadableBuf, /) -> int | None:
    method sendbreak (line 1314) | def sendbreak(self) -> None:
    method irq (line 1319) | def irq(
  class SPI (line 1352) | class SPI:
    method __init__ (line 1385) | def __init__(self, id: int, /):
    method __init__ (line 1397) | def __init__(
    method __init__ (line 1422) | def __init__(
    method init (line 1445) | def init(
    method init (line 1479) | def init(
    method deinit (line 1510) | def deinit(self) -> None:
    method read (line 1514) | def read(self, nbytes: int, write: int = 0x00, /) -> bytes:
    method readinto (line 1520) | def readinto(self, buf: AnyWritableBuf, write: int = 0x00, /) -> int |...
    method write (line 1528) | def write(self, buf: AnyReadableBuf, /) -> int | None:
    method write_readinto (line 1535) | def write_readinto(
  class I2C (line 1548) | class I2C:
    method __init__ (line 1586) | def __init__(self, id: int, /, *, freq: int = 400_000):
    method __init__ (line 1602) | def __init__(self, id: int, /, *, scl: Pin, sda: Pin, freq: int = 400_...
    method init (line 1618) | def init(self, *, freq: int = 400_000) -> None:
    method init (line 1627) | def init(self, *, scl: Pin, sda: Pin, freq: int = 400_000) -> None:
    method deinit (line 1635) | def deinit(self) -> None:
    method scan (line 1641) | def scan(self) -> list[int]:
    method start (line 1647) | def start(self) -> None:
    method stop (line 1661) | def stop(self) -> None:
    method readinto (line 1675) | def readinto(self, buf: AnyWritableBuf, nack: bool = True, /) -> None:
    method write (line 1693) | def write(self, buf: AnyReadableBuf, /) -> int:
    method readfrom (line 1709) | def readfrom(self, addr: int, nbytes: int, stop: bool = True, /) -> by...
    method readfrom_into (line 1722) | def readfrom_into(
    method writeto (line 1739) | def writeto(self, addr: int, buf: AnyReadableBuf, stop: bool = True, /...
    method writevto (line 1754) | def writevto(
    method readfrom_mem (line 1777) | def readfrom_mem(
    method readfrom_mem_into (line 1795) | def readfrom_mem_into(
    method writeto_mem (line 1816) | def writeto_mem(
  class I2S (line 1836) | class I2S:
    method __init__ (line 1926) | def __init__(
    method init (line 1967) | def init(
    method deinit (line 1982) | def deinit(self) -> None:
    method readinto (line 1986) | def readinto(self, buf: AnyWritableBuf, /,) -> int:
    method write (line 1993) | def write(self, buf: AnyReadableBuf, /,) -> int:
    method irq (line 2000) | def irq(self, handler: Callable[[], None], /,) -> None:
    method shift (line 2007) | def shift(buf: AnyWritableBuf, bits: int, shift: int, /,) -> None:
  class RTC (line 2014) | class RTC:
    method __init__ (line 2036) | def __init__(self, id: int = 0, /, *, datetime: tuple[int, int, int]):
    method __init__ (line 2043) | def __init__(self, id: int = 0, /, *, datetime: tuple[int, int, int, i...
    method __init__ (line 2050) | def __init__(self, id: int = 0, /, *, datetime: tuple[int, int, int, i...
    method __init__ (line 2057) | def __init__(
    method __init__ (line 2066) | def __init__(
    method __init__ (line 2075) | def __init__(
    method init (line 2084) | def init(self) -> None:
    method init (line 2093) | def init(self, datetime: tuple[int, int, int], /) -> None:
    method init (line 2102) | def init(self, datetime: tuple[int, int, int, int], /) -> None:
    method init (line 2111) | def init(self, datetime: tuple[int, int, int, int, int], /) -> None:
    method init (line 2120) | def init(self, datetime: tuple[int, int, int, int, int, int], /) -> None:
    method init (line 2129) | def init(self, datetime: tuple[int, int, int, int, int, int, int], /) ...
    method init (line 2138) | def init(self, datetime: tuple[int, int, int, int, int, int, int, int]...
    method now (line 2146) | def now(self) -> tuple[int, int, int, int, int, int, int, int]:
    method deinit (line 2152) | def deinit(self) -> None:
    method alarm (line 2159) | def alarm(self, id: int, time: int, /, *, repeat: bool = False) -> None:
    method alarm (line 2168) | def alarm(self, id: int, time: tuple[int, int, int], /) -> None:
    method alarm (line 2177) | def alarm(self, id: int, time: tuple[int, int, int, int], /) -> None:
    method alarm (line 2186) | def alarm(self, id: int, time: tuple[int, int, int, int, int], /) -> N...
    method alarm (line 2195) | def alarm(self, id: int, time: tuple[int, int, int, int, int, int], /)...
    method alarm (line 2204) | def alarm(self, id: int, time: tuple[int, int, int, int, int, int, int...
    method alarm (line 2213) | def alarm(
    method alarm_left (line 2223) | def alarm_left(self, alarm_id: int = 0, /) -> int:
    method cancel (line 2229) | def cancel(self, alarm_id: int = 0, /) -> None:
    method irq (line 2235) | def irq(
  class Timer (line 2252) | class Timer:
    method __init__ (line 2285) | def __init__(self, id: int, /):
    method __init__ (line 2293) | def __init__(
    method init (line 2308) | def init(
    method deinit (line 2330) | def deinit(self) -> None:
  class WDT (line 2335) | class WDT:
    method __init__ (line 2351) | def __init__(self, *, id: int = 0, timeout: int = 5000):
    method feed (line 2359) | def feed(self) -> None:
  class SD (line 2366) | class SD:
    method __init__ (line 2392) | def __init__(
    method init (line 2401) | def init(
    method deinit (line 2411) | def deinit(self) -> None:
  class SDCard (line 2417) | class SDCard(AbstractBlockDev):
    method __init__ (line 2510) | def __init__(

FILE: typehints/micropython/micropython.pyi
  function native (line 22) | def native(func: _F) -> _F:
  function viper (line 30) | def viper(func: _F) -> _F:
  function const (line 38) | def const(expr: _T, /) -> _T:
  function opt_level (line 60) | def opt_level() -> int:
  function opt_level (line 80) | def opt_level(level: int, /) -> None:
  function alloc_emergency_exception_buf (line 99) | def alloc_emergency_exception_buf(size: int, /) -> None:
  function mem_info (line 112) | def mem_info() -> None:
  function mem_info (line 123) | def mem_info(verbose: Any, /) -> None:
  function qstr_info (line 134) | def qstr_info() -> None:
  function qstr_info (line 145) | def qstr_info(verbose: bool, /) -> None:
  function stack_use (line 155) | def stack_use() -> int:
  function heap_lock (line 162) | def heap_lock() -> None:
  function heap_unlock (line 183) | def heap_unlock() -> None:
  function heap_locked (line 204) | def heap_locked() -> bool:
  function kbd_intr (line 225) | def kbd_intr(chr: int) -> None:
  function schedule (line 237) | def schedule(func: Callable[[_T], None], arg: _T, /) -> None:

FILE: typehints/micropython/neopixel.pyi
  class NeoPixel (line 30) | class NeoPixel:
    method __init__ (line 52) | def __init__(self, pin: Pin, n: int, /, *, bpp: int = 3, timing: int =...
    method fill (line 61) | def fill(self, pixel: _Color, /) -> None:
    method __len__ (line 66) | def __len__(self) -> int:
    method __setitem__ (line 70) | def __setitem__(self, index: int, val: _Color, /) -> None:
    method __getitem__ (line 74) | def __getitem__(self, index: int, /) -> _Color:
    method write (line 78) | def write(self) -> None:

FILE: typehints/micropython/network.pyi
  function country (line 54) | def country() -> str:
  function country (line 63) | def country(code: str) -> None:
  function hostname (line 72) | def hostname() -> str:
  function hostname (line 84) | def hostname(name: str) -> None:
  function phy_mode (line 150) | def phy_mode() -> int:
  function phy_mode (line 166) | def phy_mode(mode: int, /) -> None:
  class AbstractNIC (line 181) | class AbstractNIC(Protocol):
    method __init__ (line 194) | def __init__(self, id: Any = None, /, *args: Any, **kwargs: Any):
    method active (line 202) | def active(self, /) -> bool:
    method active (line 212) | def active(self, is_active: bool, /) -> None:
    method connect (line 222) | def connect(self, key: str | None = None, /, **kwargs: Any) -> None:
    method connect (line 240) | def connect(
    method disconnect (line 259) | def disconnect(self) -> None:
    method isconnected (line 264) | def isconnected(self) -> bool:
    method scan (line 269) | def scan(self, **kwargs: Any) -> list[tuple[str, ...]]:
    method status (line 287) | def status(self) -> Any:
    method status (line 304) | def status(self, param: str, /) -> Any:
    method ifconfig (line 321) | def ifconfig(self) -> tuple[str, str, str, str]:
    method ifconfig (line 332) | def ifconfig(self, ip_mask_gateway_dns: tuple[str, str, str, str], /) ...
    method config (line 343) | def config(self, param: str, /) -> Any:
    method config (line 361) | def config(self, **kwargs: Any) -> None:
  class WLAN (line 378) | class WLAN:
    method __init__ (line 390) | def __init__(self, interface_id: int, /):
    method active (line 399) | def active(self, /) -> bool:
    method active (line 406) | def active(self, is_active: bool, /) -> None:
    method connect (line 412) | def connect(
    method disconnect (line 426) | def disconnect(self) -> None:
    method scan (line 430) | def scan(self) -> tuple[str, bytes, int, int, int]:
    method status (line 458) | def status(self) -> int:
    method status (line 476) | def status(self, param: str, /) -> int:
    method isconnected (line 493) | def isconnected(self) -> bool:
    method ifconfig (line 500) | def ifconfig(self) -> tuple[str, str, str, str]:
    method ifconfig (line 510) | def ifconfig(self, ip_mask_gateway_dns: tuple[str, str, str, str], /) ...
    method config (line 520) | def config(self, param: str, /) -> Any:
    method config (line 552) | def config(self, **kwargs: Any) -> None:
  class WLANWiPy (line 584) | class WLANWiPy:
    method __init__ (line 643) | def __init__(self, id: int = 0, /):
    method __init__ (line 656) | def __init__(
    method init (line 678) | def init(
    method connect (line 713) | def connect(
    method scan (line 734) | def scan(self) -> tuple[str, bytes, int, int | None, int]:
    method disconnect (line 739) | def disconnect(self) -> None:
    method isconnected (line 743) | def isconnected(self) -> bool:
    method ifconfig (line 749) | def ifconfig(self, if_id: int = 0, /) -> tuple[str, str, str, str]:
    method ifconfig (line 761) | def ifconfig(
    method mode (line 775) | def mode(self) -> int:
    method mode (line 780) | def mode(self, mode: int, /) -> None:
    method ssid (line 785) | def ssid(self) -> str:
    method ssid (line 790) | def ssid(self, ssid: str, /) -> None:
    method auth (line 795) | def auth(self) -> int:
    method auth (line 800) | def auth(self, auth: int, /) -> None:
    method channel (line 805) | def channel(self) -> int:
    method channel (line 810) | def channel(self, channel: int, /) -> None:
    method antenna (line 815) | def antenna(self) -> int:
    method antenna (line 820) | def antenna(self, antenna: int, /) -> None:
    method mac (line 825) | def mac(self) -> bytes:
    method mac (line 830) | def mac(self, mac: bytes, /) -> None:
    method irq (line 834) | def irq(self, *, handler: Callable[[], None], wake: int) -> Any:
  class CC3K (line 845) | class CC3K:
    method __init__ (line 885) | def __init__(
    method connect (line 905) | def connect(
    method disconnect (line 918) | def disconnect(self) -> None:
    method isconnected (line 922) | def isconnected(self) -> bool:
    method ifconfig (line 927) | def ifconfig(self) -> tuple[str, str, str, str, str, str, str]:
    method patch_version (line 932) | def patch_version(self) -> str:
    method patch_program (line 936) | def patch_program(self, cmd: str, /) -> None:
  class WIZNET5K (line 942) | class WIZNET5K:
    method __init__ (line 969) | def __init__(self, spi: pyb.SPI, pin_cs: pyb.Pin, pin_rst: pyb.Pin, /):
    method isconnected (line 986) | def isconnected(self) -> bool:
    method ifconfig (line 992) | def ifconfig(self) -> tuple[str, str, str, str]:
    method ifconfig (line 1003) | def ifconfig(self, config: tuple[str, str, str, str], /):
    method regs (line 1013) | def regs(self) -> Any:

FILE: typehints/micropython/ubluetooth.pyi
  class BLE (line 30) | class BLE:
    method __init__ (line 36) | def __init__(self):
    method active (line 41) | def active(self) -> bool:
    method active (line 49) | def active(self, active: bool, /) -> None:
    method config (line 57) | def config(self, param: str, /) -> Any:
    method config (line 120) | def config(self, **kwargs) -> None:
    method irq (line 182) | def irq(self, handler: Callable[[int, tuple[memoryview, ...]], Any], /...
    method gap_advertise (line 376) | def gap_advertise(
    method gap_scan (line 399) | def gap_scan(
    method gap_connect (line 440) | def gap_connect(
    method gap_disconnect (line 472) | def gap_disconnect(self, conn_handle: memoryview, /) -> bool:
    method gatts_register_services (line 509) | def gatts_register_services(
    method gatts_read (line 596) | def gatts_read(self, value_handle: memoryview, /) -> bytes:
    method gatts_write (line 625) | def gatts_write(
    method gatts_notify (line 659) | def gatts_notify(self, value_handle: memoryview, data: bytes, /) -> None:
    method gatts_indicate (line 696) | def gatts_indicate(
    method gatts_set_buffer (line 733) | def gatts_set_buffer(
    method gattc_discover_services (line 770) | def gattc_discover_services(
    method gattc_discover_characteristics (line 792) | def gattc_discover_characteristics(
    method gattc_discover_descriptors (line 823) | def gattc_discover_descriptors(
    method gattc_read (line 843) | def gattc_read(self, conn_handle: memoryview, value_handle: memoryview...
    method gattc_write (line 862) | def gattc_write(
    method gattc_exchange_mtu (line 898) | def gattc_exchange_mtu(self, conn_handle: memoryview, /) -> None:
    method l2cap_listen (line 922) | def l2cap_listen(self, psm: memoryview, mtu: memoryview, /) -> None:
    method l2cap_connect (line 958) | def l2cap_connect(
    method l2cap_disconnect (line 991) | def l2cap_disconnect(self, conn_handle: memoryview, cid: memoryview, /...
    method l2cap_send (line 1017) | def l2cap_send(self, conn_handle: memoryview, cid: memoryview, /) -> N...
    method l2cap_recvinto (line 1052) | def l2cap_recvinto(
    method gap_pair (line 1094) | def gap_pair(self, conn_handle: memoryview, /) -> None:
    method gap_passkey (line 1119) | def gap_passkey(
  class UUID (line 1155) | class UUID:
    method __init__ (line 1161) | def __init__(self, value: int | str, /):

FILE: typehints/micropython/ucryptolib.pyi
  class aes (line 22) | class aes:
    method __init__ (line 28) | def __init__(self, key: AnyReadableBuf, mode: int, /):
    method __init__ (line 48) | def __init__(self, key: AnyReadableBuf, mode: int, IV: AnyReadableBuf,...
    method encrypt (line 68) | def encrypt(self, in_buf: AnyReadableBuf, /) -> bytes:
    method encrypt (line 76) | def encrypt(self, in_buf: AnyReadableBuf, out_buf: AnyWritableBuf, /) ...
    method decrypt (line 84) | def decrypt(self, in_buf: AnyReadableBuf, /) -> bytes:
    method decrypt (line 89) | def decrypt(self, in_buf: AnyReadableBuf, out_buf: AnyWritableBuf, /) ...

FILE: typehints/micropython/uctypes.pyi
  function sizeof (line 223) | def sizeof(struct: struct | _descriptor, layout_type: int = NATIVE, /) -...
  function addressof (line 230) | def addressof(obj: AnyReadableBuf, /) -> int:
  function bytes_at (line 237) | def bytes_at(addr: int, size: int, /) -> bytes:
  function bytearray_at (line 245) | def bytearray_at(addr: int, size: int, /) -> bytearray:
  class struct (line 332) | class struct:
    method __init__ (line 338) | def __init__(

FILE: typehints/pyboard/lcd160cr.pyi
  class LCD160CR (line 73) | class LCD160CR:
    method __init__ (line 106) | def __init__(self, connect: str, /):
    method __init__ (line 142) | def __init__(self, *, pwr: Pin, i2c: I2C, spi: SPI, i2c_addr: int = 98):
    method rgb (line 178) | def rgb(r: int, g: int, b: int, /) -> int:
    method clip_line (line 186) | def clip_line(data: Any, w: int, h: int, /) -> int:
    method set_power (line 190) | def set_power(self, on: bool, /) -> None:
    method set_orient (line 195) | def set_orient(self, orient: str, /) -> None:
    method set_brightness (line 200) | def set_brightness(self, value: int, /) -> None:
    method set_i2c_addr (line 204) | def set_i2c_addr(self, addr: int, /) -> None:
    method set_uart_baudrate (line 209) | def set_uart_baudrate(self, baudrate: int, /) -> None:
    method set_startup_deco (line 213) | def set_startup_deco(self, value: bool | str, /) -> None:
    method save_to_flash (line 218) | def save_to_flash(self) -> None:
    method set_pixel (line 223) | def set_pixel(self, x: int, y: int, c: int, /) -> None:
    method get_pixel (line 228) | def get_pixel(self, x: int, y: int, /) -> int:
    method get_line (line 232) | def get_line(self, x: int, y: int, buf: AnyWritableBuf, /) -> None:
    method screen_dump (line 239) | def screen_dump(
    method screen_load (line 256) | def screen_load(self, buf: AnyReadableBuf, /) -> None:
    method set_pos (line 260) | def set_pos(self, x: int, y: int, /) -> None:
    method set_text_color (line 265) | def set_text_color(self, fg: int, bg: int, /) -> None:
    method set_font (line 269) | def set_font(
    method write (line 296) | def write(self, s: str, /) -> None:
    method set_pen (line 302) | def set_pen(self, line: int, fill: int, /) -> None:
    method erase (line 306) | def erase(self) -> None:
    method dot (line 310) | def dot(self, x: int, y: int, /) -> None:
    method rect (line 314) | def rect(self, x: int, y: int, w: int, h: int, /) -> None:
    method rect_outline (line 321) | def rect_outline(self, x: int, y: int, w: int, h: int, /) -> None:
    method rect_interior (line 328) | def rect_interior(self, x: int, y: int, w: int, h: int, /) -> None:
    method line (line 335) | def line(self, x1: int, y1: int, x2: int, y2: int, /) -> None:
    method dot_no_clip (line 339) | def dot_no_clip(self, x: int, y: int, /) -> None:
    method rect_no_clip (line 345) | def rect_no_clip(self, x: int, y: int, w: int, h: int, /) -> None:
    method rect_outline_no_clip (line 351) | def rect_outline_no_clip(self, x: int, y: int, w: int, h: int, /) -> N...
    method rect_interior_no_clip (line 357) | def rect_interior_no_clip(self, x: int, y: int, w: int, h: int, /) -> ...
    method line_no_clip (line 363) | def line_no_clip(self, x1: int, y1: int, x2: int, y2: int, /) -> None:
    method poly_dot (line 369) | def poly_dot(self, data: AnyReadableBuf, /) -> None:
    method poly_line (line 375) | def poly_line(self, data: AnyReadableBuf, /) -> None:
    method touch_config (line 379) | def touch_config(
    method is_touched (line 395) | def is_touched(self) -> bool:
    method get_touch (line 400) | def get_touch(self) -> tuple[int, int, int]:
    method set_spi_win (line 406) | def set_spi_win(self, x: int, y: int, w: int, h: int, /) -> None:
    method fast_spi (line 410) | def fast_spi(self, flush: bool = True, /) -> SPI:
    method show_framebuf (line 422) | def show_framebuf(self, buf: AnyReadableBuf, /) -> None:
    method set_scroll (line 432) | def set_scroll(self, on: bool, /) -> None:
    method set_scroll_win (line 437) | def set_scroll_win(
    method set_scroll_win_param (line 465) | def set_scroll_win_param(self, win: int, param: int, value: int, /) ->...
    method set_scroll_buf (line 474) | def set_scroll_buf(self, s: str, /) -> None:
    method jpeg (line 479) | def jpeg(self, buf: AnyReadableBuf, /) -> None:
    method jpeg_start (line 486) | def jpeg_start(self, total_len: int, /) -> None:
    method jpeg_data (line 493) | def jpeg_data(self, buf: AnyReadableBuf, /) -> None:
    method feed_wdt (line 500) | def feed_wdt(self) -> None:
    method reset (line 506) | def reset(self) -> None:

FILE: typehints/pyboard/pyb.pyi
  class _OldAbstractReadOnlyBlockDev (line 98) | class _OldAbstractReadOnlyBlockDev(Protocol):
    method readblocks (line 106) | def readblocks(self, blocknum: int, buf: bytearray, /) -> None: ...
    method count (line 108) | def count(self) -> int: ...
  class _OldAbstractBlockDev (line 111) | class _OldAbstractBlockDev(_OldAbstractReadOnlyBlockDev, Protocol):
    method writeblocks (line 119) | def writeblocks(self, blocknum: int, buf: bytes | bytearray, /) -> Non...
    method sync (line 121) | def sync(self) -> None: ...
  function country (line 133) | def country() -> str:
  function country (line 137) | def country(alpha_2_code: str) -> None:
  function delay (line 140) | def delay(ms: int, /) -> None:
  function udelay (line 145) | def udelay(us: int, /) -> None:
  function millis (line 150) | def millis() -> int:
  function micros (line 163) | def micros() -> int:
  function elapsed_millis (line 176) | def elapsed_millis(start: int, /) -> int:
  function elapsed_micros (line 190) | def elapsed_micros(start: int, /) -> int:
  function hard_reset (line 205) | def hard_reset() -> NoReturn:
  function bootloader (line 211) | def bootloader() -> NoReturn:
  function fault_debug (line 216) | def fault_debug(value: bool = False) -> None:
  function disable_irq (line 230) | def disable_irq() -> bool:
  function enable_irq (line 238) | def enable_irq(state: bool = True, /) -> None:
  function freq (line 248) | def freq() -> tuple[int, int, int, int]:
  function freq (line 288) | def freq(sysclk: int, /) -> None:
  function freq (line 328) | def freq(sysclk: int, hclk: int, /) -> None:
  function freq (line 368) | def freq(sysclk: int, hclk: int, pclk1: int, /) -> None:
  function freq (line 408) | def freq(sysclk: int, hclk: int, pclk1: int, pclk2: int, /) -> None:
  function wfi (line 447) | def wfi() -> None:
  function stop (line 458) | def stop() -> None:
  function standby (line 469) | def standby() -> None:
  function have_cdc (line 481) | def have_cdc() -> bool:
  function hid (line 489) | def hid(data: tuple[int, int, int, int], /) -> None:
  function hid (line 498) | def hid(data: Sequence[int], /) -> None:
  function info (line 507) | def info() -> None:
  function info (line 513) | def info(dump_alloc_table: bytes, /) -> None:
  function main (line 518) | def main(filename: str, /) -> None:
  function mount (line 527) | def mount(
  function mount (line 569) | def mount(
  function repl_uart (line 611) | def repl_uart() -> UART | None:
  function repl_uart (line 617) | def repl_uart(uart: UART, /) -> None:
  function rng (line 622) | def rng() -> int:
  function sync (line 627) | def sync() -> None:
  function unique_id (line 632) | def unique_id() -> bytes:
  function usb_mode (line 639) | def usb_mode() -> str:
  function usb_mode (line 681) | def usb_mode(
  class Accel (line 731) | class Accel:
    method __init__ (line 742) | def __init__(self):
    method filtered_xyz (line 746) | def filtered_xyz(self) -> tuple[int, int, int]:
    method tilt (line 755) | def tilt(self) -> int:
    method x (line 759) | def x(self) -> int:
    method y (line 763) | def y(self) -> int:
    method z (line 767) | def z(self) -> int:
  class ADC (line 772) | class ADC:
    method __init__ (line 790) | def __init__(self, pin: int | Pin, /):
    method read (line 795) | def read(self) -> int:
    method read_timed (line 800) | def read_timed(self, buf: AnyWritableBuf, timer: Timer | int, /) -> None:
    method read_timed_multi (line 837) | def read_timed_multi(
  class ADCAll (line 891) | class ADCAll:
    method __init__ (line 972) | def __init__(self, resolution: int, mask: int = 0xFFFFFFFF, /):
    method read_channel (line 985) | def read_channel(self, channel: int, /) -> int:
    method read_core_temp (line 989) | def read_core_temp(self) -> float:
    method read_core_vbat (line 993) | def read_core_vbat(self) -> float:
    method read_core_vref (line 997) | def read_core_vref(self) -> float:
    method read_vref (line 1001) | def read_vref(self) -> float:
  class CAN (line 1006) | class CAN:
    method __init__ (line 1087) | def __init__(
    method initfilterbanks (line 1113) | def initfilterbanks(nr: int, /) -> None:
    method init (line 1122) | def init(
    method deinit (line 1175) | def deinit(self) -> None:
    method restart (line 1179) | def restart(self) -> None:
    method state (line 1190) | def state(self) -> int:
    method info (line 1205) | def info(self) -> list[int]:
    method info (line 1228) | def info(self, list: list[int], /) -> list[int]:
    method setfilter (line 1251) | def setfilter(
    method setfilter (line 1296) | def setfilter(
    method clearfilter (line 1347) | def clearfilter(self, bank: int, /) -> None:
    method any (line 1353) | def any(self, fifo: int, /) -> bool:
    method recv (line 1358) | def recv(
    method recv (line 1394) | def recv(
    method recv (line 1430) | def recv(
    method send (line 1465) | def send(
    method rxcallback (line 1493) | def rxcallback(self, fifo: int, fun: Callable[[CAN], None], /) -> None:
  class DAC (line 1529) | class DAC:
    method __init__ (line 1583) | def __init__(
    method init (line 1609) | def init(self, bits: int = 8, *, buffering: bool | None = None) -> None:
    method deinit (line 1615) | def deinit(self) -> None:
    method noise (line 1619) | def noise(self, freq: int, /) -> None:
    method triangle (line 1624) | def triangle(self, freq: int, /) -> None:
    method write (line 1630) | def write(self, value: int, /) -> None:
    method write_timed (line 1636) | def write_timed(
  class ExtInt (line 1659) | class ExtInt:
    method __init__ (line 1719) | def __init__(
    method regs (line 1743) | def regs() -> None:
    method disable (line 1747) | def disable(self) -> None:
    method enable (line 1752) | def enable(self) -> None:
    method line (line 1756) | def line(self) -> int:
    method swint (line 1760) | def swint(self) -> None:
  class Flash (line 1765) | class Flash(AbstractBlockDev):
    method __init__ (line 1777) | def __init__(self):
    method __init__ (line 1788) | def __init__(self, *, start: int = -1, len: int = -1):
    method readblocks (line 1794) | def readblocks(self, blocknum: int, buf: bytes, offset: int = 0, /) ->...
    method writeblocks (line 1800) | def writeblocks(self, blocknum: int, buf: bytes, offset: int = 0, /) -...
    method ioctl (line 1806) | def ioctl(self, op: int, arg: int) -> int | None:
  class I2C (line 1813) | class I2C:
    method __init__ (line 1874) | def __init__(
    method deinit (line 1905) | def deinit(self) -> None:
    method init (line 1909) | def init(
    method is_ready (line 1931) | def is_ready(self, addr: int, /) -> bool:
    method mem_read (line 1936) | def mem_read(
    method mem_read (line 1959) | def mem_read(
    method mem_write (line 1981) | def mem_write(
    method recv (line 2004) | def recv(self, recv: int, addr: int = 0x00, /, *, timeout: int = 5000,...
    method recv (line 2017) | def recv(
    method send (line 2031) | def send(self, addr: int = 0x00, /, *, timeout: int = 5000,) -> None:
    method scan (line 2041) | def scan(self) -> list[int]:
  class LCD (line 2047) | class LCD:
    method __init__ (line 2083) | def __init__(self, skin_position: str, /):
    method command (line 2088) | def command(self, inst_data: int, buf: bytes, /) -> None:
    method contrast (line 2094) | def contrast(self, value: int, /) -> None:
    method fill (line 2098) | def fill(self, colour: int, /) -> None:
    method get (line 2104) | def get(self, x: int, y: int, /) -> int:
    method light (line 2110) | def light(self, value: bool | int, /) -> None:
    method pixel (line 2114) | def pixel(self, x: int, y: int, colour: int, /) -> None:
    method show (line 2120) | def show(self) -> None:
    method text (line 2124) | def text(self, str: str, x: int, y: int, colour: int, /) -> None:
    method write (line 2130) | def write(self, str: str, /) -> None:
  class LED (line 2135) | class LED:
    method __init__ (line 2140) | def __init__(self, id: int, /):
    method intensity (line 2147) | def intensity(self) -> int:
    method intensity (line 2160) | def intensity(self, value: int, /) -> None:
    method off (line 2172) | def off(self) -> None:
    method on (line 2176) | def on(self) -> None:
    method toggle (line 2180) | def toggle(self) -> None:
  class Pin (line 2187) | class Pin:
    class board (line 2398) | class board:
    class cpu (line 2648) | class cpu:
    method __init__ (line 2931) | def __init__(
    method debug (line 2947) | def debug() -> bool:
    method debug (line 2953) | def debug(state: bool, /) -> None:
    method dict (line 2959) | def dict() -> Dict[str, Pin]:
    method dict (line 2965) | def dict(dict: Dict[str, Pin], /) -> None:
    method mapper (line 2971) | def mapper() -> Callable[[str], Pin]:
    method mapper (line 2977) | def mapper(fun: Callable[[str], Pin], /) -> None:
    method init (line 2981) | def init(
    method value (line 3016) | def value(self) -> int:
    method value (line 3026) | def value(self, value: Any, /) -> None:
    method __str__ (line 3035) | def __str__(self) -> str:
    method af (line 3039) | def af(self) -> int:
    method af_list (line 3045) | def af_list(self) -> list[PinAF]:
    method gpio (line 3049) | def gpio(self) -> int:
    method mode (line 3053) | def mode(self) -> int:
    method name (line 3059) | def name(self) -> str:
    method names (line 3063) | def names(self) -> list[str]:
    method pin (line 3067) | def pin(self) -> int:
    method port (line 3071) | def port(self) -> int:
    method pull (line 3075) | def pull(self) -> int:
  class PinAF (line 3082) | class PinAF(ABC):
    method __str__ (line 3139) | def __str__(self) -> str:
    method index (line 3144) | def index(self) -> int:
    method name (line 3149) | def name(self) -> str:
    method reg (line 3154) | def reg(self) -> int:
  class RTC (line 3161) | class RTC:
    method __init__ (line 3173) | def __init__(self):
    method datetime (line 3177) | def datetime(
    method wakeup (line 3195) | def wakeup(
    method info (line 3208) | def info(self) -> int:
    method calibration (line 3218) | def calibration(self) -> int:
    method calibration (line 3235) | def calibration(self, cal: int, /) -> None:
  class Servo (line 3252) | class Servo:
    method __init__ (line 3278) | def __init__(self, id: int, /):
    method angle (line 3283) | def angle(self) -> int:
    method angle (line 3295) | def angle(self, angle: int, time: int = 0, /) -> None:
    method speed (line 3307) | def speed(self) -> int:
    method speed (line 3318) | def speed(self, speed: int, time: int = 0, /) -> None:
    method speed (line 3329) | def speed(self) -> int:
    method speed (line 3337) | def speed(self, value: int, /) -> None:
    method calibration (line 3345) | def calibration(self) -> tuple[int, int, int, int, int]:
    method calibration (line 3359) | def calibration(self, pulse_min: int, pulse_max: int, pulse_centre: in...
    method calibration (line 3373) | def calibration(
  class SPI (line 3395) | class SPI:
    method __init__ (line 3439) | def __init__(self, bus: int, /):
    method __init__ (line 3456) | def __init__(
    method __init__ (line 3486) | def __init__(
    method deinit (line 3515) | def deinit(self) -> None:
    method init (line 3520) | def init(
    method init (line 3558) | def init(
    method recv (line 3595) | def recv(
    method send (line 3608) | def send(
    method send_recv (line 3619) | def send_recv(
  class Switch (line 3639) | class Switch:
    method __init__ (line 3657) | def __init__(self):
    method __call__ (line 3661) | def __call__(self) -> bool:
    method value (line 3666) | def value(self) -> bool:
    method callback (line 3670) | def callback(self, fun: Callable[[], None] | None) -> None:
  class Timer (line 3677) | class Timer:
    method __init__ (line 3825) | def __init__(self, id: int, /):
    method __init__ (line 3832) | def __init__(
    method __init__ (line 3849) | def __init__(
    method init (line 3867) | def init(
    method init (line 3923) | def init(
    method deinit (line 3979) | def deinit(self) -> None:
    method callback (line 3988) | def callback(self, fun: Callable[[Timer], None] | None, /) -> None:
    method channel (line 3995) | def channel(self, channel: int, /) -> "TimerChannel" | None:
    method channel (line 4070) | def channel(
    method channel (line 4154) | def channel(
    method channel (line 4238) | def channel(
    method channel (line 4323) | def channel(
    method channel (line 4407) | def channel(
    method counter (line 4490) | def counter(self) -> int:
    method counter (line 4495) | def counter(self, value: int, /) -> None:
    method freq (line 4500) | def freq(self) -> int:
    method freq (line 4505) | def freq(self, value: int, /) -> None:
    method period (line 4510) | def period(self) -> int:
    method period (line 4515) | def period(self, value: int, /) -> None:
    method prescaler (line 4520) | def prescaler(self) -> int:
    method prescaler (line 4525) | def prescaler(self, value: int, /) -> None:
    method source_freq (line 4529) | def source_freq(self) -> int:
  class TimerChannel (line 4534) | class TimerChannel(ABC):
    method callback (line 4544) | def callback(self, fun: Callable[[Timer], None] | None, /) -> None:
    method capture (line 4552) | def capture(self) -> int:
    method capture (line 4560) | def capture(self, value: int, /) -> None:
    method compare (line 4568) | def compare(self) -> int:
    method compare (line 4576) | def compare(self, value: int, /) -> None:
    method pulse_width (line 4584) | def pulse_width(self) -> int:
    method pulse_width (line 4595) | def pulse_width(self, value: int, /) -> None:
    method pulse_width_percent (line 4606) | def pulse_width_percent(self) -> float:
    method pulse_width_percent (line 4616) | def pulse_width_percent(self, value: int | float, /) -> None:
  class UART (line 4626) | class UART:
    method __init__ (line 4678) | def __init__(self, bus: int | str, /):
    method __init__ (line 4714) | def __init__(
    method init (line 4762) | def init(
    method deinit (line 4798) | def deinit(self) -> None:
    method any (line 4802) | def any(self) -> int:
    method read (line 4807) | def read(self) -> bytes | None:
    method read (line 4823) | def read(self, nbytes: int, /) -> bytes | None:
    method readchar (line 4838) | def readchar(self) -> int:
    method readinto (line 4845) | def readinto(self, buf: AnyWritableBuf, /) -> int | None:
    method readinto (line 4854) | def readinto(self, buf: AnyWritableBuf, nbytes: int, /) -> int | None:
    method readline (line 4862) | def readline(self) -> str | None:
    method write (line 4870) | def write(self, buf: AnyWritableBuf, /) -> int | None:
    method writechar (line 4880) | def writechar(self, char: int, /) -> None:
    method sendbreak (line 4885) | def sendbreak(self) -> None:
  class USB_HID (line 4893) | class USB_HID:
    method __init__ (line 4902) | def __init__(self):
    method recv (line 4907) | def recv(self, data: int, /, *, timeout: int = 5000) -> bytes:
    method recv (line 4919) | def recv(self, data: AnyWritableBuf, /, *, timeout: int = 5000) -> int:
    method send (line 4930) | def send(self, data: Sequence[int]) -> None:
  class USB_VCP (line 4939) | class USB_VCP:
    method __init__ (line 4963) | def __init__(self, id: int = 0, /):
    method init (line 4968) | def init(self, *, flow: int = -1) -> int:
    method setinterrupt (line 4974) | def setinterrupt(self, chr: int, /) -> None:
    method isconnected (line 4983) | def isconnected(self) -> bool:
    method any (line 4987) | def any(self) -> bool:
    method close (line 4991) | def close(self) -> None:
    method read (line 4997) | def read(self) -> bytes | None:
    method read (line 5007) | def read(self, nbytes, /) -> bytes | None:
    method readinto (line 5017) | def readinto(self, buf: AnyWritableBuf, /) -> int | None:
    method readinto (line 5028) | def readinto(self, buf: AnyWritableBuf, maxlen: int, /) -> int | None:
    method readline (line 5038) | def readline(self) -> bytes | None:
    method readlines (line 5045) | def readlines(self) -> list[bytes] | None:
    method write (line 5053) | def write(self, buf: AnyReadableBuf, /) -> int:
    method recv (line 5060) | def recv(self, data: int, /, *, timeout: int = 5000) -> bytes | None:
    method recv (line 5072) | def recv(self, data: AnyWritableBuf, /, *, timeout: int = 5000) -> int...
    method send (line 5083) | def send(self, buf: AnyWritableBuf | bytes | int, /, *, timeout: int =...

FILE: typehints/pyboard/stm.pyi
  class mem (line 23) | class mem:
    method __getitem__ (line 33) | def __getitem__(self, loc: int, /) -> int:
    method __setitem__ (line 43) | def __setitem__(self, loc: int, value: int, /) -> None:
  function rfcore_status (line 190) | def rfcore_status() -> int:
  function rfcore_fw_version (line 199) | def rfcore_fw_version(id: int, /) -> tuple[int, int, int, int, int]:
  function rfcore_sys_hci (line 210) | def rfcore_sys_hci(ogf: int, ocf: int, data: int, timeout_ms: int = 0, /...

FILE: typehints/rpi_pico/rp2.pyi
  class Flash (line 13) | class Flash:
    method ioctl (line 18) | def ioctl(self):
    method readblocks (line 21) | def readblocks(self):
    method writeblocks (line 24) | def writeblocks(self):
  class irq (line 28) | class irq:
    method flags (line 33) | def flags(self) -> int:
    method trigger (line 38) | def trigger(self):
  class PIO (line 44) | class PIO:
    method __init__ (line 56) | def __init__(self, num: int):
    method irq (line 59) | def irq(self, callback: Optional[Callable[["PIO"], None]]) -> irq:
  class StateMachine (line 63) | class StateMachine:
    method __init__ (line 67) | def __init__(self, num: int, prog: list, freq: int = None, set_base: P...
    method active (line 70) | def active(self) -> bool:
    method init (line 75) | def init(self, prog: list):
    method irq (line 80) | def irq(self) -> PIO.irq:
    method put (line 83) | def put(self, data: bytes):
  class PIOASMError (line 89) | class PIOASMError(Exception):
  function asm_pio (line 93) | def asm_pio(**kwargs) -> list:

FILE: typehints/stdlib/array.pyi
  class array (line 27) | class array(MutableSequence[_T], Generic[_T]):
    method __init__ (line 64) | def __init__(self, typecode: str, iterable: Sequence[Any] = ..., /):
    method append (line 70) | def append(self, val: Any, /) -> None:
    method extend (line 74) | def extend(self, iterable: Sequence[Any], /) -> None:
    method decode (line 79) | def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
    method __delitem__ (line 88) | def __delitem__(self, i: int) -> None:
    method __delitem__ (line 91) | def __delitem__(self, sl: slice) -> None:
    method insert (line 93) | def insert(self, index: int, value: _T) -> None:
    method __getitem__ (line 96) | def __getitem__(self, index: int) -> _T:
    method __getitem__ (line 106) | def __getitem__(self, sl: slice) -> array[_T]:
    method __setitem__ (line 115) | def __setitem__(self, index: int, value: _T) -> None:
    method __setitem__ (line 125) | def __setitem__(self, sl: slice, values: array[_T]) -> None:
    method __len__ (line 133) | def __len__(self) -> int:
    method __add__ (line 139) | def __add__(self, other: array[_T]) -> array[_T]:
    method __iadd__ (line 146) | def __iadd__(self, other: array[_T]) -> None:
    method __repr__ (line 154) | def __repr__(self) -> str:

FILE: typehints/stdlib/binascii.pyi
  function hexlify (line 22) | def hexlify(data: bytes, sep: str | bytes = ..., /) -> bytes:
  function unhexlify (line 31) | def unhexlify(data: str | bytes, /) -> bytes:
  function a2b_base64 (line 37) | def a2b_base64(data: str | bytes, /) -> bytes:
  function b2a_base64 (line 44) | def b2a_base64(data: bytes, /) -> bytes:

FILE: typehints/stdlib/cmath.pyi
  function cos (line 29) | def cos(z: _C, /) -> complex:
  function exp (line 34) | def exp(z: _C, /) -> complex:
  function log (line 39) | def log(z: _C, /) -> complex:
  function log10 (line 44) | def log10(z: _C, /) -> complex:
  function phase (line 49) | def phase(z: _C, /) -> float:
  function polar (line 54) | def polar(z: _C, /) -> tuple[float, float]:
  function rect (line 59) | def rect(r: float, phi: float, /) -> complex:
  function sin (line 64) | def sin(z: _C, /) -> complex:
  function sqrt (line 69) | def sqrt(z: _C, /) -> complex:

FILE: typehints/stdlib/collections.pyi
  function namedtuple (line 27) | def namedtuple(name: str, fields: str | Iterable[str]) -> Type[tuple[Any...
  class deque (line 47) | class deque:
    method __init__ (line 52) | def __init__(self, iterable: tuple[Any], maxlen: int, flags: int = 0, /):
    method __bool__ (line 66) | def __bool__(self) -> bool:
    method __len__ (line 73) | def __len__(self) -> int:
    method append (line 80) | def append(self, x: Any, /) -> None:
    method popleft (line 85) | def popleft(self) -> Any:
  class OrderedDict (line 91) | class OrderedDict(Dict[_KT, _VT], Generic[_KT, _VT]):
    method __init__ (line 185) | def __init__(self):
    method __init__ (line 210) | def __init__(self, **kwargs: _VT):
    method __init__ (line 235) | def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT):

FILE: typehints/stdlib/gc.pyi
  function enable (line 21) | def enable() -> None:
  function disable (line 26) | def disable() -> None:
  function collect (line 32) | def collect() -> None:
  function mem_alloc (line 37) | def mem_alloc() -> int:
  function mem_free (line 47) | def mem_free() -> int:
  function threshold (line 59) | def threshold() -> int:
  function threshold (line 85) | def threshold(amount: int) -> None:

FILE: typehints/stdlib/hashlib.pyi
  class sha256 (line 43) | class sha256("_Hash"):
    method __init__ (line 52) | def __init__(self):
    method __init__ (line 57) | def __init__(self, data: AnyReadableBuf):
  class sha1 (line 63) | class sha1("_Hash"):
    method __init__ (line 72) | def __init__(self):
    method __init__ (line 77) | def __init__(self, data: AnyReadableBuf):
  class md5 (line 83) | class md5("_Hash"):
    method __init__ (line 90) | def __init__(self, data: AnyReadableBuf = ..., /):
  class _Hash (line 95) | class _Hash(ABC):
    method update (line 100) | def update(self, data: AnyReadableBuf, /) -> None:
    method digest (line 104) | def digest(self) -> bytes:
    method hexdigest (line 109) | def hexdigest(self) -> str:

FILE: typehints/stdlib/heapq.pyi
  function heappush (line 29) | def heappush(heap: list[_T], item: _T, /) -> None:
  function heappop (line 34) | def heappop(heap: list[_T], /) -> _T:
  function heapify (line 42) | def heapify(x: list[Any], /) -> None:

FILE: typehints/stdlib/io.pyi
  class PathLike (line 169) | class PathLike(Protocol[AnyStr_co]):
    method __fspath__ (line 170) | def __fspath__(self) -> AnyStr_co: ...
  class IOBase (line 188) | class IOBase(Protocol[AnyStr, _Self]):
    method __enter__ (line 192) | def __enter__(self) -> _Self:
    method __exit__ (line 198) | def __exit__(
    method __next__ (line 216) | def __next__(self) -> AnyStr:
    method __iter__ (line 220) | def __iter__(self) -> _Self:
    method close (line 224) | def close(self) -> None:
    method flush (line 233) | def flush(self) -> None:
    method read (line 241) | def read(self, size: int | None = -1) -> AnyStr | None:
    method readinto (line 251) | def readinto(self, b: AnyWritableBuf) -> int | None:
    method readline (line 258) | def readline(self, size: int = -1) -> AnyStr:
    method readlines (line 267) | def readlines(self, hint: int | None = -1) -> list[AnyStr]:
    method write (line 281) | def write(self, b: AnyReadableBuf) -> int | None:
    method seek (line 291) | def seek(self, offset: int, whence: int = 0) -> int:
    method tell (line 305) | def tell(self) -> int:
  function open (line 311) | def open(name: _OpenFile, /, **kwargs) -> "TextIOWrapper":
  function open (line 319) | def open(name: _OpenFile, mode: _OpenTextMode = ..., /, **kwargs) -> "Te...
  function open (line 327) | def open(name: _OpenFile, mode: _OpenBinaryMode = ..., /, **kwargs) -> "...
  class FileIO (line 334) | class FileIO(IOBase[bytes, "FileIO"]):
    method __init__ (line 339) | def __init__(self, name: _OpenFile, mode: str = ..., /, **kwargs):
  class TextIOWrapper (line 345) | class TextIOWrapper(IOBase[str, "TextIOWrapper"]):
    method __init__ (line 350) | def __init__(self, name: _OpenFile, mode: str = ..., /, **kwargs):
  class StringIO (line 356) | class StringIO(IOBase[str, "StringIO"]):
    method __init__ (line 362) | def __init__(self, string: str = "", /):
    method __init__ (line 382) | def __init__(self, alloc_size: int, /):
    method getvalue (line 401) | def getvalue(self) -> str:
  class BytesIO (line 404) | class BytesIO(IOBase[bytes, "BytesIO"]):
    method __init__ (line 410) | def __init__(self, string: bytes = "", /):
    method __init__ (line 436) | def __init__(self, alloc_size: int, /):
    method getvalue (line 461) | def getvalue(self) -> bytes:

FILE: typehints/stdlib/json.pyi
  function dump (line 26) | def dump(
  function dumps (line 37) | def dumps(obj: Any, separators: tuple[str, str] | None = None) -> str:
  function load (line 44) | def load(stream: IOBase[str, Any]) -> Any:
  function loads (line 54) | def loads(str: AnyStr) -> Any:

FILE: typehints/stdlib/math.pyi
  function acos (line 29) | def acos(x: SupportsFloat, /) -> float:
  function acosh (line 34) | def acosh(x: SupportsFloat, /) -> float:
  function asin (line 39) | def asin(x: SupportsFloat, /) -> float:
  function asinh (line 44) | def asinh(x: SupportsFloat, /) -> float:
  function atan (line 49) | def atan(x: SupportsFloat, /) -> float:
  function atan2 (line 54) | def atan2(y: SupportsFloat, x: SupportsFloat, /) -> float:
  function atanh (line 59) | def atanh(x: SupportsFloat, /) -> float:
  function ceil (line 64) | def ceil(x: SupportsFloat, /) -> int:
  function copysign (line 69) | def copysign(x: SupportsFloat, y: SupportsFloat, /) -> float:
  function cos (line 74) | def cos(x: SupportsFloat, /) -> float:
  function cosh (line 79) | def cosh(x: SupportsFloat, /) -> float:
  function degrees (line 84) | def degrees(x: SupportsFloat, /) -> float:
  function erf (line 89) | def erf(x: SupportsFloat, /) -> float:
  function erfc (line 94) | def erfc(x: SupportsFloat, /) -> float:
  function exp (line 99) | def exp(x: SupportsFloat, /) -> float:
  function expm1 (line 104) | def expm1(x: SupportsFloat, /) -> float:
  function fabs (line 109) | def fabs(x: SupportsFloat, /) -> float:
  function floor (line 114) | def floor(x: SupportsFloat, /) -> int:
  function fmod (line 119) | def fmod(x: SupportsFloat, y: SupportsFloat, /) -> float:
  function frexp (line 124) | def frexp(x: SupportsFloat, /) -> tuple[float, int]:
  function gamma (line 132) | def gamma(x: SupportsFloat, /) -> float:
  function isfinite (line 137) | def isfinite(x: SupportsFloat, /) -> bool:
  function isinf (line 142) | def isinf(x: SupportsFloat, /) -> bool:
  function isnan (line 147) | def isnan(x: SupportsFloat, /) -> bool:
  function ldexp (line 153) | def ldexp(x: SupportsFloat, exp: int, /) -> float:
  function lgamma (line 158) | def lgamma(x: SupportsFloat, /) -> float:
  function log (line 163) | def log(x: SupportsFloat, /) -> float:
  function log10 (line 168) | def log10(x: SupportsFloat, /) -> float:
  function log2 (line 173) | def log2(x: SupportsFloat, /) -> float:
  function modf (line 178) | def modf(x: SupportsFloat, /) -> tuple[float, float]:
  function pow (line 184) | def pow(x: SupportsFloat, y: SupportsFloat, /) -> float:
  function radians (line 189) | def radians(x: SupportsFloat, /) -> float:
  function sin (line 194) | def sin(x: SupportsFloat, /) -> float:
  function sinh (line 199) | def sinh(x: SupportsFloat, /) -> float:
  function sqrt (line 204) | def sqrt(x: SupportsFloat, /) -> float:
  function tan (line 209) | def tan(x: SupportsFloat, /) -> float:
  function tanh (line 214) | def tanh(x: SupportsFloat, /) -> float:
  function trunc (line 219) | def trunc(x: SupportsFloat, /) -> float:

FILE: typehints/stdlib/os.pyi
  class _PathLike (line 30) | class _PathLike(Protocol[_StrOrBytesT]):
    method __fspath__ (line 32) | def __fspath__(self) -> _StrOrBytesT:
  function uname (line 38) | def uname() -> tuple[str, str, str, str, str]:
  function urandom (line 51) | def urandom(n: int, /) -> bytes:
  function chdir (line 57) | def chdir(path: _FdOrAnyPath, /) -> None:
  function getcwd (line 62) | def getcwd() -> str:
  function ilistdir (line 68) | def ilistdir() -> list[tuple[str, int, int] | tuple[str, int, int, int]]:
  function ilistdir (line 89) | def ilistdir(dir: int, /) -> list[tuple[str, int, int] | tuple[str, int,...
  function ilistdir (line 110) | def ilistdir(dir: str, /) -> list[tuple[str, int, int] | tuple[str, int,...
  function ilistdir (line 131) | def ilistdir(
  function ilistdir (line 154) | def ilistdir(
  function ilistdir (line 177) | def ilistdir(
  function listdir (line 200) | def listdir() -> list[str]:
  function listdir (line 206) | def listdir(dir: int, /) -> list[str]:
  function listdir (line 212) | def listdir(dir: str, /) -> list[str]:
  function listdir (line 218) | def listdir(dir: bytes, /) -> list[bytes]:
  function listdir (line 224) | def listdir(dir: _PathLike[str], /) -> list[str]:
  function listdir (line 230) | def listdir(dir: _PathLike[bytes], /) -> list[bytes]:
  function mkdir (line 235) | def mkdir(path: _AnyPath, /) -> None:
  function remove (line 240) | def remove(path: _AnyPath, /) -> None:
  function rmdir (line 245) | def rmdir(path: _AnyPath, /) -> None:
  function rename (line 250) | def rename(old_path: _AnyPath, new_path: _AnyPath, /) -> None:
  function stat (line 255) | def stat(
  function statvfs (line 262) | def statvfs(
  function sync (line 286) | def sync() -> None:
  function dupterm (line 291) | def dupterm(stream_object: IOBase | None, index: int = 0, /) -> IOBase |...
  function mount (line 313) | def mount(
  function umount (line 344) | def umount(mount_point: str, /) -> None:
  class VfsFat (line 353) | class VfsFat("AbstractBlockDev"):
    method __init__ (line 358) | def __init__(self, block_dev: "AbstractBlockDev", /):
    method mkfs (line 365) | def mkfs(block_dev: "AbstractBlockDev", /) -> None:
  class VfsLfs1 (line 370) | class VfsLfs1("AbstractBlockDev"):
    method __init__ (line 375) | def __init__(
    method mkfs (line 392) | def mkfs(
  class VfsLfs2 (line 406) | class VfsLfs2("AbstractBlockDev"):
    method __init__ (line 411) | def __init__(
    method mkfs (line 437) | def mkfs(
  class AbstractBlockDev (line 453) | class AbstractBlockDev(Protocol):
    method __init__ (line 487) | def __init__(self):
    method readblocks (line 493) | def readblocks(self, block_num: int, buf: bytearray, /) -> None:
    method readblocks (line 508) | def readblocks(self, block_num: int, buf: bytearray, offset: int, /) -...
    method writeblocks (line 523) | def writeblocks(self, block_num: int, buf: bytes | bytearray, /) -> None:
    method writeblocks (line 544) | def writeblocks(
    method ioctl (line 567) | def ioctl(self, op: int, arg: int) -> int | None:
    method ioctl (line 599) | def ioctl(self, op: Literal[4, 5], arg: int) -> int:
    method ioctl (line 631) | def ioctl(self, op: Literal[1, 2, 3, 6], arg: int) -> int | None:

FILE: typehints/stdlib/re.pyi
  function compile (line 123) | def compile(regex_str: _StrLike, flags: int = ..., /) -> "ure":
  function match (line 128) | def match(regex_str: _StrLike, string: AnyStr, /) -> "Match[AnyStr]":
  function search (line 134) | def search(regex_str: _StrLike, string: AnyStr, /) -> "Match[AnyStr]":
  function sub (line 141) | def sub(
  class ure (line 172) | class ure:
    method match (line 178) | def match(self, string: AnyStr, /) -> "Match[AnyStr]":
    method search (line 185) | def search(self, string: AnyStr, /) -> "Match[AnyStr]":
    method sub (line 192) | def sub(
    method split (line 206) | def split(self, string: AnyStr, max_split: int = -1, /) -> list[AnyStr]:
  class Match (line 213) | class Match(Generic[AnyStr]):
    method group (line 223) | def group(self, index: int, /) -> AnyStr:
    method groups (line 228) | def groups(self) -> tuple[AnyStr | Any, ...]:
    method start (line 234) | def start(self, index: int = ..., /) -> int:
    method end (line 242) | def end(self, index: int = ..., /) -> int:
    method span (line 250) | def span(self, index: int = ..., /) -> tuple[int, int]:

FILE: typehints/stdlib/select.pyi
  function poll (line 38) | def poll() -> "Poll":
  function select (line 43) | def select(
  class Poll (line 57) | class Poll:
    method register (line 64) | def register(self, obj: IOBase, eventmask: int = POLLIN | POLLOUT, /) ...
    method unregister (line 82) | def unregister(self, obj: IOBase, /) -> None:
    method modify (line 86) | def modify(self, obj: IOBase, eventmask: int, /) -> None:
    method poll (line 91) | def poll(self, timeout: int = -1, /) -> list[tuple[Any, int, Any, ...]]:
    method ipoll (line 114) | def ipoll(

FILE: typehints/stdlib/socket.pyi
  function socket (line 93) | def socket(
  function getaddrinfo (line 109) | def getaddrinfo(
  function inet_ntop (line 152) | def inet_ntop(af: int, bin_addr: bytes, /) -> str:
  function inet_pton (line 161) | def inet_pton(af: int, txt_addr: str, /) -> bytes:
  class Socket (line 228) | class Socket:
    method close (line 237) | def close(self) -> None:
    method bind (line 246) | def bind(self, address: _Address | bytes, /) -> None:
    method listen (line 250) | def listen(self, backlog: int = ..., /) -> None:
    method accept (line 257) | def accept(self) -> None:
    method connect (line 264) | def connect(self, address: _Address | bytes, /) -> None:
    method send (line 268) | def send(self, bytes: AnyReadableBuf, /) -> int:
    method sendall (line 274) | def sendall(self, bytes: AnyReadableBuf, /) -> None:
    method recv (line 285) | def recv(self, bufsize: int, /) -> bytes:
    method sendto (line 290) | def sendto(self, bytes: AnyReadableBuf, address: _Address, /) -> int:
    method recvfrom (line 295) | def recvfrom(self, bufsize: int, /) -> tuple[bytes, Any]:
    method setsockopt (line 301) | def setsockopt(
    method settimeout (line 309) | def settimeout(self, value: float | None, /) -> None:
    method setblocking (line 343) | def setblocking(self, value: bool, /) -> None:
    method makefile (line 354) | def makefile(
    method makefile (line 375) | def makefile(self, mode: str, buffering: int = 0, /) -> Socket:
    method read (line 394) | def read(self) -> bytes:
    method read (line 403) | def read(self, size: int, /) -> bytes:
    method readinto (line 412) | def readinto(self, buf: AnyWritableBuf, /) -> int | None:
    method readinto (line 421) | def readinto(self, buf: AnyWritableBuf, nbytes: int, /) -> int | None:
    method readline (line 429) | def readline(self) -> bytes:
    method write (line 435) | def write(self, buf: AnyReadableBuf, /) -> int | None:

FILE: typehints/stdlib/ssl.pyi
  function wrap_socket (line 29) | def wrap_socket(

FILE: typehints/stdlib/struct.pyi
  function calcsize (line 34) | def calcsize(fmt: str | bytes, /,) -> int:
  function pack (line 39) | def pack(fmt: str | bytes, /, *v: Any) -> bytes:
  function pack_into (line 45) | def pack_into(
  function unpack (line 54) | def unpack(fmt: str | bytes, data: AnyReadableBuf, /) -> tuple[Any, ...]:
  function unpack_from (line 60) | def unpack_from(

FILE: typehints/stdlib/sys.pyi
  class Implementation (line 23) | class Implementation(tuple[str, tuple[int, int, int], int]):
  class ModuleType (line 28) | class ModuleType:
  function exit (line 32) | def exit(retval: object = 0, /) -> NoReturn:
  function atexit (line 39) | def atexit(func: Callable[[], None] | None, /) -> Callable[[], None] | N...
  function print_exception (line 53) | def print_exception(exc: BaseException, file: IOBase[str] = "stdout", /)...

FILE: typehints/stdlib/time.pyi
  class _TicksMs (line 48) | class _TicksMs: ...
  class _TicksUs (line 49) | class _TicksUs: ...
  class _TicksCPU (line 50) | class _TicksCPU: ...
  function gmtime (line 54) | def gmtime(secs: int | None = None, /) -> tuple[int, int, int, int, int,...
  function localtime (line 75) | def localtime(
  function mktime (line 98) | def mktime(local_time: tuple[int, int, int, int, int, int, int, int], /)...
  function sleep (line 105) | def sleep(seconds: float, /) -> None:
  function sleep_ms (line 113) | def sleep_ms(ms: int, /) -> None:
  function sleep_us (line 123) | def sleep_us(us: int, /) -> None:
  function ticks_ms (line 132) | def ticks_ms() -> _TicksMs:
  function ticks_us (line 155) | def ticks_us() -> _TicksUs:
  function ticks_cpu (line 160) | def ticks_cpu() -> _TicksCPU:
  function ticks_add (line 174) | def ticks_add(ticks: _Ticks, delta: int, /) -> _Ticks:
  function ticks_diff (line 200) | def ticks_diff(ticks1: _Ticks, ticks2: _Ticks, /) -> int:
  function time (line 265) | def time() -> int:
  function time_ns (line 292) | def time_ns() -> int:

FILE: typehints/stdlib/uarray.pyi
  class array (line 27) | class array(MutableSequence[_T], Generic[_T]):
    method __init__ (line 64) | def __init__(self, typecode: str, iterable: Sequence[Any] = ..., /):
    method append (line 70) | def append(self, val: Any, /) -> None:
    method extend (line 74) | def extend(self, iterable: Sequence[Any], /) -> None:
    method decode (line 79) | def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
    method __delitem__ (line 88) | def __delitem__(self, i: int) -> None:
    method __delitem__ (line 91) | def __delitem__(self, sl: slice) -> None:
    method insert (line 93) | def insert(self, index: int, value: _T) -> None:
    method __getitem__ (line 96) | def __getitem__(self, index: int) -> _T:
    method __getitem__ (line 106) | def __getitem__(self, sl: slice) -> array[_T]:
    method __setitem__ (line 115) | def __setitem__(self, index: int, value: _T) -> None:
    method __setitem__ (line 125) | def __setitem__(self, sl: slice, values: array[_T]) -> None:
    method __len__ (line 133) | def __len__(self) -> int:
    method __add__ (line 139) | def __add__(self, other: array[_T]) -> array[_T]:
    method __iadd__ (line 146) | def __iadd__(self, other: array[_T]) -> None:
    method __repr__ (line 154) | def __repr__(self) -> str:

FILE: typehints/stdlib/uasyncio.pyi
  function create_task (line 50) | def create_task(coro: _C, /) -> Task[_T]:
  function current_task (line 57) | def current_task() -> Task[Any] | None:
  function run (line 62) | def run(coro: _C, /) -> _T:
  function sleep (line 69) | def sleep(t: float) -> Awaitable[None]:
  function sleep_ms (line 76) | def sleep_ms(t: int, /) -> Awaitable[None]:
  function wait_for (line 83) | def wait_for(awaitable: Awaitable[_T], timeout: float, /) -> Awaitable[_T]:
  function wait_for_ms (line 97) | def wait_for_ms(awaitable: Awaitable[_T], timeout: int, /) -> Awaitable[...
  function gather (line 104) | def gather(
  function open_connection (line 120) | def open_connection(
  function start_server (line 134) | def start_server(
  function get_event_loop (line 151) | def get_event_loop() -> Loop:
  function new_event_loop (line 156) | def new_event_loop() -> Loop:
  class Task (line 164) | class Task(Awaitable[_T], Iterable[_T], Generic[_T], ABC):
    method __init__ (line 170) | def __init__(self):
    method cancel (line 178) | def cancel(self) -> None:
  class Event (line 184) | class Event:
    method __init__ (line 190) | def __init__(self):
    method is_set (line 195) | def is_set(self) -> bool:
    method set (line 199) | def set(self) -> None:
    method clear (line 206) | def clear(self) -> None:
    method wait (line 210) | def wait(self) -> Awaitable[Any]:
  class ThreadSafeFlag (line 218) | class ThreadSafeFlag:
    method __init__ (line 224) | def __init__(self):
    method set (line 230) | def set(self) -> None:
    method wait (line 235) | def wait(self) -> Awaitable[None]:
  class Lock (line 245) | class Lock(Awaitable[None], ABC):
    method __init__ (line 251) | def __init__(self):
    method locked (line 258) | def locked(self) -> bool:
    method acquire (line 262) | def acquire(self) -> Awaitable[None]:
    method release (line 269) | def release(self) -> None:
  class Stream (line 276) | class Stream:
    method __init__ (line 281) | def __init__(self):
    method get_extra_info (line 287) | def get_extra_info(self, v: str, /) -> str:
    method close (line 292) | def close(self) -> None:
    method wait_close (line 296) | def wait_close(self) -> Awaitable[None]:
    method read (line 302) | def read(self, n: int, /) -> Awaitable[bytes]:
    method readline (line 308) | def readline(self) -> Awaitable[bytes]:
    method write (line 314) | def write(self, buf: AnyReadableBuf, /) -> None:
    method drain (line 320) | def drain(self) -> Awaitable[None]:
  class Server (line 327) | class Server:
    method __init__ (line 332) | def __init__(self):
    method close (line 337) | def close(self) -> None:
    method wait_close (line 341) | def wait_close(self) -> Awaitable[None]:
  class Loop (line 348) | class Loop:
    method __init__ (line 353) | def __init__(self):
    method create_task (line 358) | def create_task(self, coro: _C, /) -> Task[_T]:
    method run_forever (line 362) | def run_forever(self) -> None:
    method run_until_complete (line 366) | def run_until_complete(self, awaitable: Awaitable[_T], /) -> None:
    method stop (line 371) | def stop(self) -> None:
    method close (line 375) | def close(self) -> None:
    method set_exception_handler (line 379) | def set_exception_handler(
    method get_exception_handler (line 386) | def get_exception_handler(self) -> Callable[[Loop, Dict[str, Any]], No...
    method default_exception_handler (line 391) | def default_exception_handler(self, context: Dict[str, Any], /) -> None:
    method call_exception_handler (line 395) | def call_exception_handler(self, context: Dict[str, Any], /) -> None:

FILE: typehints/stdlib/ubinascii.pyi
  function hexlify (line 22) | def hexlify(data: bytes, sep: str | bytes = ..., /) -> bytes:
  function unhexlify (line 31) | def unhexlify(data: str | bytes, /) -> bytes:
  function a2b_base64 (line 37) | def a2b_base64(data: str | bytes, /) -> bytes:
  function b2a_base64 (line 44) | def b2a_base64(data: bytes, /) -> bytes:

FILE: typehints/stdlib/ucollections.pyi
  function namedtuple (line 27) | def namedtuple(name: str, fields: str | Iterable[str]) -> Type[tuple[Any...
  class deque (line 47) | class deque:
    method __init__ (line 52) | def __init__(self, iterable: tuple[Any], maxlen: int, flags: int = 0, /):
    method __bool__ (line 66) | def __bool__(self) -> bool:
    method __len__ (line 73) | def __len__(self) -> int:
    method append (line 80) | def append(self, x: Any, /) -> None:
    method popleft (line 85) | def popleft(self) -> Any:
  class OrderedDict (line 91) | class OrderedDict(Dict[_KT, _VT], Generic[_KT, _VT]):
    method __init__ (line 185) | def __init__(self):
    method __init__ (line 210) | def __init__(self, **kwargs: _VT):
    method __init__ (line 235) | def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT):

FILE: typehints/stdlib/uhashlib.pyi
  class sha256 (line 43) | class sha256("_Hash"):
    method __init__ (line 52) | def __init__(self):
    method __init__ (line 57) | def __init__(self, data: AnyReadableBuf):
  class sha1 (line 63) | class sha1("_Hash"):
    method __init__ (line 72) | def __init__(self):
    method __init__ (line 77) | def __init__(self, data: AnyReadableBuf):
  class md5 (line 83) | class md5("_Hash"):
    method __init__ (line 90) | def __init__(self, data: AnyReadableBuf = ..., /):
  class _Hash (line 95) | class _Hash(ABC):
    method update (line 100) | def update(self, data: AnyReadableBuf, /) -> None:
    method digest (line 104) | def digest(self) -> bytes:
    method hexdigest (line 109) | def hexdigest(self) -> str:

FILE: typehints/stdlib/uheapq.pyi
  function heappush (line 29) | def heappush(heap: list[_T], item: _T, /) -> None:
  function heappop (line 34) | def heappop(heap: list[_T], /) -> _T:
  function heapify (line 42) | def heapify(x: list[Any], /) -> None:

FILE: typehints/stdlib/uio.pyi
  class PathLike (line 169) | class PathLike(Protocol[AnyStr_co]):
    method __fspath__ (line 170) | def __fspath__(self) -> AnyStr_co: ...
  class IOBase (line 188) | class IOBase(Protocol[AnyStr, _Self]):
    method __enter__ (line 192) | def __enter__(self) -> _Self:
    method __exit__ (line 198) | def __exit__(
    method __next__ (line 216) | def __next__(self) -> AnyStr:
    method __iter__ (line 220) | def __iter__(self) -> _Self:
    method close (line 224) | def close(self) -> None:
    method flush (line 233) | def flush(self) -> None:
    method read (line 241) | def read(self, size: int | None = -1) -> AnyStr | None:
    method readinto (line 251) | def readinto(self, b: AnyWritableBuf) -> int | None:
    method readline (line 258) | def readline(self, size: int = -1) -> AnyStr:
    method readlines (line 267) | def readlines(self, hint: int | None = -1) -> list[AnyStr]:
    method write (line 281) | def write(self, b: AnyReadableBuf) -> int | None:
    method seek (line 291) | def seek(self, offset: int, whence: int = 0) -> int:
    method tell (line 305) | def tell(self) -> int:
  function open (line 311) | def open(name: _OpenFile, /, **kwargs) -> "TextIOWrapper":
  function open (line 319) | def open(name: _OpenFile, mode: _OpenTextMode = ..., /, **kwargs) -> "Te...
  function open (line 327) | def open(name: _OpenFile, mode: _OpenBinaryMode = ..., /, **kwargs) -> "...
  class FileIO (line 334) | class FileIO(IOBase[bytes, "FileIO"]):
    method __init__ (line 339) | def __init__(self, name: _OpenFile, mode: str = ..., /, **kwargs):
  class TextIOWrapper (line 345) | class TextIOWrapper(IOBase[str, "TextIOWrapper"]):
    method __init__ (line 350) | def __init__(self, name: _OpenFile, mode: str = ..., /, **kwargs):
  class StringIO (line 356) | class StringIO(IOBase[str, "StringIO"]):
    method __init__ (line 362) | def __init__(self, string: str = "", /):
    method __init__ (line 382) | def __init__(self, alloc_size: int, /):
    method getvalue (line 401) | def getvalue(self) -> str:
  class BytesIO (line 404) | class BytesIO(IOBase[bytes, "BytesIO"]):
    method __init__ (line 410) | def __init__(self, string: bytes = "", /):
    method __init__ (line 436) | def __init__(self, alloc_size: int, /):
    method getvalue (line 461) | def getvalue(self) -> bytes:

FILE: typehints/stdlib/ujson.pyi
  function dump (line 26) | def dump(
  function dumps (line 37) | def dumps(obj: Any, separators: tuple[str, str] | None = None) -> str:
  function load (line 44) | def load(stream: IOBase[str, Any]) -> Any:
  function loads (line 54) | def loads(str: AnyStr) -> Any:

FILE: typehints/stdlib/uos.pyi
  class _PathLike (line 30) | class _PathLike(Protocol[_StrOrBytesT]):
    method __fspath__ (line 32) | def __fspath__(self) -> _StrOrBytesT:
  function uname (line 38) | def uname() -> tuple[str, str, str, str, str]:
  function urandom (line 51) | def urandom(n: int, /) -> bytes:
  function chdir (line 57) | def chdir(path: _FdOrAnyPath, /) -> None:
  function getcwd (line 62) | def getcwd() -> str:
  function ilistdir (line 68) | def ilistdir() -> list[tuple[str, int, int] | tuple[str, int, int, int]]:
  function ilistdir (line 89) | def ilistdir(dir: int, /) -> list[tuple[str, int, int] | tuple[str, int,...
  function ilistdir (line 110) | def ilistdir(dir: str, /) -> list[tuple[str, int, int] | tuple[str, int,...
  function ilistdir (line 131) | def ilistdir(
  function ilistdir (line 154) | def ilistdir(
  function ilistdir (line 177) | def ilistdir(
  function listdir (line 200) | def listdir() -> list[str]:
  function listdir (line 206) | def listdir(dir: int, /) -> list[str]:
  function listdir (line 212) | def listdir(dir: str, /) -> list[str]:
  function listdir (line 218) | def listdir(dir: bytes, /) -> list[bytes]:
  function listdir (line 224) | def listdir(dir: _PathLike[str], /) -> list[str]:
  function listdir (line 230) | def listdir(dir: _PathLike[bytes], /) -> list[bytes]:
  function mkdir (line 235) | def mkdir(path: _AnyPath, /) -> None:
  function remove (line 240) | def remove(path: _AnyPath, /) -> None:
  function rmdir (line 245) | def rmdir(path: _AnyPath, /) -> None:
  function rename (line 250) | def rename(old_path: _AnyPath, new_path: _AnyPath, /) -> None:
  function stat (line 255) | def stat(
  function statvfs (line 262) | def statvfs(
  function sync (line 286) | def sync() -> None:
  function dupterm (line 291) | def dupterm(stream_object: IOBase | None, index: int = 0, /) -> IOBase |...
  function mount (line 313) | def mount(
  function umount (line 344) | def umount(mount_point: str, /) -> None:
  class VfsFat (line 353) | class VfsFat("AbstractBlockDev"):
    method __init__ (line 358) | def __init__(self, block_dev: "AbstractBlockDev", /):
    method mkfs (line 365) | def mkfs(block_dev: "AbstractBlockDev", /) -> None:
  class VfsLfs1 (line 370) | class VfsLfs1("AbstractBlockDev"):
    method __init__ (line 375) | def __init__(
    method mkfs (line 392) | def mkfs(
  class VfsLfs2 (line 406) | class VfsLfs2("AbstractBlockDev"):
    method __init__ (line 411) | def __init__(
    method mkfs (line 437) | def mkfs(
  class AbstractBlockDev (line 453) | class AbstractBlockDev(Protocol):
    method __init__ (line 487) | def __init__(self):
    method readblocks (line 493) | def readblocks(self, block_num: int, buf: bytearray, /) -> None:
    method readblocks (line 508) | def readblocks(self, block_num: int, buf: bytearray, offset: int, /) -...
    method writeblocks (line 523) | def writeblocks(self, block_num: int, buf: bytes | bytearray, /) -> None:
    method writeblocks (line 544) | def writeblocks(
    method ioctl (line 567) | def ioctl(self, op: int, arg: int) -> int | None:
    method ioctl (line 599) | def ioctl(self, op: Literal[4, 5], arg: int) -> int:
    method ioctl (line 631) | def ioctl(self, op: Literal[1, 2, 3, 6], arg: int) -> int | None:

FILE: typehints/stdlib/ure.pyi
  function compile (line 123) | def compile(regex_str: _StrLike, flags: int = ..., /) -> "ure":
  function match (line 128) | def match(regex_str: _StrLike, string: AnyStr, /) -> "Match[AnyStr]":
  function search (line 134) | def search(regex_str: _StrLike, string: AnyStr, /) -> "Match[AnyStr]":
  function sub (line 141) | def sub(
  class ure (line 172) | class ure:
    method match (line 178) | def match(self, string: AnyStr, /) -> "Match[AnyStr]":
    method search (line 185) | def search(self, string: AnyStr, /) -> "Match[AnyStr]":
    method sub (line 192) | def sub(
    method split (line 206) | def split(self, string: AnyStr, max_split: int = -1, /) -> list[AnyStr]:
  class Match (line 213) | class Match(Generic[AnyStr]):
    method group (line 223) | def group(self, index: int, /) -> AnyStr:
    method groups (line 228) | def groups(self) -> tuple[AnyStr | Any, ...]:
    method start (line 234) | def start(self, index: int = ..., /) -> int:
    method end (line 242) | def end(self, index: int = ..., /) -> int:
    method span (line 250) | def span(self, index: int = ..., /) -> tuple[int, int]:

FILE: typehints/stdlib/uselect.pyi
  function poll (line 38) | def poll() -> "Poll":
  function select (line 43) | def select(
  class Poll (line 57) | class Poll:
    method register (line 64) | def register(self, obj: IOBase, eventmask: int = POLLIN | POLLOUT, /) ...
    method unregister (line 82) | def unregister(self, obj: IOBase, /) -> None:
    method modify (line 86) | def modify(self, obj: IOBase, eventmask: int, /) -> None:
    method poll (line 91) | def poll(self, timeout: int = -1, /) -> list[tuple[Any, int, Any, ...]]:
    method ipoll (line 114) | def ipoll(

FILE: typehints/stdlib/usocket.pyi
  function socket (line 93) | def socket(
  function getaddrinfo (line 109) | def getaddrinfo(
  function inet_ntop (line 152) | def inet_ntop(af: int, bin_addr: bytes, /) -> str:
  function inet_pton (line 161) | def inet_pton(af: int, txt_addr: str, /) -> bytes:
  class Socket (line 228) | class Socket:
    method close (line 237) | def close(self) -> None:
    method bind (line 246) | def bind(self, address: _Address | bytes, /) -> None:
    method listen (line 250) | def listen(self, backlog: int = ..., /) -> None:
    method accept (line 257) | def accept(self) -> None:
    method connect (line 264) | def connect(self, address: _Address | bytes, /) -> None:
    method send (line 268) | def send(self, bytes: AnyReadableBuf, /) -> int:
    method sendall (line 274) | def sendall(self, bytes: AnyReadableBuf, /) -> None:
    method recv (line 285) | def recv(self, bufsize: int, /) -> bytes:
    method sendto (line 290) | def sendto(self, bytes: AnyReadableBuf, address: _Address, /) -> int:
    method recvfrom (line 295) | def recvfrom(self, bufsize: int, /) -> tuple[bytes, Any]:
    method setsockopt (line 301) | def setsockopt(
    method settimeout (line 309) | def settimeout(self, value: float | None, /) -> None:
    method setblocking (line 343) | def setblocking(self, value: bool, /) -> None:
    method makefile (line 354) | def makefile(
    method makefile (line 375) | def makefile(self, mode: str, buffering: int = 0, /) -> Socket:
    method read (line 394) | def read(self) -> bytes:
    method read (line 403) | def read(self, size: int, /) -> bytes:
    method readinto (line 412) | def readinto(self, buf: AnyWritableBuf, /) -> int | None:
    method readinto (line 421) | def readinto(self, buf: AnyWritableBuf, nbytes: int, /) -> int | None:
    method readline (line 429) | def readline(self) -> bytes:
    method write (line 435) | def write(self, buf: AnyReadableBuf, /) -> int | None:

FILE: typehints/stdlib/ussl.pyi
  function wrap_socket (line 29) | def wrap_socket(

FILE: typehints/stdlib/ustruct.pyi
  function calcsize (line 34) | def calcsize(fmt: str | bytes, /,) -> int:
  function pack (line 39) | def pack(fmt: str | bytes, /, *v: Any) -> bytes:
  function pack_into (line 45) | def pack_into(
  function unpack (line 54) | def unpack(fmt: str | bytes, data: AnyReadableBuf, /) -> tuple[Any, ...]:
  function unpack_from (line 60) | def unpack_from(

FILE: typehints/stdlib/usys.pyi
  class Implementation (line 23) | class Implementation(tuple[str, tuple[int, int, int], int]):
  class ModuleType (line 28) | class ModuleType:
  function exit (line 32) | def exit(retval: object = 0, /) -> NoReturn:
  function atexit (line 39) | def atexit(func: Callable[[], None] | None, /) -> Callable[[], None] | N...
  function print_exception (line 53) | def print_exception(exc: BaseException, file: IOBase[str] = "stdout", /)...

FILE: typehints/stdlib/utime.pyi
  class _TicksMs (line 48) | class _TicksMs: ...
  class _TicksUs (line 49) | class _TicksUs: ...
  class _TicksCPU (line 50) | class _TicksCPU: ...
  function gmtime (line 54) | def gmtime(secs: int | None = None, /) -> tuple[int, int, int, int, int,...
  function localtime (line 75) | def localtime(
  function mktime (line 98) | def mktime(local_time: tuple[int, int, int, int, int, int, int, int], /)...
  function sleep (line 105) | def sleep(seconds: float, /) -> None:
  function sleep_ms (line 113) | def sleep_ms(ms: int, /) -> None:
  function sleep_us (line 123) | def sleep_us(us: int, /) -> None:
  function ticks_ms (line 132) | def ticks_ms() -> _TicksMs:
  function ticks_us (line 155) | def ticks_us() -> _TicksUs:
  function ticks_cpu (line 160) | def ticks_cpu() -> _TicksCPU:
  function ticks_add (line 174) | def ticks_add(ticks: _Ticks, delta: int, /) -> _Ticks:
  function ticks_diff (line 200) | def ticks_diff(ticks1: _Ticks, ticks2: _Ticks, /) -> int:
  function time (line 265) | def time() -> int:
  function time_ns (line 292) | def time_ns() -> int:

FILE: typehints/stdlib/uzlib.pyi
  function decompress (line 26) | def decompress(data: bytes, wbits: int = 0, bufsize: int = 0, /) -> bytes:
  class DecompIO (line 36) | class DecompIO(IOBase[bytes]):
    method __init__ (line 41) | def __init__(self, stream: IOBase[bytes], wbits: int = 0, /):

FILE: typehints/stdlib/zlib.pyi
  function decompress (line 26) | def decompress(data: bytes, wbits: int = 0, bufsize: int = 0, /) -> bytes:
  class DecompIO (line 36) | class DecompIO(IOBase[bytes]):
    method __init__ (line 41) | def __init__(self, stream: IOBase[bytes], wbits: int = 0, /):
Condensed preview — 121 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,050K chars).
[
  {
    "path": ".github/workflows/check.yml",
    "chars": 1058,
    "preview": "name: check\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n  schedule:\n    -   cron: '0 3 * * *'\n\n# Allow can"
  },
  {
    "path": ".gitignore",
    "chars": 121,
    "preview": "*.iml\n.idea/\n!/.idea/runConfigurations/\n.gradle/\nbuild/\nvenv/\ntmp/\n\n# IntelliJ Platform Gradle Plugin\n.intellijPlatform/"
  },
  {
    "path": "CHANGES.md",
    "chars": 6194,
    "preview": "The Changelog\n=============\n\n1.4.6 - 2024-08-28\n------------------\n\n* Support for 2024.2 IDE versions\n  ([#295](https://"
  },
  {
    "path": "LICENSE.txt",
    "chars": 11352,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "Pipfile",
    "chars": 186,
    "preview": "[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[packages]\ndocopt = \"*\"\nadafruit-ampy = \"*\"\n"
  },
  {
    "path": "README.md",
    "chars": 5438,
    "preview": "# MicroPython Plugin for PyCharm and IntelliJ\n\n[![JetBrains team project](http://jb.gg/badges/team.svg)](https://conflue"
  },
  {
    "path": "build.gradle.kts",
    "chars": 1587,
    "preview": "import org.jetbrains.kotlin.gradle.dsl.JvmTarget\nimport org.jetbrains.kotlin.gradle.dsl.KotlinVersion\nimport org.jetbrai"
  },
  {
    "path": "examples/rpsls.py",
    "chars": 3069,
    "preview": "from random import choice\nimport gc\n\nimport radio\nfrom microbit import *\n\n\nCLASSIC_STORY = \"\"\"\nScissors cuts Paper\nPaper"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 251,
    "preview": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributi"
  },
  {
    "path": "gradle.properties",
    "chars": 458,
    "preview": "version=1.4.6-2024.2\nplatformType=PC\nplatformVersion=242-EAP-SNAPSHOT\npythonPlugin=PythonCore:242.20224.300\npublishToken"
  },
  {
    "path": "gradlew",
    "chars": 8739,
    "preview": "#!/bin/sh\n\n#\n# Copyright © 2015-2021 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"Lice"
  },
  {
    "path": "gradlew.bat",
    "chars": 2966,
    "preview": "@rem\r\n@rem Copyright 2015 the original author or authors.\r\n@rem\r\n@rem Licensed under the Apache License, Version 2.0 (th"
  },
  {
    "path": "licenses/microrepl_license.txt",
    "chars": 592,
    "preview": "Copyright 2015 The Python Software Foundation (http://python.org/)\n\nLicensed under the Apache License, Version 2.0 (the "
  },
  {
    "path": "scripts/findusb.py",
    "chars": 955,
    "preview": "# Copyright 2000-2017 JetBrains s.r.o.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not"
  },
  {
    "path": "scripts/microcleanfs.py",
    "chars": 2248,
    "preview": "# Copyright 2000-2017 JetBrains s.r.o.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not"
  },
  {
    "path": "scripts/microrepl.py",
    "chars": 4020,
    "preview": "# Copyright 2015 The Python Software Foundation (http://python.org/)\n#\n# Licensed under the Apache License, Version 2.0 "
  },
  {
    "path": "scripts/microupload.py",
    "chars": 4279,
    "preview": "# Copyright 2000-2017 JetBrains s.r.o.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/actions/MicroPythonAction.kt",
    "chars": 653,
    "preview": "package com.jetbrains.micropython.actions\n\nimport com.intellij.facet.ui.ValidationResult\nimport com.intellij.openapi.act"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/actions/MicroPythonCommandAction.kt",
    "chars": 1523,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/actions/RemoveAllFilesFromDeviceAction.kt",
    "chars": 1240,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/actions/RunMicroReplAction.kt",
    "chars": 2045,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/Esp8266DeviceProvider.kt",
    "chars": 2211,
    "preview": "package com.jetbrains.micropython.devices\n\nimport com.intellij.execution.configurations.CommandLineState\nimport com.inte"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/MicroBitDeviceProvider.kt",
    "chars": 2690,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/MicroBitV2DeviceProvider.kt",
    "chars": 725,
    "preview": "package com.jetbrains.micropython.devices\n\nimport com.intellij.openapi.projectRoots.Sdk\nimport com.jetbrains.python.pack"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/MicroPythonDeviceProvider.kt",
    "chars": 2101,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/PyboardDeviceProvider.kt",
    "chars": 2589,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/devices/RPiPicoDeviceProvider.kt",
    "chars": 3013,
    "preview": "package com.jetbrains.micropython.devices\n\nimport com.intellij.execution.configurations.CommandLineState\nimport com.inte"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/inspections/MicroPythonRequirementsInspection.kt",
    "chars": 1929,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/repl/MicroPythonReplManager.kt",
    "chars": 743,
    "preview": "package com.jetbrains.micropython.repl\n\nimport com.intellij.openapi.components.Service\nimport com.intellij.openapi.proje"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/repl/StopReplBeforeRunTask.kt",
    "chars": 1680,
    "preview": "package com.jetbrains.micropython.repl\n\nimport com.intellij.execution.BeforeRunTask\nimport com.intellij.execution.Before"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/repl/ToolWindowReplTab.kt",
    "chars": 7356,
    "preview": "package com.jetbrains.micropython.repl\n\nimport com.intellij.icons.AllIcons\nimport com.intellij.ide.ActivityTracker\nimpor"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/run/MicroPythonConfigurationType.kt",
    "chars": 1990,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfiguration.kt",
    "chars": 6209,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfigurationEditor.kt",
    "chars": 2158,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/run/MicroPythonRunConfigurationProducer.kt",
    "chars": 2949,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/run/MicroUpload.kt",
    "chars": 1827,
    "preview": "package com.jetbrains.micropython.run\n\nimport com.intellij.openapi.module.Module\nimport com.intellij.openapi.project.gue"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonDevicesConfiguration.kt",
    "chars": 1158,
    "preview": "package com.jetbrains.micropython.settings\n\nimport com.intellij.openapi.components.PersistentStateComponent\nimport com.i"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacet.kt",
    "chars": 7499,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetConfiguration.kt",
    "chars": 2078,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetDetector.kt",
    "chars": 2741,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetEditorTab.kt",
    "chars": 1382,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetType.kt",
    "chars": 1898,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonModuleConfigurable.kt",
    "chars": 3279,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonProjectConfigurable.kt",
    "chars": 1114,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonSettingsPanel.kt",
    "chars": 4715,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonTypeHints.kt",
    "chars": 727,
    "preview": "/*\n * Copyright 2000-2017 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you "
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonUsbId.kt",
    "chars": 378,
    "preview": "package com.jetbrains.micropython.settings\n\n/**\n * @author vlan\n */\ndata class MicroPythonUsbId(val vendorId: Int, val p"
  },
  {
    "path": "src/main/kotlin/com/jetbrains/micropython/ui/MicroPythonToolWindowFactory.kt",
    "chars": 1088,
    "preview": "package com.jetbrains.micropython.ui\n\nimport com.intellij.openapi.components.service\nimport com.intellij.openapi.project"
  },
  {
    "path": "src/main/resources/META-INF/plugin.xml",
    "chars": 4381,
    "preview": "<idea-plugin url=\"https://github.com/JetBrains/intellij-micropython\">\n  <name>MicroPython</name>\n  <id>intellij-micropyt"
  },
  {
    "path": "src/main/resources/inspectionDescriptions/MicroPythonRequirements.html",
    "chars": 135,
    "preview": "<html>\n<body>\n<p>Detects missing Python packages that are required for communicating with your MicroPython device.\n</p>\n"
  },
  {
    "path": "typehints/esp32/esp.pyi",
    "chars": 1291,
    "preview": "from typing import Optional\nfrom typing import Final\n\nLOG_NONE: Final[int] = ...\nLOG_ERROR: Final[int] = ...\nLOG_WARN: F"
  },
  {
    "path": "typehints/esp32/esp32.pyi",
    "chars": 11854,
    "preview": "from machine import Pin\nfrom typing import Optional\nfrom typing import overload\nfrom typing import Final\n\nHEAP_DATA: Fin"
  },
  {
    "path": "typehints/esp32/network.pyi",
    "chars": 6749,
    "preview": "\"\"\"network configuration\n\nThis module provides network drivers and routing configuration. To use this\nmodule, a MicroPyt"
  },
  {
    "path": "typehints/esp8266/esp.pyi",
    "chars": 3285,
    "preview": "\nfrom typing import Optional\n\ndef sleep_type(sleep_type: Optional[int]) -> Optional[int]:\n    \"\"\"\n    Get or set the sle"
  },
  {
    "path": "typehints/esp8266/network.pyi",
    "chars": 6749,
    "preview": "\"\"\"network configuration\n\nThis module provides network drivers and routing configuration. To use this\nmodule, a MicroPyt"
  },
  {
    "path": "typehints/microbit/microbit/__init__.pyi",
    "chars": 11705,
    "preview": "\"\"\"micro:bit Micropython API\n\nEverything directly related to interacting with the hardware lives in the\n`microbit` modul"
  },
  {
    "path": "typehints/microbit/microbit/accelerometer.pyi",
    "chars": 1774,
    "preview": "\"\"\"This object gives you access to the on-board accelerometer. The accelerometer\nalso provides convenience functions for"
  },
  {
    "path": "typehints/microbit/microbit/compass.pyi",
    "chars": 1822,
    "preview": "\"\"\"This module lets you access the built-in electronic compass. Before using,\nthe compass should be calibrated, otherwis"
  },
  {
    "path": "typehints/microbit/microbit/display.pyi",
    "chars": 2923,
    "preview": "\"\"\"This module controls the 5×5 LED display on the front of your board. It can\nbe used to display images, animations and"
  },
  {
    "path": "typehints/microbit/microbit/i2c.pyi",
    "chars": 2129,
    "preview": "\"\"\"The ``i2c`` module lets you communicate with devices connected to your board\nusing the I²C bus protocol. There can be"
  },
  {
    "path": "typehints/microbit/microbit/spi.pyi",
    "chars": 2813,
    "preview": "\"\"\"The ``spi`` module lets you talk to a device connected to your board using\na serial peripheral interface (SPI) bus. S"
  },
  {
    "path": "typehints/microbit/microbit/uart.pyi",
    "chars": 3232,
    "preview": "\"\"\"The ``uart`` module lets you talk to a device connected to your board using\na serial interface.\n\"\"\"\n\nfrom . import Mi"
  },
  {
    "path": "typehints/microbit/music.pyi",
    "chars": 8725,
    "preview": "\n\n\n\"\"\"\nMicroPython on the BBC micro:bit comes with a powerful music and\nsound module. It’s very easy to generate bleeps "
  },
  {
    "path": "typehints/microbit/neopixel.pyi",
    "chars": 2604,
    "preview": "\"\"\"\nThe neopixel module lets you use Neopixel (WS2812) individually\naddressable RGB LED strips with the Microbit.\n\nNote "
  },
  {
    "path": "typehints/microbit/radio.pyi",
    "chars": 5565,
    "preview": "\"\"\"The ``radio`` module allows devices to work together via simple wireless\nnetworks.\n\nThe radio module is conceptually "
  },
  {
    "path": "typehints/microbit/speech.pyi",
    "chars": 2857,
    "preview": "\"\"\"\nSpeech\n\nWarning\n\nWARNING! THIS IS ALPHA CODE.\n\nWe reserve the right to change this API as development continues.\n\nTh"
  },
  {
    "path": "typehints/micropython/bluetooth.pyi",
    "chars": 55768,
    "preview": "\"\"\"\nLow-level Bluetooth radio functionality.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/mic"
  },
  {
    "path": "typehints/micropython/btree.pyi",
    "chars": 8754,
    "preview": "\"\"\"\nsimple BTree database.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/do"
  },
  {
    "path": "typehints/micropython/cryptolib.pyi",
    "chars": 3766,
    "preview": "\"\"\"\ncryptographic ciphers.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/do"
  },
  {
    "path": "typehints/micropython/framebuf.pyi",
    "chars": 8370,
    "preview": "\"\"\"\nFrame buffer manipulation.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/maste"
  },
  {
    "path": "typehints/micropython/machine.pyi",
    "chars": 98819,
    "preview": "\"\"\"\nfunctions related to the hardware.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyth"
  },
  {
    "path": "typehints/micropython/micropython.pyi",
    "chars": 11660,
    "preview": "\"\"\"\naccess and control MicroPython internals.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/mi"
  },
  {
    "path": "typehints/micropython/neopixel.pyi",
    "chars": 2552,
    "preview": "\"\"\"\ncontrol of WS2812 / NeoPixel LEDs.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyth"
  },
  {
    "path": "typehints/micropython/network.pyi",
    "chars": 37653,
    "preview": "\"\"\"\nnetwork configuration.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/do"
  },
  {
    "path": "typehints/micropython/ubluetooth.pyi",
    "chars": 55768,
    "preview": "\"\"\"\nLow-level Bluetooth radio functionality.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/mic"
  },
  {
    "path": "typehints/micropython/ucryptolib.pyi",
    "chars": 3766,
    "preview": "\"\"\"\ncryptographic ciphers.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/do"
  },
  {
    "path": "typehints/micropython/uctypes.pyi",
    "chars": 11686,
    "preview": "\"\"\"\naccess binary data in a structured way.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micr"
  },
  {
    "path": "typehints/pyboard/lcd160cr.pyi",
    "chars": 21848,
    "preview": "\"\"\"\ncontrol of LCD160CR display.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/mas"
  },
  {
    "path": "typehints/pyboard/pyb.pyi",
    "chars": 183791,
    "preview": "\"\"\"\nfunctions related to the board.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/"
  },
  {
    "path": "typehints/pyboard/stm.pyi",
    "chars": 7730,
    "preview": "\"\"\"\nfunctionality specific to STM32 MCUs.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/microp"
  },
  {
    "path": "typehints/rpi_pico/rp2.pyi",
    "chars": 1592,
    "preview": "\"\"\"\nRaspberry Pi Pico specific micropython support.\n\nThese methods are not fully documented and this is a best effort to"
  },
  {
    "path": "typehints/stdlib/_thread.pyi",
    "chars": 697,
    "preview": "\"\"\"\nmultithreading support.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/d"
  },
  {
    "path": "typehints/stdlib/array.pyi",
    "chars": 8365,
    "preview": "\"\"\"\nefficient arrays of numeric data.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropytho"
  },
  {
    "path": "typehints/stdlib/binascii.pyi",
    "chars": 1606,
    "preview": "\"\"\"\nbinary/ASCII conversions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master"
  },
  {
    "path": "typehints/stdlib/cmath.pyi",
    "chars": 1976,
    "preview": "\"\"\"\nmathematical functions for complex numbers.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/"
  },
  {
    "path": "typehints/stdlib/collections.pyi",
    "chars": 5828,
    "preview": "\"\"\"\ncollection and container types.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/"
  },
  {
    "path": "typehints/stdlib/errno.pyi",
    "chars": 1850,
    "preview": "\"\"\"\nsystem error codes.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  },
  {
    "path": "typehints/stdlib/gc.pyi",
    "chars": 3948,
    "preview": "\"\"\"\ncontrol the garbage collector.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/m"
  },
  {
    "path": "typehints/stdlib/hashlib.pyi",
    "chars": 3667,
    "preview": "\"\"\"\nhashing algorithms.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  },
  {
    "path": "typehints/stdlib/heapq.pyi",
    "chars": 1291,
    "preview": "\"\"\"\nheap queue algorithm.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/doc"
  },
  {
    "path": "typehints/stdlib/io.pyi",
    "chars": 18564,
    "preview": "\"\"\"\ninput/output streams.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/doc"
  },
  {
    "path": "typehints/stdlib/json.pyi",
    "chars": 1793,
    "preview": "\"\"\"\nJSON encoding and decoding.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/mast"
  },
  {
    "path": "typehints/stdlib/math.pyi",
    "chars": 5209,
    "preview": "\"\"\"\nmathematical functions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/d"
  },
  {
    "path": "typehints/stdlib/os.pyi",
    "chars": 28175,
    "preview": "\"\"\"\nbasic \"operating system\" services.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyth"
  },
  {
    "path": "typehints/stdlib/re.pyi",
    "chars": 8251,
    "preview": "\"\"\"\nregular expressions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs"
  },
  {
    "path": "typehints/stdlib/select.pyi",
    "chars": 5045,
    "preview": "\"\"\"\nwait for events on a set of streams.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropy"
  },
  {
    "path": "typehints/stdlib/socket.pyi",
    "chars": 18377,
    "preview": "\"\"\"\nsocket.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/library/sock"
  },
  {
    "path": "typehints/stdlib/ssl.pyi",
    "chars": 2703,
    "preview": "\"\"\"\nTLS/SSL wrapper for socket objects.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyt"
  },
  {
    "path": "typehints/stdlib/struct.pyi",
    "chars": 2132,
    "preview": "\"\"\"\npack and unpack primitive data types.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/microp"
  },
  {
    "path": "typehints/stdlib/sys.pyi",
    "chars": 5392,
    "preview": "\"\"\"\nsystem specific functions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/maste"
  },
  {
    "path": "typehints/stdlib/time.pyi",
    "chars": 13414,
    "preview": "\"\"\"\ntime related functions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/d"
  },
  {
    "path": "typehints/stdlib/uarray.pyi",
    "chars": 8365,
    "preview": "\"\"\"\nefficient arrays of numeric data.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropytho"
  },
  {
    "path": "typehints/stdlib/uasyncio.pyi",
    "chars": 11435,
    "preview": "\"\"\"\nasynchronous I/O scheduler for writing concurrent code.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/"
  },
  {
    "path": "typehints/stdlib/ubinascii.pyi",
    "chars": 1606,
    "preview": "\"\"\"\nbinary/ASCII conversions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master"
  },
  {
    "path": "typehints/stdlib/ucollections.pyi",
    "chars": 5828,
    "preview": "\"\"\"\ncollection and container types.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/"
  },
  {
    "path": "typehints/stdlib/uerrno.pyi",
    "chars": 1850,
    "preview": "\"\"\"\nsystem error codes.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  },
  {
    "path": "typehints/stdlib/uhashlib.pyi",
    "chars": 3667,
    "preview": "\"\"\"\nhashing algorithms.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  },
  {
    "path": "typehints/stdlib/uheapq.pyi",
    "chars": 1291,
    "preview": "\"\"\"\nheap queue algorithm.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/doc"
  },
  {
    "path": "typehints/stdlib/uio.pyi",
    "chars": 18564,
    "preview": "\"\"\"\ninput/output streams.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/doc"
  },
  {
    "path": "typehints/stdlib/ujson.pyi",
    "chars": 1793,
    "preview": "\"\"\"\nJSON encoding and decoding.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/mast"
  },
  {
    "path": "typehints/stdlib/uos.pyi",
    "chars": 28175,
    "preview": "\"\"\"\nbasic \"operating system\" services.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyth"
  },
  {
    "path": "typehints/stdlib/ure.pyi",
    "chars": 8251,
    "preview": "\"\"\"\nregular expressions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs"
  },
  {
    "path": "typehints/stdlib/uselect.pyi",
    "chars": 5045,
    "preview": "\"\"\"\nwait for events on a set of streams.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropy"
  },
  {
    "path": "typehints/stdlib/usocket.pyi",
    "chars": 18377,
    "preview": "\"\"\"\nsocket.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/library/sock"
  },
  {
    "path": "typehints/stdlib/ussl.pyi",
    "chars": 2703,
    "preview": "\"\"\"\nTLS/SSL wrapper for socket objects.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropyt"
  },
  {
    "path": "typehints/stdlib/ustruct.pyi",
    "chars": 2132,
    "preview": "\"\"\"\npack and unpack primitive data types.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/microp"
  },
  {
    "path": "typehints/stdlib/usys.pyi",
    "chars": 5392,
    "preview": "\"\"\"\nsystem specific functions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/maste"
  },
  {
    "path": "typehints/stdlib/utime.pyi",
    "chars": 13414,
    "preview": "\"\"\"\ntime related functions.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/d"
  },
  {
    "path": "typehints/stdlib/uzlib.pyi",
    "chars": 2059,
    "preview": "\"\"\"\nzlib decompression.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  },
  {
    "path": "typehints/stdlib/zlib.pyi",
    "chars": 2059,
    "preview": "\"\"\"\nzlib decompression.\n\nDescriptions taken from:\nhttps://raw.githubusercontent.com/micropython/micropython/master/docs/"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the JetBrains/intellij-micropython GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 121 files (978.1 KB), approximately 245.6k tokens, and a symbol index with 1409 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!